diff --git a/CHANGELOG.md b/CHANGELOG.md index 23e4fc8..3df5f4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ Formato baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versões seguem SemVer. +## [0.2.0] - 2026-10-18 + +### Adicionado +- **Pré-visualização completa:** imagem (zoom), vídeo (MP4 e outros), áudio, PDF (pdf.js incluso, funciona offline), texto, Word/Excel/PowerPoint/OpenDocument, conteúdo de ZIP e hexadecimal; tela cheia com navegação por teclado (↑ ↓ ← → Espaço Esc). O conteúdo é lido sob demanda com suporte a Range, sem gravar em disco. +- Seletor de tema **Auto / Claro / Escuro**; a escolha é salva e vale também no app reiniciado como administrador. +- Nova identidade visual em verde-azulado, com logo de pixels que se juntam até formar um lobo-guará. + +### Corrigido +- Reiniciar como administrador no Linux: no AppImage o executável fica num ponto de montagem inacessível ao root; agora usa o próprio `.AppImage`, mostra o motivo se falhar e fecha o app antigo só quando o novo abre. +- Barra de ações inferior piscava a cada atualização; agora é criada uma vez e só atualiza o texto. O painel de progresso também deixou de ser recriado a cada ciclo. +- FAT32 em mídias pequenas (menos de 65 525 clusters) não era reconhecido. +- O tema não acompanhava a escolha ao abrir como root (o WebView do root usava outro tema do sistema). + ## [0.1.0] - 2026-10-18 ### Adicionado diff --git a/Cargo.lock b/Cargo.lock index 47262bf..d110d5a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -248,7 +248,7 @@ dependencies = [ [[package]] name = "guara-cli" -version = "0.1.0" +version = "0.2.0" dependencies = [ "clap", "ctrlc", @@ -260,7 +260,7 @@ dependencies = [ [[package]] name = "guara-core" -version = "0.1.0" +version = "0.2.0" dependencies = [ "libc", "serde", diff --git a/Cargo.toml b/Cargo.toml index 5ebb7ce..4cc871c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "2" members = ["crates/guara-core", "crates/guara-cli"] [workspace.package] -version = "0.1.0" +version = "0.2.0" edition = "2021" license = "MIT OR Apache-2.0" repository = "https://github.com/lucasrguerra/guara" diff --git a/README.md b/README.md index c7074cb..cdb8857 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -

Guará

+

Guará

Guará

Recuperação de arquivos livre e gratuita para HD, SSD e pendrive.
Terminal e interface gráfica · Windows, Linux e macOS · somente leitura na origem.

@@ -55,7 +55,9 @@ guara ui # interface no navegador (127.0.0.1 + t ## Interface gráfica -App desktop (Tauri) com barra lateral de dispositivos, mapa do disco, resultados ao vivo, filtros por tipo, busca, pré-visualização de imagens, confiança por arquivo, pausar/continuar e salvar sessão. Tema claro/escuro automático e layout responsivo. O mesmo front-end roda em `guara ui`. +App desktop (Tauri) com barra lateral de dispositivos, mapa do disco, resultados ao vivo, filtros por tipo, busca, confiança por arquivo, pausar/continuar e salvar sessão. Tema **Auto / Claro / Escuro** à sua escolha (lembrado também ao reiniciar como administrador) e layout responsivo. O mesmo front-end roda em `guara ui`. + +**Pré-visualização antes de recuperar** (lida direto do disco, sem gravar nada): imagens (com zoom), **vídeo (MP4/MOV/WebM)** e áudio com player, **PDF** (página a página), texto, documentos Word/Excel/PowerPoint/OpenDocument (texto extraído), conteúdo de ZIP e visão hexadecimal para o resto. Use ↑/↓ para percorrer a lista, Espaço/Enter ou duplo clique para abrir em tela cheia. Quando um arquivo não abre, o aviso ajuda a julgar se ele está danificado. A reprodução de vídeo depende dos codecs do seu sistema (no Linux, instale os plugins `gstreamer1.0-libav` e `gstreamer1.0-plugins-good`). ## Limites conhecidos (v0.1) diff --git a/apps/gui/src-tauri/Cargo.toml b/apps/gui/src-tauri/Cargo.toml index b59a2f1..ee04140 100644 --- a/apps/gui/src-tauri/Cargo.toml +++ b/apps/gui/src-tauri/Cargo.toml @@ -3,7 +3,7 @@ [package] name = "guara-gui" description = "Guará: interface gráfica de recuperação de arquivos" -version = "0.1.0" +version = "0.2.0" edition = "2021" license = "MIT OR Apache-2.0" repository = "https://github.com/lucasrguerra/guara" @@ -20,6 +20,9 @@ tauri-plugin-dialog = "2" serde_json = "1" guara-core = { path = "../../../crates/guara-core" } +[target.'cfg(unix)'.dependencies] +libc = "0.2" + [profile.release] lto = "thin" codegen-units = 1 diff --git a/apps/gui/src-tauri/icons/128x128.png b/apps/gui/src-tauri/icons/128x128.png index b5f3037..98e2dc6 100644 Binary files a/apps/gui/src-tauri/icons/128x128.png and b/apps/gui/src-tauri/icons/128x128.png differ diff --git a/apps/gui/src-tauri/icons/128x128@2x.png b/apps/gui/src-tauri/icons/128x128@2x.png index 21850a2..d1768e8 100644 Binary files a/apps/gui/src-tauri/icons/128x128@2x.png and b/apps/gui/src-tauri/icons/128x128@2x.png differ diff --git a/apps/gui/src-tauri/icons/32x32.png b/apps/gui/src-tauri/icons/32x32.png index 0b3fe10..aae93ae 100644 Binary files a/apps/gui/src-tauri/icons/32x32.png and b/apps/gui/src-tauri/icons/32x32.png differ diff --git a/apps/gui/src-tauri/icons/icon.ico b/apps/gui/src-tauri/icons/icon.ico index cf03709..297ce64 100644 Binary files a/apps/gui/src-tauri/icons/icon.ico and b/apps/gui/src-tauri/icons/icon.ico differ diff --git a/apps/gui/src-tauri/icons/icon.png b/apps/gui/src-tauri/icons/icon.png index ae2a8d4..025426f 100644 Binary files a/apps/gui/src-tauri/icons/icon.png and b/apps/gui/src-tauri/icons/icon.png differ diff --git a/apps/gui/src-tauri/icons/source.png b/apps/gui/src-tauri/icons/source.png index ae2a8d4..025426f 100644 Binary files a/apps/gui/src-tauri/icons/source.png and b/apps/gui/src-tauri/icons/source.png differ diff --git a/apps/gui/src-tauri/src/main.rs b/apps/gui/src-tauri/src/main.rs index 1b39114..63b8219 100644 --- a/apps/gui/src-tauri/src/main.rs +++ b/apps/gui/src-tauri/src/main.rs @@ -16,40 +16,144 @@ async fn rpc(state: tauri::State<'_, State>, method: String, params: serde_json: } /// Reabre o app com privilégios de administrador (Linux/macOS). No Windows o -/// manifesto já exige elevação. +/// manifesto já exige elevação. O app novo encerra este quando abre; se a +/// autorização falhar, a janela continua aqui e a interface mostra o motivo. #[tauri::command] -fn relaunch_elevated() -> Result<(), String> { - let exe = std::env::current_exe().map_err(|e| e.to_string())?; - #[cfg(target_os = "linux")] +fn relaunch_elevated(app: tauri::AppHandle) -> Result<(), String> { + #[cfg(any(target_os = "linux", target_os = "macos"))] { - let mut cmd = std::process::Command::new("pkexec"); - cmd.arg("env"); - for k in ["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS"] { - if let Ok(v) = std::env::var(k) { - cmd.arg(format!("{k}={v}")); + use tauri::Emitter; + let exe = elevated_exe()?; + let cfg = guara_core::settings::config_dir(); + let log = std::env::temp_dir().join(format!("guara-elevate-{}.log", std::process::id())); + let _ = std::fs::write(&log, b""); + let out = std::fs::OpenOptions::new().append(true).open(&log).map_err(|e| e.to_string())?; + let err = out.try_clone().map_err(|e| e.to_string())?; + let pid = std::process::id().to_string(); + + #[cfg(target_os = "linux")] + let mut cmd = { + let mut c = std::process::Command::new("pkexec"); + c.arg("/usr/bin/env"); + for k in ["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "GDK_BACKEND"] { + if let Ok(v) = std::env::var(k) { + c.arg(format!("{k}={v}")); + } } - } - cmd.arg(exe); - cmd.spawn().map_err(|e| format!("pkexec indisponível: {e}"))?; - std::process::exit(0); - } - #[cfg(target_os = "macos")] - { - let script = format!("do shell script \"'{}' &> /dev/null &\" with administrator privileges", exe.display()); - std::process::Command::new("osascript").args(["-e", &script]).spawn().map_err(|e| e.to_string())?; - std::process::exit(0); + c.arg(format!("GUARA_CONFIG_DIR={}", cfg.display())); + c.arg(format!("GUARA_REPLACE_PID={pid}")); + c.arg(&exe); + c + }; + #[cfg(target_os = "macos")] + let mut cmd = { + let shell = format!( + "GUARA_CONFIG_DIR='{}' GUARA_REPLACE_PID={} '{}' >/dev/null 2>&1 &", + cfg.display(), + pid, + exe.display() + ); + let script = format!("do shell script \"{}\" with administrator privileges", shell.replace('\\', "\\\\").replace('"', "\\\"")); + let mut c = std::process::Command::new("osascript"); + c.args(["-e", &script]); + c + }; + cmd.stdout(out).stderr(err); + let mut child = cmd.spawn().map_err(|e| format!("não foi possível pedir privilégios: {e}"))?; + std::thread::spawn(move || { + // No Linux o pkexec só termina com sucesso quando o app elevado é fechado (e o app + // elevado já terá encerrado este processo). Qualquer falha antes disso vira aviso. + let status = child.wait(); + if matches!(&status, Ok(s) if s.success()) { + let _ = std::fs::remove_file(&log); + return; + } + let detail = std::fs::read_to_string(&log).unwrap_or_default(); + let msg = match status.ok().and_then(|s| s.code()) { + Some(126) => "Autorização cancelada.".to_string(), + Some(127) => "Não foi possível autenticar como administrador.".to_string(), + _ => format!("Não foi possível reiniciar como administrador. {}", detail.lines().last().unwrap_or("").trim()), + }; + let _ = app.emit("elevate-failed", msg); + let _ = std::fs::remove_file(&log); + }); + Ok(()) } #[cfg(windows)] { - let _ = exe; + let _ = app; Err("o Guará já roda como administrador no Windows".into()) } } +/// Caminho que o root consegue executar. No AppImage, `current_exe` aponta para +/// dentro de um ponto de montagem FUSE do usuário, inacessível ao root: usa o +/// próprio arquivo `.AppImage` (variável `APPIMAGE`). +#[cfg(any(target_os = "linux", target_os = "macos"))] +fn elevated_exe() -> Result { + if let Some(p) = std::env::var_os("APPIMAGE").map(std::path::PathBuf::from).filter(|p| p.is_file()) { + return Ok(p); + } + std::env::current_exe().map_err(|e| e.to_string()) +} + +/// Serve os arquivos recuperados para pré-visualização (`guara://localhost/file//`), +/// com suporte a Range para vídeo/áudio/PDF, lendo direto da origem. +fn serve_file(eng: &Engine, req: &tauri::http::Request>) -> tauri::http::Response> { + use tauri::http::Response; + const CAP: u64 = 8 * 1024 * 1024; + let mut it = req.uri().path().trim_start_matches("/file/").split('/'); + let (job, id) = (it.next().unwrap_or(""), it.next().and_then(|s| s.parse::().ok())); + let err = |code: u16| Response::builder().status(code).header("Access-Control-Allow-Origin", "*").body(Vec::new()).unwrap(); + let Some(id) = id else { return err(400) }; + let range = req.headers().get("range").and_then(|v| v.to_str().ok()); + let slice = match eng.file_slice(job, id, range) { + Ok(s) => s, + Err(code) => return err(code), + }; + let total = slice.total; + let start = slice.start; + let want = slice.len(); + let mut headers = slice.headers(); + let partial = slice.partial || want > CAP; + let Ok(data) = slice.read_all(CAP) else { return err(500) }; + let mut b = Response::builder().status(if partial { 206 } else { 200 }); + headers.retain(|(k, _)| *k != "Content-Range"); + for (k, v) in &headers { + b = b.header(*k, v); + } + if partial && !data.is_empty() { + b = b.header("Content-Range", format!("bytes {}-{}/{}", start, start + data.len() as u64 - 1, total)); + } + b.body(data).unwrap_or_else(|_| err(500)) +} + fn main() { + let engine = Arc::new(Engine::new()); + let for_protocol = engine.clone(); tauri::Builder::default() .plugin(tauri_plugin_dialog::init()) - .manage(State(Arc::new(Engine::new()))) + .manage(State(engine)) + .register_asynchronous_uri_scheme_protocol("guara", move |_ctx, request, responder| { + let eng = for_protocol.clone(); + std::thread::spawn(move || responder.respond(serve_file(&eng, &request))); + }) + .setup(|_app| { + // Quando abrimos elevados a pedido do app normal, ele fecha o app antigo. + #[cfg(unix)] + if let Some(pid) = std::env::var("GUARA_REPLACE_PID").ok().and_then(|p| p.parse::().ok()) { + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(1200)); + // SAFETY: só envia SIGTERM ao processo anterior do próprio usuário. + unsafe { + if libc::geteuid() == 0 { + libc::kill(pid, libc::SIGTERM); + } + } + }); + } + Ok(()) + }) .invoke_handler(tauri::generate_handler![rpc, relaunch_elevated]) .run(tauri::generate_context!()) .expect("erro ao iniciar o Guará"); diff --git a/apps/gui/src-tauri/tauri.conf.json b/apps/gui/src-tauri/tauri.conf.json index f8365a5..d828477 100644 --- a/apps/gui/src-tauri/tauri.conf.json +++ b/apps/gui/src-tauri/tauri.conf.json @@ -1,9 +1,11 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Guara", - "version": "0.1.0", + "version": "0.2.0", "identifier": "dev.guara.app", - "build": { "frontendDist": "../ui" }, + "build": { + "frontendDist": "../ui" + }, "app": { "withGlobalTauri": true, "windows": [ @@ -16,7 +18,9 @@ "resizable": true } ], - "security": { "csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'" } + "security": { + "csp": "default-src 'self'; img-src 'self' data: blob: guara: http://guara.localhost; media-src 'self' blob: guara: http://guara.localhost; connect-src 'self' ipc: http://ipc.localhost guara: http://guara.localhost; style-src 'self' 'unsafe-inline'; script-src 'self'; worker-src 'self' blob:; frame-src 'none'; object-src 'none'" + } }, "bundle": { "active": true, @@ -24,6 +28,12 @@ "category": "Utility", "shortDescription": "Recuperação de arquivos", "longDescription": "Guará recupera arquivos apagados e partições perdidas de HD, SSD e pendrive, sempre em modo somente leitura na origem.", - "icon": ["icons/32x32.png", "icons/128x128.png", "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.ico"] + "icon": [ + "icons/32x32.png", + "icons/128x128.png", + "icons/128x128@2x.png", + "icons/icon.icns", + "icons/icon.ico" + ] } } diff --git a/apps/gui/ui/app.css b/apps/gui/ui/app.css index 70f6d37..cf17ae3 100644 --- a/apps/gui/ui/app.css +++ b/apps/gui/ui/app.css @@ -7,10 +7,10 @@ --text-2: #6e6e73; --text-3: #8e8e93; --line: rgba(0, 0, 0, 0.09); - --accent: #d9541e; - --accent-2: #ff8a3d; + --accent: #0f766e; + --accent-2: #14b8a6; --accent-ink: #ffffff; - --accent-soft: rgba(217, 84, 30, 0.1); + --accent-soft: rgba(15, 118, 110, 0.11); --ok: #1a8f3c; --warn: #b26a00; --bad: #d12b2b; @@ -34,10 +34,10 @@ --text-2: #a1a1a6; --text-3: #7d7d82; --line: rgba(255, 255, 255, 0.1); - --accent: #ff7a3d; - --accent-2: #ff9d5c; - --accent-ink: #1a0b03; - --accent-soft: rgba(255, 122, 61, 0.15); + --accent: #2dd4bf; + --accent-2: #5eead4; + --accent-ink: #042f2e; + --accent-soft: rgba(45, 212, 191, 0.15); --ok: #32d74b; --warn: #ffb340; --bad: #ff6961; @@ -48,6 +48,32 @@ } } +:root[data-theme="dark"] { + --bg: #000000; + --surface: #1c1c1e; + --surface-2: #232326; + --side: rgba(28, 28, 30, 0.8); + --text: #f5f5f7; + --text-2: #a1a1a6; + --text-3: #7d7d82; + --line: rgba(255, 255, 255, 0.1); + --accent: #2dd4bf; + --accent-2: #5eead4; + --accent-ink: #042f2e; + --accent-soft: rgba(45, 212, 191, 0.15); + --ok: #32d74b; + --warn: #ffb340; + --bad: #ff6961; + --ok-soft: rgba(50, 215, 75, 0.15); + --warn-soft: rgba(255, 179, 64, 0.15); + --bad-soft: rgba(255, 105, 97, 0.15); + --shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.4); +} + +:root { color-scheme: light dark; } +:root[data-theme="light"] { color-scheme: light; } +:root[data-theme="dark"] { color-scheme: dark; } + * { box-sizing: border-box; } html, body { height: 100%; } body { @@ -211,7 +237,8 @@ input[type="checkbox"] { accent-color: var(--accent); width: 17px; height: 17px; .kv { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; font-size: 13.5px; } .kv dt { color: var(--text-3); } .kv dd { margin: 0; overflow-wrap: anywhere; } -.actionbar { position: fixed; left: var(--side-w); right: 0; bottom: 0; padding: 14px 24px calc(14px + env(safe-area-inset-bottom)); display: flex; gap: 12px; align-items: center; justify-content: center; background: var(--side); backdrop-filter: saturate(180%) blur(24px); -webkit-backdrop-filter: saturate(180%) blur(24px); border-top: 1px solid var(--line); z-index: 5; animation: rise .3s; } +.actionbar { position: fixed; left: var(--side-w); right: 0; bottom: 0; padding: 14px 24px calc(14px + env(safe-area-inset-bottom)); display: flex; gap: 12px; align-items: center; justify-content: center; background: var(--side); backdrop-filter: saturate(180%) blur(24px); -webkit-backdrop-filter: saturate(180%) blur(24px); border-top: 1px solid var(--line); z-index: 5; } +.actionbar.enter { animation: rise .3s; } .actionbar .info { color: var(--text-2); font-size: 14px; } dialog { border: 0; border-radius: 22px; padding: 26px; width: min(520px, calc(100vw - 32px)); background: var(--surface); color: var(--text); box-shadow: 0 30px 80px rgba(0, 0, 0, .35); } @@ -255,3 +282,53 @@ code, .mono { overflow-wrap: anywhere; font-family: var(--mono); font-size: .92e @media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; } } + +/* ------------------------------------------------------------ tema */ +.theme-switch { display: inline-flex; padding: 2px; border-radius: 999px; background: color-mix(in srgb, var(--text) 8%, transparent); } +.theme-switch button { border: 0; background: transparent; cursor: pointer; padding: 4px 10px; border-radius: 999px; font-size: 12px; color: var(--text-2); } +.theme-switch button[aria-pressed="true"] { background: var(--surface); color: var(--text); box-shadow: 0 1px 3px rgba(0, 0, 0, .18); font-weight: 600; } + +/* ------------------------------------------------------------ pré-visualização */ +.viewer { position: relative; min-height: 160px; max-height: 52vh; overflow: auto; border-radius: 12px; background: var(--surface-2); box-shadow: inset 0 0 0 1px var(--line); display: flex; flex-direction: column; align-items: center; } +.viewer.large { max-height: none; height: 100%; min-height: 0; } +.viewer > * { max-width: 100%; } +.pv-img { display: block; max-width: 100%; max-height: 46vh; object-fit: contain; margin: auto; } +.viewer.large .pv-img { max-height: 100%; } +.viewer.zoomable .pv-img { cursor: zoom-in; } +.viewer.actual .pv-img { max-width: none; max-height: none; cursor: zoom-out; } +.viewer.actual { align-items: flex-start; } +.pv-video { width: 100%; max-height: 46vh; background: #000; border-radius: 12px; } +.viewer.large .pv-video { max-height: 100%; height: 100%; } +.pv-audio { width: calc(100% - 24px); margin: auto 12px; } +.pv-note { width: 100%; padding: 8px 12px; font-size: 12.5px; color: var(--text-2); text-align: center; } +.pv-note.bad { text-align: left; color: var(--text); background: var(--warn-soft); border-radius: 10px; margin: 8px; width: calc(100% - 16px); font-size: 13.5px; } +.pv-loading { height: 160px; display: grid; place-items: center; width: 100%; } +.pv-loading i { width: 26px; height: 26px; border-radius: 50%; border: 3px solid var(--line); border-top-color: var(--accent); animation: spin .8s linear infinite; } +@keyframes spin { to { transform: rotate(360deg); } } +.pv-text, .pv-hex { margin: 0; padding: 12px 14px; width: 100%; font: 12.5px/1.5 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; color: var(--text); text-align: left; } +.pv-hex { white-space: pre; overflow-x: auto; overflow-wrap: normal; font-size: 12px; } +.pv-hex .o { color: var(--text-3); } .pv-hex .a { color: var(--accent); } +.pv-page { width: 100%; background: var(--surface); padding: 18px 22px; font-family: Georgia, "Times New Roman", serif; font-size: 14px; line-height: 1.6; text-align: left; } +.pv-page p { margin: 0 0 .8em; white-space: pre-wrap; } .pv-page h4 { margin: 1em 0 .4em; font-family: var(--font); font-size: 16px; } +.pv-sheet { width: 100%; overflow: auto; text-align: left; } +.pv-sheet table { border-collapse: collapse; font-size: 12.5px; min-width: 100%; } +.pv-sheet th, .pv-sheet td { border: 1px solid var(--line); padding: 4px 8px; white-space: nowrap; max-width: 240px; overflow: hidden; text-overflow: ellipsis; } +.pv-sheet th { background: var(--surface); color: var(--text-3); font-weight: 500; position: sticky; top: 0; } +.pv-slide { width: calc(100% - 20px); margin: 10px; padding: 14px 16px; background: var(--surface); border-radius: 10px; box-shadow: 0 0 0 1px var(--line); text-align: left; } +.pv-slide small { color: var(--text-3); } .pv-slide h4 { margin: 4px 0 6px; font-size: 16px; } .pv-slide p { margin: 0 0 4px; font-size: 13.5px; } +.pv-zip { list-style: none; margin: 0; padding: 4px 0; width: 100%; text-align: left; font-size: 13px; } +.pv-zip li { display: flex; justify-content: space-between; gap: 12px; padding: 5px 14px; border-bottom: 1px solid var(--line); } +.pv-zip li span { overflow-wrap: anywhere; } .pv-zip small { color: var(--text-3); flex: none; } +.pv-pdfbar { position: sticky; top: 0; z-index: 2; display: flex; gap: 10px; align-items: center; justify-content: center; padding: 6px; width: 100%; background: var(--side); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); } +.pv-pdfbar .pg { font-size: 13px; color: var(--text-2); min-width: 110px; text-align: center; } +.pv-pdfwrap { padding: 8px; } .pv-canvas { display: block; background: #fff; box-shadow: 0 2px 14px rgba(0, 0, 0, .25); } + +dialog.lightbox { width: min(1180px, 96vw); height: min(90vh, 920px); padding: 0; display: none; grid-template-rows: auto minmax(0, 1fr) auto; overflow: hidden; } +dialog.lightbox[open] { display: grid; } +.lb-head, .lb-foot { display: flex; gap: 12px; align-items: center; padding: 12px 16px; } +.lb-head { border-bottom: 1px solid var(--line); } .lb-foot { border-top: 1px solid var(--line); flex-wrap: wrap; justify-content: space-between; } +.lb-head .ttl { flex: 1; min-width: 0; } .lb-head .ttl b { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .lb-head .ttl small { color: var(--text-2); } +.lb-body { padding: 12px; min-height: 0; } + +.hero-logo { width: min(440px, 80%); height: auto; display: block; margin: 0 0 22px -4px; } +.pill.accent { background: var(--accent-soft); color: var(--accent); } diff --git a/apps/gui/ui/app.js b/apps/gui/ui/app.js index 00b26b7..71ab29a 100644 --- a/apps/gui/ui/app.js +++ b/apps/gui/ui/app.js @@ -1,6 +1,8 @@ // Guará — interface. Fala com o núcleo por `rpc(método, parâmetros)`: // • app Tauri: invoke('rpc') • modo `guara ui`: POST /rpc/ com token. +import { renderPreview, kindOf, KIND_LABEL } from './preview.js'; + const tauri = window.__TAURI__; const params = new URLSearchParams(location.search); let token = params.get('token'); @@ -21,6 +23,32 @@ async function rpc(method, p = {}) { return body; } +const isWin = /Windows/i.test(navigator.userAgent); +const fileBase = tauri ? (isWin ? 'http://guara.localhost' : 'guara://localhost') : ''; +const fileUrl = (job, id) => `${fileBase}/file/${job}/${id}` + (tauri ? '' : `?t=${encodeURIComponent(token || '')}`); + +// Atualiza o HTML só quando mudou (evita piscar e perder o foco/hover). +function setHTML(el, html) { + if (!el || el._h === html) return false; + el._h = html; + el.innerHTML = html; + return true; +} + +// ------------------------------------------------------------------ tema +function applyTheme(t) { + const root = document.documentElement; + if (t === 'light' || t === 'dark') root.dataset.theme = t; else delete root.dataset.theme; + document.querySelectorAll('[data-theme-pick]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.themePick === (t || 'auto')))); +} +try { applyTheme(localStorage.getItem('guara-theme') || 'auto'); } catch { applyTheme('auto'); } +document.querySelectorAll('[data-theme-pick]').forEach((b) => (b.onclick = async () => { + const t = b.dataset.themePick; + applyTheme(t); + try { localStorage.setItem('guara-theme', t); } catch { /* sem armazenamento */ } + try { await rpc('settings_set', { theme: t }); } catch { /* segue só com o armazenamento local */ } +})); + // ------------------------------------------------------------------ utilidades const $ = (s, el = document) => el.querySelector(s); const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); @@ -173,7 +201,7 @@ function renderHome() { S.device = null; S.job = null; renderSide(); main.innerHTML = `
-

Encontre o que você achou que tinha perdido.

+

Encontre o que você achou que tinha perdido.

Escolha um disco, SSD ou pendrive ao lado. O Guará lê tudo — arquivos apagados, partições perdidas e espaço não particionado — sem escrever nada no disco de origem.

Uma varredura, tudo junto

Metadados do sistema de arquivos e busca por assinatura na mesma passada, sem duplicatas.

@@ -348,10 +376,13 @@ function renderScan() {
`; $('#backBtn').onclick = () => (S.device ? openDevice(S.device) : renderHome()); + $('#progressArea').onclick = onProgressClick; + $('#chips').onclick = (e) => { const c = e.target.closest('.chip'); if (c) { S.filters.category = c.dataset.c || null; resetSel(); tick(); } }; let t; $('#q').oninput = (e) => { clearTimeout(t); t = setTimeout(() => { S.filters.query = e.target.value; resetSel(); tick(); }, 250); }; $('#conf').onchange = (e) => { S.filters.minConfidence = e.target.value || null; resetSel(); tick(); }; $('#sort').onchange = (e) => { S.filters.sort = e.target.value; tick(); }; + wireTable(); paintPreview(); } const resetSel = () => { S.selected = new Set(); S.allFiltered = false; }; @@ -366,10 +397,10 @@ function paintStatus() { $('#scanSub').innerHTML = `${esc(st.target)}`; const rate = p.total && st.elapsed > 1 && p.done ? p.done / st.elapsed : 0; const eta = rate && running ? dur((p.total - p.done) / rate) : null; - $('#progressArea').innerHTML = `
+ setHTML($('#progressArea'), `
${esc(p.phase || (running ? 'Iniciando' : ''))}${pct != null ? ` · ${pct}%` : ''}
-
${running ? '' : st.status === 'paused' ? '' : ''} - ${!running && st.found ? '' : ''}
+
${running ? '' : st.status === 'paused' ? '' : ''} + ${!running && st.found ? '' : ''}
${st.found.toLocaleString('pt-BR')}arquivos encontrados
@@ -377,86 +408,151 @@ function paintStatus() {
${st.confidence.high}confiança alta
${st.confidence.medium}média
${st.confidence.low}baixa
-
`; - $('#pauseBtn')?.addEventListener('click', async () => { await rpc('scan_pause', { job: S.job }); toast('Pausando…'); }); - $('#stopBtn')?.addEventListener('click', async () => { await rpc('scan_stop', { job: S.job }); }); - $('#resumeBtn')?.addEventListener('click', async () => { await rpc('scan_resume', { job: S.job }); stopPoll(); S.poll = setInterval(tick, 500); tick(); }); - $('#saveBtn')?.addEventListener('click', async () => { - const path = await ask({ title: 'Salvar sessão', text: 'Guarda os resultados para recuperar depois, sem varrer de novo.', value: (S.defaults.home || '') + (S.defaults.sep || '/') + 'guara-sessao.json', ok: 'Salvar' }); - if (path) { try { await rpc('session_save', { job: S.job, path }); toast('Sessão salva'); } catch (e) { toast(e.message); } } - }); - $('#warnArea').innerHTML = (st.warnings || []).map((w) => `
${warnSvg}
${esc(w)}
`).join('') - + (st.error ? `
${warnSvg}
${esc(st.error)}
` : ''); +
`); + setHTML($('#warnArea'), (st.warnings || []).map((w) => `
${warnSvg}
${esc(w)}
`).join('') + + (st.error ? `
${warnSvg}
${esc(st.error)}
` : '')); // chips const total = st.found; - $('#chips').innerHTML = [``] - .concat(CATS.filter(([k]) => st.categories[k]).map(([k, n]) => ``)).join(''); - $('#chips').querySelectorAll('.chip').forEach((c) => (c.onclick = () => { S.filters.category = c.dataset.c || null; resetSel(); tick(); })); + setHTML($('#chips'), [``] + .concat(CATS.filter(([k]) => st.categories[k]).map(([k, n]) => ``)).join('')); const sel = $('#conf'); if (sel && sel.value !== (S.filters.minConfidence || '')) sel.value = S.filters.minConfidence || ''; paintBar(); } +async function onProgressClick(e) { + const act = e.target.closest('[data-act]')?.dataset.act; + if (!act) return; + if (act === 'pause') { await rpc('scan_pause', { job: S.job }); toast('Pausando…'); } + else if (act === 'stop') await rpc('scan_stop', { job: S.job }); + else if (act === 'resume') { await rpc('scan_resume', { job: S.job }); stopPoll(); S.poll = setInterval(tick, 500); tick(); } + else if (act === 'save') { + const path = await ask({ title: 'Salvar sessão', text: 'Guarda os resultados para recuperar depois, sem varrer de novo.', value: (S.defaults.home || '') + (S.defaults.sep || '/') + 'guara-sessao.json', ok: 'Salvar' }); + if (path) { try { await rpc('session_save', { job: S.job, path }); toast('Sessão salva'); } catch (err) { toast(err.message); } } + } +} + +function rowHtml(i) { + const [cl, cc] = CONF[i.confidence]; + const on = S.allFiltered || S.selected.has(i.id); + return `
+ +
${esc(i.name)}${esc(i.dir || (i.origin === 'carved' ? 'Encontrado por assinatura' : '—'))}
+
${human(i.size)}
${i.origin === 'carved' ? 'assinatura' : esc(i.origin)}
+
${cl}
`; +} + function paintList() { const el = $('#table'); if (!el) return; const st = S.status; if (!S.items.length) { - el.innerHTML = `

${st && st.status === 'running' ? 'Procurando…' : 'Nada por aqui'}

${st && st.status === 'running' ? 'Os arquivos aparecem aqui assim que são encontrados.' : (S.filters.category || S.filters.query || S.filters.minConfidence) ? 'Nenhum arquivo combina com os filtros.' : 'Não encontramos arquivos recuperáveis neste disco.'}

`; + setHTML(el, `

${st && st.status === 'running' ? 'Procurando…' : 'Nada por aqui'}

${st && st.status === 'running' ? 'Os arquivos aparecem aqui assim que são encontrados.' : (S.filters.category || S.filters.query || S.filters.minConfidence) ? 'Nenhum arquivo combina com os filtros.' : 'Não encontramos arquivos recuperáveis neste disco.'}

`); + paintBar(); return; } const allSel = S.items.every((i) => S.selected.has(i.id)) || S.allFiltered; - el.innerHTML = `
NomeTamanhoOrigemConfiança
` - + S.items.map((i) => { - const [cl, cc] = CONF[i.confidence]; - const on = S.allFiltered || S.selected.has(i.id); - return `
- -
${esc(i.name)}${esc(i.dir || (i.origin === 'carved' ? 'Encontrado por assinatura' : '—'))}
-
${human(i.size)}
${i.origin === 'carved' ? 'assinatura' : esc(i.origin)}
-
${cl}
`; - }).join('') - + (S.items.length < S.total ? `
` : ''); - $('#selAll').onchange = (e) => { - if (e.target.checked) S.items.forEach((i) => S.selected.add(i.id)); else resetSel(); - paintList(); paintBar(); - }; - el.querySelectorAll('.tr').forEach((row) => { - const id = +row.dataset.id; - const cb = $('input', row); - cb.onclick = (e) => { e.stopPropagation(); if (S.allFiltered) { S.allFiltered = false; S.items.forEach((i) => S.selected.add(i.id)); } cb.checked ? S.selected.add(id) : S.selected.delete(id); paintBar(); row.setAttribute('aria-selected', cb.checked); }; - row.onclick = () => focusItem(S.items.find((i) => i.id === id)); - row.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); focusItem(S.items.find((i) => i.id === id)); } }; - }); - $('#moreBtn')?.addEventListener('click', () => loadResults(false)); + setHTML(el, `
NomeTamanhoOrigemConfiança
` + + S.items.map(rowHtml).join('') + + (S.items.length < S.total ? `
` : '')); paintBar(); } -async function focusItem(item) { +// Eventos da tabela por delegação (o HTML é recriado, o listener não). +function wireTable() { + const el = $('#table'); + el.addEventListener('click', (e) => { + if (e.target.id === 'moreBtn') return loadResults(false); + const row = e.target.closest('.tr'); + if (e.target.id === 'selAll') { + if (e.target.checked) S.items.forEach((i) => S.selected.add(i.id)); else resetSel(); + el._h = null; paintList(); + return; + } + if (!row) return; + const id = +row.dataset.id; + if (e.target.matches('input[type=checkbox]')) { + if (S.allFiltered) { S.allFiltered = false; S.items.forEach((i) => S.selected.add(i.id)); } + e.target.checked ? S.selected.add(id) : S.selected.delete(id); + row.setAttribute('aria-selected', e.target.checked); + el._h = null; + paintBar(); + return; + } + focusItem(S.items.find((i) => i.id === id)); + }); + el.addEventListener('dblclick', (e) => { if (e.target.closest('.tr')) openLightbox(); }); +} + +let stopPv = null; +function focusItem(item, { scroll = false } = {}) { + if (!item) return; S.current = item; - document.querySelectorAll('.tr').forEach((r) => r.setAttribute('aria-selected', (+r.dataset.id === item.id) || S.selected.has(+r.dataset.id) || S.allFiltered)); + document.querySelectorAll('.tr').forEach((r) => { + const on = +r.dataset.id === item.id || S.selected.has(+r.dataset.id) || S.allFiltered; + r.setAttribute('aria-selected', on); + if (scroll && +r.dataset.id === item.id) r.scrollIntoView({ block: 'nearest' }); + }); paintPreview(); - if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(item.ext) && item.size < 8 * 1024 * 1024) { - try { - const p = await rpc('preview', { job: S.job, id: item.id }); - if (S.current?.id === item.id && p.mime) $('.thumb', $('#preview')).innerHTML = `Pré-visualização de ${esc(item.name)}`; - } catch { /* sem prévia */ } - } +} + +function detailsHtml(i) { + const [cl, cc] = CONF[i.confidence]; + return `
Nome
${esc(i.name)}
Pasta
${esc(i.dir || '—')}
Tamanho
${human(i.size)}
+
Modificado
${date(i.modified)}
Origem
${i.origin === 'carved' ? 'Assinatura de formato' : esc(i.origin.toUpperCase())}
+
Confiança
${cl}
${i.note ? `
Aviso
${esc(i.note)}
` : ''}
`; } function paintPreview() { const el = $('#preview'); if (!el) return; + stopPv?.(); stopPv = null; const i = S.current; - if (!i) { el.innerHTML = `
Selecione um arquivo para ver os detalhes
`; return; } - const [cl, cc] = CONF[i.confidence]; - el.innerHTML = `
${esc(i.ext ? i.ext.toUpperCase() : 'ARQUIVO')}
-
Nome
${esc(i.name)}
Pasta
${esc(i.dir || '—')}
Tamanho
${human(i.size)}
-
Modificado
${date(i.modified)}
Origem
${i.origin === 'carved' ? 'Assinatura de formato' : esc(i.origin.toUpperCase())}
-
Confiança
${cl}
${i.note ? `
Aviso
${esc(i.note)}
` : ''}
-
`; + if (!i) { el.innerHTML = '
Selecione um arquivo para pré-visualizar
'; return; } + el.innerHTML = `
${esc(KIND_LABEL[kindOf(i)])}
${detailsHtml(i)} +
`; + stopPv = renderPreview($('#pvHost'), i, { url: fileUrl(S.job, i.id) }); + $('#pvFull').onclick = openLightbox; $('#recOne').onclick = () => recover({ ids: [i.id] }); } +// ------------------------------------------------------------------ tela cheia +let stopLb = null; +function openLightbox() { + const i = S.current; + if (!i) return; + const d = $('#lightbox'); + const idx = S.items.findIndex((x) => x.id === i.id); + d.innerHTML = `
+
${esc(i.name)}${esc(KIND_LABEL[kindOf(i)])} · ${human(i.size)} · confiança ${CONF[i.confidence][0]}
+
+
+
${i.note ? esc(i.note) : '← → para navegar · Esc para fechar'}
`; + stopLb?.(); + stopLb = renderPreview($('#lbHost', d), i, { url: fileUrl(S.job, i.id), large: true }); + const go = (n) => { const t = S.items[idx + n]; if (t) { focusItem(t, { scroll: true }); openLightbox(); } }; + $('#lbPrev', d).onclick = () => go(-1); + $('#lbNext', d).onclick = () => go(1); + $('#lbClose', d).onclick = () => d.close(); + $('#lbRec', d).onclick = () => { d.close(); recover({ ids: [i.id] }); }; + d.onclose = () => { stopLb?.(); stopLb = null; }; + d.onkeydown = (e) => { if (e.key === 'ArrowLeft') go(-1); else if (e.key === 'ArrowRight') go(1); }; + if (!d.open) d.showModal(); +} + +// Teclado: ↑/↓ percorre a lista; Espaço/Enter abre a tela cheia. +document.addEventListener('keydown', (e) => { + if (!S.job || document.querySelector('dialog[open]') || /^(INPUT|SELECT|TEXTAREA)$/.test(document.activeElement?.tagName) && document.activeElement.type !== 'checkbox') return; + const idx = S.items.findIndex((x) => x.id === S.current?.id); + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + e.preventDefault(); + const t = S.items[Math.min(S.items.length - 1, Math.max(0, idx + (e.key === 'ArrowDown' ? 1 : -1)))]; + focusItem(t, { scroll: true }); + } else if ((e.key === ' ' || e.key === 'Enter') && S.current && !e.target.closest?.('button')) { + e.preventDefault(); + openLightbox(); + } +}); + function selCount() { return S.allFiltered ? S.total : S.selected.size; } function paintBar() { @@ -465,14 +561,24 @@ function paintBar() { const st = S.status; const n = selCount(); const canAll = st && st.found > 0 && st.status !== 'error'; - if (!n && !canAll) { host.innerHTML = ''; return; } + if (!n && !canAll) { host.innerHTML = ''; host._h = null; return; } const moreOffer = !S.allFiltered && S.selected.size > 0 && S.selected.size < S.total && S.items.length === S.selected.size - ? `` : ''; - host.innerHTML = `
${n ? `${n.toLocaleString('pt-BR')} selecionado(s)` : `${S.total.toLocaleString('pt-BR')} arquivo(s) na lista`}${moreOffer} - ${n ? '' : ''}
`; - $('#selFiltered')?.addEventListener('click', () => { S.allFiltered = true; paintList(); }); - $('#recSel')?.addEventListener('click', () => recover(S.allFiltered ? { filter: currentFilter() } : { ids: [...S.selected] })); - $('#recAll')?.addEventListener('click', () => recover({ filter: currentFilter() })); + ? '' : ''; + const inner = `${n ? `${n.toLocaleString('pt-BR')} selecionado(s)` : `${S.total.toLocaleString('pt-BR')} arquivo(s) na lista`}${moreOffer} + ${n ? '' : ''}`; + let bar = host.firstElementChild; + if (!bar) { + // A barra é criada uma vez (com animação de entrada) e depois só tem o texto atualizado. + host.innerHTML = '
'; + bar = host.firstElementChild; + bar.onclick = (e) => { + const act = e.target.closest('[data-bar]')?.dataset.bar; + if (act === 'all') { S.allFiltered = true; $('#table')._h = null; paintList(); } + else if (act === 'sel') recover(S.allFiltered ? { filter: currentFilter() } : { ids: [...S.selected] }); + else if (act === 'rec') recover({ filter: currentFilter() }); + }; + } + setHTML(bar, inner); } function currentFilter() { @@ -540,6 +646,8 @@ async function openJobFromList(s) { openJob(s); } const v = await rpc('version'); $('#versionTag').textContent = `v${v.version}`; S.defaults = await rpc('defaults'); + try { const st = await rpc('settings_get'); if (st?.theme) { applyTheme(st.theme); try { localStorage.setItem('guara-theme', st.theme); } catch { /* */ } } } catch { /* usa o local */ } + tauri?.event?.listen?.('elevate-failed', (e) => { toast(String(e.payload || 'Não foi possível reiniciar como administrador')); }); } catch (e) { main.innerHTML = `
${warnSvg}
Não foi possível falar com o núcleo do Guará: ${esc(e.message)}. Se abriu esta página manualmente, use o endereço completo exibido pelo comando guara ui (ele inclui o token).
`; return; diff --git a/apps/gui/ui/guara-logo.svg b/apps/gui/ui/guara-logo.svg new file mode 100644 index 0000000..258babd --- /dev/null +++ b/apps/gui/ui/guara-logo.svg @@ -0,0 +1 @@ + diff --git a/apps/gui/ui/guara.svg b/apps/gui/ui/guara.svg index a49fc40..382878a 100644 --- a/apps/gui/ui/guara.svg +++ b/apps/gui/ui/guara.svg @@ -1,17 +1 @@ - - - - - - - - - - - - - - - - - + diff --git a/apps/gui/ui/index.html b/apps/gui/ui/index.html index 93a20ea..df1cdee 100644 --- a/apps/gui/ui/index.html +++ b/apps/gui/ui/index.html @@ -26,13 +26,14 @@
    -
    Somente leitura na origem
    +
    Somente leitura na origem
    +
    diff --git a/apps/gui/ui/preview.js b/apps/gui/ui/preview.js new file mode 100644 index 0000000..25de0f8 --- /dev/null +++ b/apps/gui/ui/preview.js @@ -0,0 +1,297 @@ +// Pré-visualização de arquivos recuperados. +// O conteúdo é lido em streaming do núcleo (com Range) pela URL `url`; nada é +// gravado em disco. Tipos: imagem, vídeo, áudio, PDF (pdf.js), texto, documentos +// Office/OpenDocument (texto extraído), listagem de ZIP e visão hexadecimal. + +const IMG = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'avif', 'ico']); +const VID = new Set(['mp4', 'm4v', 'mov', 'webm', 'mkv', 'ogv']); +const AUD = new Set(['mp3', 'wav', 'ogg', 'opus', 'm4a', 'aac', 'flac']); +const TXT = new Set(['txt', 'md', 'csv', 'tsv', 'json', 'xml', 'html', 'htm', 'log', 'ini', 'yml', 'yaml', 'js', 'css', 'c', 'h', 'cpp', 'py', 'rs', 'sh', 'bat', 'sql', 'toml', 'cfg', 'conf', 'srt', 'tex', 'svg']); +const OFFICE = new Set(['docx', 'xlsx', 'pptx', 'odt', 'ods', 'odp']); +const ZIPS = new Set(['zip', 'jar', 'apk', 'epub']); + +export function kindOf(item) { + const e = (item.ext || '').toLowerCase(); + if (IMG.has(e)) return 'image'; + if (VID.has(e)) return 'video'; + if (AUD.has(e)) return 'audio'; + if (e === 'pdf') return 'pdf'; + if (OFFICE.has(e)) return 'office'; + if (ZIPS.has(e)) return 'zip'; + if (TXT.has(e)) return 'text'; + return 'hex'; +} + +export const KIND_LABEL = { + image: 'Imagem', video: 'Vídeo', audio: 'Áudio', pdf: 'PDF', office: 'Documento (texto extraído)', + zip: 'Conteúdo do arquivo compactado', text: 'Texto', hex: 'Dados brutos (hexadecimal)', +}; + +const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); +const human = (n) => { + const u = ['B', 'KB', 'MB', 'GB']; + let i = 0, v = n; + while (v >= 1024 && i < 3) { v /= 1024; i++; } + return i ? `${v.toFixed(1)} ${u[i]}` : `${n} B`; +}; + +async function fetchRange(url, a, b) { + const r = await fetch(url, { headers: { Range: `bytes=${a}-${b}` } }); + if (!r.ok) throw new Error(`leitura falhou (${r.status})`); + return new Uint8Array(await r.arrayBuffer()); +} + +// ------------------------------------------------------------------ ZIP mínimo +async function zipDir(url, size) { + const tailLen = Math.min(size, 66000); + const tail = await fetchRange(url, size - tailLen, size - 1); + const dv = new DataView(tail.buffer); + let e = -1; + for (let i = tail.length - 22; i >= 0; i--) if (dv.getUint32(i, true) === 0x06054b50) { e = i; break; } + if (e < 0) throw new Error('diretório do ZIP não encontrado (arquivo possivelmente incompleto)'); + const n = dv.getUint16(e + 10, true); + const cdSize = dv.getUint32(e + 12, true); + const cdOff = dv.getUint32(e + 16, true); + if (cdOff + cdSize > size) throw new Error('diretório do ZIP inconsistente'); + const cd = await fetchRange(url, cdOff, cdOff + cdSize - 1); + const cv = new DataView(cd.buffer); + const out = []; + let p = 0; + for (let i = 0; i < n && p + 46 <= cd.length; i++) { + if (cv.getUint32(p, true) !== 0x02014b50) break; + const nl = cv.getUint16(p + 28, true), xl = cv.getUint16(p + 30, true), cl = cv.getUint16(p + 32, true); + out.push({ + method: cv.getUint16(p + 10, true), csize: cv.getUint32(p + 20, true), usize: cv.getUint32(p + 24, true), + off: cv.getUint32(p + 42, true), name: new TextDecoder().decode(cd.subarray(p + 46, p + 46 + nl)), + }); + p += 46 + nl + xl + cl; + } + return out; +} + +async function zipRead(url, e, cap = 8 << 20) { + if (e.usize > cap) throw new Error('parte grande demais'); + const lh = await fetchRange(url, e.off, e.off + 29); + const dv = new DataView(lh.buffer); + const start = e.off + 30 + dv.getUint16(26, true) + dv.getUint16(28, true); + const data = e.csize ? await fetchRange(url, start, start + e.csize - 1) : new Uint8Array(0); + if (e.method === 0) return data; + if (e.method !== 8) throw new Error('compressão não suportada'); + const stream = new Blob([data]).stream().pipeThrough(new DecompressionStream('deflate-raw')); + return new Uint8Array(await new Response(stream).arrayBuffer()); +} + +const xml = (bytes) => new DOMParser().parseFromString(new TextDecoder().decode(bytes), 'application/xml'); + +// ------------------------------------------------------------------ renderizadores +function note(host, html, cls = '') { + host.insertAdjacentHTML('beforeend', `
    ${html}
    `); +} + +function failure(host, item, err, withHex) { + host.innerHTML = ''; + note(host, `Não foi possível pré-visualizar.
    ${esc(err?.message || err || '')} O arquivo pode estar danificado, incompleto ou parcialmente sobrescrito — isso também indica que a chance de recuperação é menor.`, 'bad'); + return withHex ? hex(host, item, host.dataset.url, false) : null; +} + +async function hex(host, item, url, large) { + const n = Math.min(item.size, large ? 4096 : 1024); + if (!n) { note(host, 'Arquivo vazio.'); return; } + const b = await fetchRange(url, 0, n - 1); + const lines = []; + for (let i = 0; i < b.length; i += 16) { + const row = [...b.subarray(i, i + 16)]; + const h = row.map((x) => x.toString(16).padStart(2, '0')).join(' ').padEnd(47); + const a = row.map((x) => (x >= 32 && x < 127 ? String.fromCharCode(x) : '·')).join(''); + lines.push(`${i.toString(16).padStart(6, '0')} ${h} ${esc(a)}`); + } + host.insertAdjacentHTML('beforeend', `
    ${lines.join('\n')}
    `); + if (item.size > n) note(host, `Mostrando os primeiros ${human(n)} de ${human(item.size)}.`); +} + +async function text(host, item, url, large) { + const cap = large ? 262144 : 24576; + const b = await fetchRange(url, 0, Math.min(item.size, cap) - 1); + const sample = b.subarray(0, 2048); + const bin = sample.filter((x) => x === 0 || (x < 9) ).length; + if (bin > sample.length * 0.02) { note(host, 'Este arquivo não parece ser texto.'); return hex(host, item, url, large); } + let s = new TextDecoder('utf-8', { fatal: false }).decode(b); + if ((s.match(/�/g) || []).length > s.length * 0.02) s = new TextDecoder('windows-1252').decode(b); + host.insertAdjacentHTML('beforeend', `
    ${esc(s)}
    `); + if (item.size > b.length) note(host, `Mostrando o início (${human(b.length)} de ${human(item.size)}).`); +} + +async function image(host, item, url, state) { + await new Promise((resolve) => { + const img = new Image(); + img.alt = `Pré-visualização de ${item.name}`; + img.className = 'pv-img'; + img.decoding = 'async'; + img.onload = () => { + if (state.dead) return resolve(); + host.innerHTML = ''; + host.appendChild(img); + host.classList.add('zoomable'); + img.onclick = () => host.classList.toggle('actual'); + note(host, `${img.naturalWidth} × ${img.naturalHeight} px — clique para alternar entre ajustar e tamanho real.`); + resolve(); + }; + img.onerror = () => { if (!state.dead) failure(host, item, 'A imagem não pôde ser decodificada.', true); resolve(); }; + img.src = url; + }); +} + +function media(host, item, url, tag, state) { + const el = document.createElement(tag); + el.controls = true; + el.preload = 'metadata'; + el.className = `pv-${tag}`; + if (tag === 'video') el.playsInline = true; + el.onerror = () => { if (!state.dead) failure(host, item, `Não foi possível reproduzir este ${tag === 'video' ? 'vídeo' : 'áudio'}.`, true); }; + el.src = url; + host.innerHTML = ''; + host.appendChild(el); + state.cleanup.push(() => { el.pause?.(); el.removeAttribute('src'); el.load?.(); }); +} + +let pdfjsPromise; +function loadPdfjs() { + pdfjsPromise ??= import('./vendor/pdf.min.mjs').then((m) => { + m.GlobalWorkerOptions.workerSrc = new URL('./vendor/pdf.worker.min.mjs', import.meta.url).href; + return m; + }); + return pdfjsPromise; +} + +async function pdf(host, item, url, state, large) { + const pdfjs = await loadPdfjs(); + const task = pdfjs.getDocument({ url, disableAutoFetch: true, isEvalSupported: false }); + state.cleanup.push(() => task.destroy()); + const doc = await task.promise; + if (state.dead) return; + host.innerHTML = '
    '; + const canvas = host.querySelector('canvas'); + const label = host.querySelector('.pg'); + let n = 1, busy = false; + async function draw() { + if (busy || state.dead) return; + busy = true; + try { + const page = await doc.getPage(n); + const base = page.getViewport({ scale: 1 }); + const width = Math.max(240, (host.clientWidth || 320) - 16); + const scale = (width / base.width) * (large ? 1 : 1); + const dpr = window.devicePixelRatio || 1; + const vp = page.getViewport({ scale: scale * dpr }); + canvas.width = vp.width; canvas.height = vp.height; + canvas.style.width = `${vp.width / dpr}px`; + await page.render({ canvasContext: canvas.getContext('2d'), viewport: vp }).promise; + label.textContent = `Página ${n} de ${doc.numPages}`; + } catch (e) { + if (!state.dead) { host.innerHTML = ''; failure(host, item, e, true); } + } + busy = false; + } + host.querySelectorAll('[data-d]').forEach((b) => (b.onclick = () => { n = Math.min(doc.numPages, Math.max(1, n + +b.dataset.d)); draw(); })); + await draw(); +} + +const colIndex = (ref) => [...ref.replace(/\d+/g, '')].reduce((a, c) => a * 26 + c.charCodeAt(0) - 64, 0) - 1; +const colName = (i) => { let s = ''; i++; while (i > 0) { s = String.fromCharCode(65 + ((i - 1) % 26)) + s; i = Math.floor((i - 1) / 26); } return s; }; + +async function office(host, item, url, state) { + const ents = await zipDir(url, item.size); + const find = (n) => ents.find((e) => e.name === n); + const ext = item.ext.toLowerCase(); + let html = ''; + if (ext === 'docx') { + const d = xml(await zipRead(url, find('word/document.xml'))); + const paras = [...d.getElementsByTagName('w:p')].slice(0, 400).map((p) => { + let t = ''; + p.querySelectorAll('t, tab, br').forEach((n) => { t += n.localName === 't' ? n.textContent : n.localName === 'tab' ? '\t' : '\n'; }); + const h = p.querySelector('pStyle')?.getAttribute('w:val') || ''; + const tag = /^(Heading|Ttulo|Title)/i.test(h) ? 'h4' : 'p'; + return t.trim() ? `<${tag}>${esc(t)}` : ''; + }); + html = `
    ${paras.join('') || '

    Sem texto.

    '}
    `; + } else if (ext === 'odt') { + const d = xml(await zipRead(url, find('content.xml'))); + const els = [...d.getElementsByTagName('text:p'), ...[]].slice(0, 400); + html = `
    ${els.map((p) => (p.textContent.trim() ? `

    ${esc(p.textContent)}

    ` : '')).join('') || '

    Sem texto.

    '}
    `; + } else if (ext === 'xlsx') { + const ss = find('xl/sharedStrings.xml'); + const strings = ss ? [...xml(await zipRead(url, ss)).getElementsByTagName('si')].map((si) => si.textContent) : []; + const sheet = ents.filter((e) => /^xl\/worksheets\/sheet\d+\.xml$/.test(e.name)).sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }))[0]; + const d = xml(await zipRead(url, sheet)); + const rows = [...d.getElementsByTagName('row')].slice(0, 80); + let maxc = 0; + const grid = rows.map((r) => { + const cells = {}; + [...r.getElementsByTagName('c')].forEach((c) => { + const i = colIndex(c.getAttribute('r') || 'A1'); + const v = c.getElementsByTagName('v')[0]?.textContent ?? c.getElementsByTagName('t')[0]?.textContent ?? ''; + cells[i] = c.getAttribute('t') === 's' ? strings[+v] ?? '' : v; + maxc = Math.max(maxc, i + 1); + }); + return [r.getAttribute('r'), cells]; + }); + maxc = Math.min(maxc, 16); + html = `
    ${Array.from({ length: maxc }, (_, i) => ``).join('')}${grid + .map(([n, cells]) => `${Array.from({ length: maxc }, (_, i) => ``).join('')}`).join('')}
    ${colName(i)}
    ${esc(n)}${esc(cells[i] ?? '')}
    `; + } else if (ext === 'ods') { + const d = xml(await zipRead(url, find('content.xml'))); + const rows = [...d.getElementsByTagName('table:table-row')].slice(0, 80); + html = `
    ${rows.map((r) => `${[...r.getElementsByTagName('table:table-cell')].slice(0, 16).map((c) => ``).join('')}`).join('')}
    ${esc(c.textContent)}
    `; + } else { + // pptx / odp: texto por slide + let slides; + if (ext === 'pptx') { + const files = ents.filter((e) => /^ppt\/slides\/slide\d+\.xml$/.test(e.name)).sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true })).slice(0, 60); + slides = []; + for (const f of files) { + const d = xml(await zipRead(url, f)); + slides.push([...d.getElementsByTagName('a:p')].map((p) => p.textContent).filter((t) => t.trim())); + } + } else { + const d = xml(await zipRead(url, find('content.xml'))); + slides = [...d.getElementsByTagName('draw:page')].slice(0, 60).map((pg) => [...pg.getElementsByTagName('text:p')].map((p) => p.textContent).filter((t) => t.trim())); + } + html = slides.map((s, i) => `
    Slide ${i + 1}${s.map((t, j) => (j === 0 ? `

    ${esc(t)}

    ` : `

    ${esc(t)}

    `)).join('') || '

    Sem texto.

    '}
    `).join(''); + } + if (state.dead) return; + host.innerHTML = html; + note(host, 'Texto extraído do documento. A formatação, as imagens e os gráficos originais não são exibidos.'); +} + +async function zip(host, item, url, state) { + const ents = await zipDir(url, item.size); + if (state.dead) return; + host.innerHTML = `
      ${ents.slice(0, 400).map((e) => `
    • ${esc(e.name)}${e.name.endsWith('/') ? 'pasta' : human(e.usize)}
    • `).join('')}
    `; + note(host, `${ents.length} item(ns) no arquivo compactado.`); +} + +// ------------------------------------------------------------------ API +/** Desenha a pré-visualização de `item` dentro de `host`. Devolve uma função de limpeza. */ +export function renderPreview(host, item, { url, large = false }) { + const state = { dead: false, cleanup: [] }; + host.dataset.url = url; + host.classList.remove('zoomable', 'actual'); + host.innerHTML = '
    '; + const kind = kindOf(item); + (async () => { + try { + if (!item.size) { host.innerHTML = ''; note(host, 'Arquivo vazio.'); return; } + if (kind === 'image') await image(host, item, url, state); + else if (kind === 'video') media(host, item, url, 'video', state); + else if (kind === 'audio') media(host, item, url, 'audio', state); + else if (kind === 'pdf') await pdf(host, item, url, state, large); + else if (kind === 'office') await office(host, item, url, state); + else if (kind === 'zip') await zip(host, item, url, state); + else if (kind === 'text') { host.innerHTML = ''; await text(host, item, url, large); } + else { host.innerHTML = ''; await hex(host, item, url, large); } + } catch (e) { + if (!state.dead) await failure(host, item, e, kind !== 'hex' && kind !== 'text'); + } + })(); + return () => { state.dead = true; state.cleanup.forEach((f) => { try { f(); } catch { /* ignora */ } }); }; +} diff --git a/apps/gui/ui/vendor/PDFJS-LICENSE b/apps/gui/ui/vendor/PDFJS-LICENSE new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/apps/gui/ui/vendor/PDFJS-LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/apps/gui/ui/vendor/README.md b/apps/gui/ui/vendor/README.md new file mode 100644 index 0000000..d3c65c3 --- /dev/null +++ b/apps/gui/ui/vendor/README.md @@ -0,0 +1,3 @@ +# Bibliotecas de terceiros + +- **pdf.js** 4.10.38 (build "legacy"), © Mozilla, licença Apache-2.0 (`PDFJS-LICENSE`). Usada só para pré-visualizar PDFs, localmente e sem internet. Origem: https://github.com/mozilla/pdf.js diff --git a/apps/gui/ui/vendor/pdf.min.mjs b/apps/gui/ui/vendor/pdf.min.mjs new file mode 100644 index 0000000..5bafcc3 --- /dev/null +++ b/apps/gui/ui/vendor/pdf.min.mjs @@ -0,0 +1,21 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * Copyright 2024 Mozilla Foundation + * + * 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. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */var t={9306:(t,e,i)=>{var s=i(4901),n=i(6823),r=TypeError;t.exports=function(t){if(s(t))return t;throw new r(n(t)+" is not a function")}},3506:(t,e,i)=>{var s=i(3925),n=String,r=TypeError;t.exports=function(t){if(s(t))return t;throw new r("Can't set "+n(t)+" as a prototype")}},7080:(t,e,i)=>{var s=i(4402).has;t.exports=function(t){s(t);return t}},679:(t,e,i)=>{var s=i(1625),n=TypeError;t.exports=function(t,e){if(s(e,t))return t;throw new n("Incorrect invocation")}},8551:(t,e,i)=>{var s=i(34),n=String,r=TypeError;t.exports=function(t){if(s(t))return t;throw new r(n(t)+" is not an object")}},7811:t=>{t.exports="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView},7394:(t,e,i)=>{var s=i(4576),n=i(6706),r=i(2195),a=s.ArrayBuffer,o=s.TypeError;t.exports=a&&n(a.prototype,"byteLength","get")||function(t){if("ArrayBuffer"!==r(t))throw new o("ArrayBuffer expected");return t.byteLength}},3238:(t,e,i)=>{var s=i(4576),n=i(7476),r=i(7394),a=s.ArrayBuffer,o=a&&a.prototype,l=o&&n(o.slice);t.exports=function(t){if(0!==r(t))return!1;if(!l)return!1;try{l(t,0,0);return!1}catch(t){return!0}}},5169:(t,e,i)=>{var s=i(3238),n=TypeError;t.exports=function(t){if(s(t))throw new n("ArrayBuffer is detached");return t}},5636:(t,e,i)=>{var s=i(4576),n=i(9504),r=i(6706),a=i(7696),o=i(5169),l=i(7394),h=i(4483),c=i(1548),d=s.structuredClone,u=s.ArrayBuffer,p=s.DataView,g=Math.min,f=u.prototype,m=p.prototype,b=n(f.slice),v=r(f,"resizable","get"),y=r(f,"maxByteLength","get"),w=n(m.getInt8),A=n(m.setInt8);t.exports=(c||h)&&function(t,e,i){var s,n=l(t),r=void 0===e?n:a(e),f=!v||!v(t);o(t);if(c){t=d(t,{transfer:[t]});if(n===r&&(i||f))return t}if(n>=r&&(!i||f))s=b(t,0,r);else{var m=i&&!f&&y?{maxByteLength:y(t)}:void 0;s=new u(r,m);for(var x=new p(t),_=new p(s),E=g(r,n),S=0;S{var s,n,r,a=i(7811),o=i(3724),l=i(4576),h=i(4901),c=i(34),d=i(9297),u=i(6955),p=i(6823),g=i(6699),f=i(6840),m=i(2106),b=i(1625),v=i(2787),y=i(2967),w=i(8227),A=i(3392),x=i(1181),_=x.enforce,E=x.get,S=l.Int8Array,C=S&&S.prototype,T=l.Uint8ClampedArray,M=T&&T.prototype,P=S&&v(S),D=C&&v(C),k=Object.prototype,R=l.TypeError,I=w("toStringTag"),L=A("TYPED_ARRAY_TAG"),O="TypedArrayConstructor",N=a&&!!y&&"Opera"!==u(l.opera),B=!1,H={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},U={BigInt64Array:8,BigUint64Array:8},getTypedArrayConstructor=function(t){var e=v(t);if(c(e)){var i=E(e);return i&&d(i,O)?i[O]:getTypedArrayConstructor(e)}},isTypedArray=function(t){if(!c(t))return!1;var e=u(t);return d(H,e)||d(U,e)};for(s in H)(r=(n=l[s])&&n.prototype)?_(r)[O]=n:N=!1;for(s in U)(r=(n=l[s])&&n.prototype)&&(_(r)[O]=n);if(!N||!h(P)||P===Function.prototype){P=function TypedArray(){throw new R("Incorrect invocation")};if(N)for(s in H)l[s]&&y(l[s],P)}if(!N||!D||D===k){D=P.prototype;if(N)for(s in H)l[s]&&y(l[s].prototype,D)}N&&v(M)!==D&&y(M,D);if(o&&!d(D,I)){B=!0;m(D,I,{configurable:!0,get:function(){return c(this)?this[L]:void 0}});for(s in H)l[s]&&g(l[s],L,s)}t.exports={NATIVE_ARRAY_BUFFER_VIEWS:N,TYPED_ARRAY_TAG:B&&L,aTypedArray:function(t){if(isTypedArray(t))return t;throw new R("Target is not a typed array")},aTypedArrayConstructor:function(t){if(h(t)&&(!y||b(P,t)))return t;throw new R(p(t)+" is not a typed array constructor")},exportTypedArrayMethod:function(t,e,i,s){if(o){if(i)for(var n in H){var r=l[n];if(r&&d(r.prototype,t))try{delete r.prototype[t]}catch(i){try{r.prototype[t]=e}catch(t){}}}D[t]&&!i||f(D,t,i?e:N&&C[t]||e,s)}},exportTypedArrayStaticMethod:function(t,e,i){var s,n;if(o){if(y){if(i)for(s in H)if((n=l[s])&&d(n,t))try{delete n[t]}catch(t){}if(P[t]&&!i)return;try{return f(P,t,i?e:N&&P[t]||e)}catch(t){}}for(s in H)!(n=l[s])||n[t]&&!i||f(n,t,e)}},getTypedArrayConstructor,isView:function isView(t){if(!c(t))return!1;var e=u(t);return"DataView"===e||d(H,e)||d(U,e)},isTypedArray,TypedArray:P,TypedArrayPrototype:D}},5370:(t,e,i)=>{var s=i(6198);t.exports=function(t,e,i){for(var n=0,r=arguments.length>2?i:s(e),a=new t(r);r>n;)a[n]=e[n++];return a}},9617:(t,e,i)=>{var s=i(5397),n=i(5610),r=i(6198),createMethod=function(t){return function(e,i,a){var o=s(e),l=r(o);if(0===l)return!t&&-1;var h,c=n(a,l);if(t&&i!=i){for(;l>c;)if((h=o[c++])!=h)return!0}else for(;l>c;c++)if((t||c in o)&&o[c]===i)return t||c||0;return!t&&-1}};t.exports={includes:createMethod(!0),indexOf:createMethod(!1)}},4527:(t,e,i)=>{var s=i(3724),n=i(4376),r=TypeError,a=Object.getOwnPropertyDescriptor,o=s&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(t){return t instanceof TypeError}}();t.exports=o?function(t,e){if(n(t)&&!a(t,"length").writable)throw new r("Cannot set read only .length");return t.length=e}:function(t,e){return t.length=e}},7680:(t,e,i)=>{var s=i(9504);t.exports=s([].slice)},7628:(t,e,i)=>{var s=i(6198);t.exports=function(t,e){for(var i=s(t),n=new e(i),r=0;r{var s=i(6198),n=i(1291),r=RangeError;t.exports=function(t,e,i,a){var o=s(t),l=n(i),h=l<0?o+l:l;if(h>=o||h<0)throw new r("Incorrect index");for(var c=new e(o),d=0;d{var s=i(8551),n=i(9539);t.exports=function(t,e,i,r){try{return r?e(s(i)[0],i[1]):e(i)}catch(e){n(t,"throw",e)}}},2195:(t,e,i)=>{var s=i(9504),n=s({}.toString),r=s("".slice);t.exports=function(t){return r(n(t),8,-1)}},6955:(t,e,i)=>{var s=i(2140),n=i(4901),r=i(2195),a=i(8227)("toStringTag"),o=Object,l="Arguments"===r(function(){return arguments}());t.exports=s?r:function(t){var e,i,s;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(i=function(t,e){try{return t[e]}catch(t){}}(e=o(t),a))?i:l?r(e):"Object"===(s=r(e))&&n(e.callee)?"Arguments":s}},7740:(t,e,i)=>{var s=i(9297),n=i(5031),r=i(7347),a=i(4913);t.exports=function(t,e,i){for(var o=n(e),l=a.f,h=r.f,c=0;c{var s=i(9039);t.exports=!s((function(){function F(){}F.prototype.constructor=null;return Object.getPrototypeOf(new F)!==F.prototype}))},2529:t=>{t.exports=function(t,e){return{value:t,done:e}}},6699:(t,e,i)=>{var s=i(3724),n=i(4913),r=i(6980);t.exports=s?function(t,e,i){return n.f(t,e,r(1,i))}:function(t,e,i){t[e]=i;return t}},6980:t=>{t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},4659:(t,e,i)=>{var s=i(3724),n=i(4913),r=i(6980);t.exports=function(t,e,i){s?n.f(t,e,r(0,i)):t[e]=i}},2106:(t,e,i)=>{var s=i(283),n=i(4913);t.exports=function(t,e,i){i.get&&s(i.get,e,{getter:!0});i.set&&s(i.set,e,{setter:!0});return n.f(t,e,i)}},6840:(t,e,i)=>{var s=i(4901),n=i(4913),r=i(283),a=i(9433);t.exports=function(t,e,i,o){o||(o={});var l=o.enumerable,h=void 0!==o.name?o.name:e;s(i)&&r(i,h,o);if(o.global)l?t[e]=i:a(e,i);else{try{o.unsafe?t[e]&&(l=!0):delete t[e]}catch(t){}l?t[e]=i:n.f(t,e,{value:i,enumerable:!1,configurable:!o.nonConfigurable,writable:!o.nonWritable})}return t}},6279:(t,e,i)=>{var s=i(6840);t.exports=function(t,e,i){for(var n in e)s(t,n,e[n],i);return t}},9433:(t,e,i)=>{var s=i(4576),n=Object.defineProperty;t.exports=function(t,e){try{n(s,t,{value:e,configurable:!0,writable:!0})}catch(i){s[t]=e}return e}},3724:(t,e,i)=>{var s=i(9039);t.exports=!s((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]}))},4483:(t,e,i)=>{var s,n,r,a,o=i(4576),l=i(9429),h=i(1548),c=o.structuredClone,d=o.ArrayBuffer,u=o.MessageChannel,p=!1;if(h)p=function(t){c(t,{transfer:[t]})};else if(d)try{u||(s=l("worker_threads"))&&(u=s.MessageChannel);if(u){n=new u;r=new d(2);a=function(t){n.port1.postMessage(null,[t])};if(2===r.byteLength){a(r);0===r.byteLength&&(p=a)}}}catch(t){}t.exports=p},4055:(t,e,i)=>{var s=i(4576),n=i(34),r=s.document,a=n(r)&&n(r.createElement);t.exports=function(t){return a?r.createElement(t):{}}},6837:t=>{var e=TypeError;t.exports=function(t){if(t>9007199254740991)throw e("Maximum allowed index exceeded");return t}},5002:t=>{t.exports={IndexSizeError:{s:"INDEX_SIZE_ERR",c:1,m:1},DOMStringSizeError:{s:"DOMSTRING_SIZE_ERR",c:2,m:0},HierarchyRequestError:{s:"HIERARCHY_REQUEST_ERR",c:3,m:1},WrongDocumentError:{s:"WRONG_DOCUMENT_ERR",c:4,m:1},InvalidCharacterError:{s:"INVALID_CHARACTER_ERR",c:5,m:1},NoDataAllowedError:{s:"NO_DATA_ALLOWED_ERR",c:6,m:0},NoModificationAllowedError:{s:"NO_MODIFICATION_ALLOWED_ERR",c:7,m:1},NotFoundError:{s:"NOT_FOUND_ERR",c:8,m:1},NotSupportedError:{s:"NOT_SUPPORTED_ERR",c:9,m:1},InUseAttributeError:{s:"INUSE_ATTRIBUTE_ERR",c:10,m:1},InvalidStateError:{s:"INVALID_STATE_ERR",c:11,m:1},SyntaxError:{s:"SYNTAX_ERR",c:12,m:1},InvalidModificationError:{s:"INVALID_MODIFICATION_ERR",c:13,m:1},NamespaceError:{s:"NAMESPACE_ERR",c:14,m:1},InvalidAccessError:{s:"INVALID_ACCESS_ERR",c:15,m:1},ValidationError:{s:"VALIDATION_ERR",c:16,m:0},TypeMismatchError:{s:"TYPE_MISMATCH_ERR",c:17,m:1},SecurityError:{s:"SECURITY_ERR",c:18,m:1},NetworkError:{s:"NETWORK_ERR",c:19,m:1},AbortError:{s:"ABORT_ERR",c:20,m:1},URLMismatchError:{s:"URL_MISMATCH_ERR",c:21,m:1},QuotaExceededError:{s:"QUOTA_EXCEEDED_ERR",c:22,m:1},TimeoutError:{s:"TIMEOUT_ERR",c:23,m:1},InvalidNodeTypeError:{s:"INVALID_NODE_TYPE_ERR",c:24,m:1},DataCloneError:{s:"DATA_CLONE_ERR",c:25,m:1}}},8727:t=>{t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},6193:(t,e,i)=>{var s=i(4215);t.exports="NODE"===s},2839:(t,e,i)=>{var s=i(4576).navigator,n=s&&s.userAgent;t.exports=n?String(n):""},9519:(t,e,i)=>{var s,n,r=i(4576),a=i(2839),o=r.process,l=r.Deno,h=o&&o.versions||l&&l.version,c=h&&h.v8;c&&(n=(s=c.split("."))[0]>0&&s[0]<4?1:+(s[0]+s[1]));!n&&a&&(!(s=a.match(/Edge\/(\d+)/))||s[1]>=74)&&(s=a.match(/Chrome\/(\d+)/))&&(n=+s[1]);t.exports=n},4215:(t,e,i)=>{var s=i(4576),n=i(2839),r=i(2195),userAgentStartsWith=function(t){return n.slice(0,t.length)===t};t.exports=userAgentStartsWith("Bun/")?"BUN":userAgentStartsWith("Cloudflare-Workers")?"CLOUDFLARE":userAgentStartsWith("Deno/")?"DENO":userAgentStartsWith("Node.js/")?"NODE":s.Bun&&"string"==typeof Bun.version?"BUN":s.Deno&&"object"==typeof Deno.version?"DENO":"process"===r(s.process)?"NODE":s.window&&s.document?"BROWSER":"REST"},8574:(t,e,i)=>{var s=i(9504),n=Error,r=s("".replace),a=String(new n("zxcasd").stack),o=/\n\s*at [^:]*:[^\n]*/,l=o.test(a);t.exports=function(t,e){if(l&&"string"==typeof t&&!n.prepareStackTrace)for(;e--;)t=r(t,o,"");return t}},6518:(t,e,i)=>{var s=i(4576),n=i(7347).f,r=i(6699),a=i(6840),o=i(9433),l=i(7740),h=i(2796);t.exports=function(t,e){var i,c,d,u,p,g=t.target,f=t.global,m=t.stat;if(i=f?s:m?s[g]||o(g,{}):s[g]&&s[g].prototype)for(c in e){u=e[c];d=t.dontCallGetSet?(p=n(i,c))&&p.value:i[c];if(!h(f?c:g+(m?".":"#")+c,t.forced)&&void 0!==d){if(typeof u==typeof d)continue;l(u,d)}(t.sham||d&&d.sham)&&r(u,"sham",!0);a(i,c,u,t)}}},9039:t=>{t.exports=function(t){try{return!!t()}catch(t){return!0}}},8745:(t,e,i)=>{var s=i(616),n=Function.prototype,r=n.apply,a=n.call;t.exports="object"==typeof Reflect&&Reflect.apply||(s?a.bind(r):function(){return a.apply(r,arguments)})},6080:(t,e,i)=>{var s=i(7476),n=i(9306),r=i(616),a=s(s.bind);t.exports=function(t,e){n(t);return void 0===e?t:r?a(t,e):function(){return t.apply(e,arguments)}}},616:(t,e,i)=>{var s=i(9039);t.exports=!s((function(){var t=function(){}.bind();return"function"!=typeof t||t.hasOwnProperty("prototype")}))},9565:(t,e,i)=>{var s=i(616),n=Function.prototype.call;t.exports=s?n.bind(n):function(){return n.apply(n,arguments)}},350:(t,e,i)=>{var s=i(3724),n=i(9297),r=Function.prototype,a=s&&Object.getOwnPropertyDescriptor,o=n(r,"name"),l=o&&"something"===function something(){}.name,h=o&&(!s||s&&a(r,"name").configurable);t.exports={EXISTS:o,PROPER:l,CONFIGURABLE:h}},6706:(t,e,i)=>{var s=i(9504),n=i(9306);t.exports=function(t,e,i){try{return s(n(Object.getOwnPropertyDescriptor(t,e)[i]))}catch(t){}}},7476:(t,e,i)=>{var s=i(2195),n=i(9504);t.exports=function(t){if("Function"===s(t))return n(t)}},9504:(t,e,i)=>{var s=i(616),n=Function.prototype,r=n.call,a=s&&n.bind.bind(r,r);t.exports=s?a:function(t){return function(){return r.apply(t,arguments)}}},9429:(t,e,i)=>{var s=i(4576),n=i(6193);t.exports=function(t){if(n){try{return s.process.getBuiltinModule(t)}catch(t){}try{return Function('return require("'+t+'")')()}catch(t){}}}},7751:(t,e,i)=>{var s=i(4576),n=i(4901);t.exports=function(t,e){return arguments.length<2?(i=s[t],n(i)?i:void 0):s[t]&&s[t][e];var i}},1767:t=>{t.exports=function(t){return{iterator:t,next:t.next,done:!1}}},8646:(t,e,i)=>{var s=i(9565),n=i(8551),r=i(1767),a=i(851);t.exports=function(t,e){e&&"string"==typeof t||n(t);var i=a(t);return r(n(void 0!==i?s(i,t):t))}},851:(t,e,i)=>{var s=i(6955),n=i(5966),r=i(4117),a=i(6269),o=i(8227)("iterator");t.exports=function(t){if(!r(t))return n(t,o)||n(t,"@@iterator")||a[s(t)]}},81:(t,e,i)=>{var s=i(9565),n=i(9306),r=i(8551),a=i(6823),o=i(851),l=TypeError;t.exports=function(t,e){var i=arguments.length<2?o(t):e;if(n(i))return r(s(i,t));throw new l(a(t)+" is not iterable")}},5966:(t,e,i)=>{var s=i(9306),n=i(4117);t.exports=function(t,e){var i=t[e];return n(i)?void 0:s(i)}},3789:(t,e,i)=>{var s=i(9306),n=i(8551),r=i(9565),a=i(1291),o=i(1767),l="Invalid size",h=RangeError,c=TypeError,d=Math.max,SetRecord=function(t,e){this.set=t;this.size=d(e,0);this.has=s(t.has);this.keys=s(t.keys)};SetRecord.prototype={getIterator:function(){return o(n(r(this.keys,this.set)))},includes:function(t){return r(this.has,this.set,t)}};t.exports=function(t){n(t);var e=+t.size;if(e!=e)throw new c(l);var i=a(e);if(i<0)throw new h(l);return new SetRecord(t,i)}},4576:function(t){var check=function(t){return t&&t.Math===Math&&t};t.exports=check("object"==typeof globalThis&&globalThis)||check("object"==typeof window&&window)||check("object"==typeof self&&self)||check("object"==typeof global&&global)||check("object"==typeof this&&this)||function(){return this}()||Function("return this")()},9297:(t,e,i)=>{var s=i(9504),n=i(8981),r=s({}.hasOwnProperty);t.exports=Object.hasOwn||function hasOwn(t,e){return r(n(t),e)}},421:t=>{t.exports={}},397:(t,e,i)=>{var s=i(7751);t.exports=s("document","documentElement")},5917:(t,e,i)=>{var s=i(3724),n=i(9039),r=i(4055);t.exports=!s&&!n((function(){return 7!==Object.defineProperty(r("div"),"a",{get:function(){return 7}}).a}))},7055:(t,e,i)=>{var s=i(9504),n=i(9039),r=i(2195),a=Object,o=s("".split);t.exports=n((function(){return!a("z").propertyIsEnumerable(0)}))?function(t){return"String"===r(t)?o(t,""):a(t)}:a},3167:(t,e,i)=>{var s=i(4901),n=i(34),r=i(2967);t.exports=function(t,e,i){var a,o;r&&s(a=e.constructor)&&a!==i&&n(o=a.prototype)&&o!==i.prototype&&r(t,o);return t}},3706:(t,e,i)=>{var s=i(9504),n=i(4901),r=i(7629),a=s(Function.toString);n(r.inspectSource)||(r.inspectSource=function(t){return a(t)});t.exports=r.inspectSource},1181:(t,e,i)=>{var s,n,r,a=i(8622),o=i(4576),l=i(34),h=i(6699),c=i(9297),d=i(7629),u=i(6119),p=i(421),g="Object already initialized",f=o.TypeError,m=o.WeakMap;if(a||d.state){var b=d.state||(d.state=new m);b.get=b.get;b.has=b.has;b.set=b.set;s=function(t,e){if(b.has(t))throw new f(g);e.facade=t;b.set(t,e);return e};n=function(t){return b.get(t)||{}};r=function(t){return b.has(t)}}else{var v=u("state");p[v]=!0;s=function(t,e){if(c(t,v))throw new f(g);e.facade=t;h(t,v,e);return e};n=function(t){return c(t,v)?t[v]:{}};r=function(t){return c(t,v)}}t.exports={set:s,get:n,has:r,enforce:function(t){return r(t)?n(t):s(t,{})},getterFor:function(t){return function(e){var i;if(!l(e)||(i=n(e)).type!==t)throw new f("Incompatible receiver, "+t+" required");return i}}}},4209:(t,e,i)=>{var s=i(8227),n=i(6269),r=s("iterator"),a=Array.prototype;t.exports=function(t){return void 0!==t&&(n.Array===t||a[r]===t)}},4376:(t,e,i)=>{var s=i(2195);t.exports=Array.isArray||function isArray(t){return"Array"===s(t)}},1108:(t,e,i)=>{var s=i(6955);t.exports=function(t){var e=s(t);return"BigInt64Array"===e||"BigUint64Array"===e}},4901:t=>{var e="object"==typeof document&&document.all;t.exports=void 0===e&&void 0!==e?function(t){return"function"==typeof t||t===e}:function(t){return"function"==typeof t}},2796:(t,e,i)=>{var s=i(9039),n=i(4901),r=/#|\.prototype\./,isForced=function(t,e){var i=o[a(t)];return i===h||i!==l&&(n(e)?s(e):!!e)},a=isForced.normalize=function(t){return String(t).replace(r,".").toLowerCase()},o=isForced.data={},l=isForced.NATIVE="N",h=isForced.POLYFILL="P";t.exports=isForced},4117:t=>{t.exports=function(t){return null==t}},34:(t,e,i)=>{var s=i(4901);t.exports=function(t){return"object"==typeof t?null!==t:s(t)}},3925:(t,e,i)=>{var s=i(34);t.exports=function(t){return s(t)||null===t}},6395:t=>{t.exports=!1},757:(t,e,i)=>{var s=i(7751),n=i(4901),r=i(1625),a=i(7040),o=Object;t.exports=a?function(t){return"symbol"==typeof t}:function(t){var e=s("Symbol");return n(e)&&r(e.prototype,o(t))}},507:(t,e,i)=>{var s=i(9565);t.exports=function(t,e,i){for(var n,r,a=i?t:t.iterator,o=t.next;!(n=s(o,a)).done;)if(void 0!==(r=e(n.value)))return r}},2652:(t,e,i)=>{var s=i(6080),n=i(9565),r=i(8551),a=i(6823),o=i(4209),l=i(6198),h=i(1625),c=i(81),d=i(851),u=i(9539),p=TypeError,Result=function(t,e){this.stopped=t;this.result=e},g=Result.prototype;t.exports=function(t,e,i){var f,m,b,v,y,w,A,x=i&&i.that,_=!(!i||!i.AS_ENTRIES),E=!(!i||!i.IS_RECORD),S=!(!i||!i.IS_ITERATOR),C=!(!i||!i.INTERRUPTED),T=s(e,x),stop=function(t){f&&u(f,"normal",t);return new Result(!0,t)},callFn=function(t){if(_){r(t);return C?T(t[0],t[1],stop):T(t[0],t[1])}return C?T(t,stop):T(t)};if(E)f=t.iterator;else if(S)f=t;else{if(!(m=d(t)))throw new p(a(t)+" is not iterable");if(o(m)){for(b=0,v=l(t);v>b;b++)if((y=callFn(t[b]))&&h(g,y))return y;return new Result(!1)}f=c(t,m)}w=E?t.next:f.next;for(;!(A=n(w,f)).done;){try{y=callFn(A.value)}catch(t){u(f,"throw",t)}if("object"==typeof y&&y&&h(g,y))return y}return new Result(!1)}},9539:(t,e,i)=>{var s=i(9565),n=i(8551),r=i(5966);t.exports=function(t,e,i){var a,o;n(t);try{if(!(a=r(t,"return"))){if("throw"===e)throw i;return i}a=s(a,t)}catch(t){o=!0;a=t}if("throw"===e)throw i;if(o)throw a;n(a);return i}},9462:(t,e,i)=>{var s=i(9565),n=i(2360),r=i(6699),a=i(6279),o=i(8227),l=i(1181),h=i(5966),c=i(7657).IteratorPrototype,d=i(2529),u=i(9539),p=o("toStringTag"),g="IteratorHelper",f="WrapForValidIterator",m=l.set,createIteratorProxyPrototype=function(t){var e=l.getterFor(t?f:g);return a(n(c),{next:function next(){var i=e(this);if(t)return i.nextHandler();try{var s=i.done?void 0:i.nextHandler();return d(s,i.done)}catch(t){i.done=!0;throw t}},return:function(){var i=e(this),n=i.iterator;i.done=!0;if(t){var r=h(n,"return");return r?s(r,n):d(void 0,!0)}if(i.inner)try{u(i.inner.iterator,"normal")}catch(t){return u(n,"throw",t)}n&&u(n,"normal");return d(void 0,!0)}})},b=createIteratorProxyPrototype(!0),v=createIteratorProxyPrototype(!1);r(v,p,"Iterator Helper");t.exports=function(t,e){var i=function Iterator(i,s){if(s){s.iterator=i.iterator;s.next=i.next}else s=i;s.type=e?f:g;s.nextHandler=t;s.counter=0;s.done=!1;m(this,s)};i.prototype=e?b:v;return i}},713:(t,e,i)=>{var s=i(9565),n=i(9306),r=i(8551),a=i(1767),o=i(9462),l=i(6319),h=o((function(){var t=this.iterator,e=r(s(this.next,t));if(!(this.done=!!e.done))return l(t,this.mapper,[e.value,this.counter++],!0)}));t.exports=function map(t){r(this);n(t);return new h(a(this),{mapper:t})}},7657:(t,e,i)=>{var s,n,r,a=i(9039),o=i(4901),l=i(34),h=i(2360),c=i(2787),d=i(6840),u=i(8227),p=i(6395),g=u("iterator"),f=!1;[].keys&&("next"in(r=[].keys())?(n=c(c(r)))!==Object.prototype&&(s=n):f=!0);!l(s)||a((function(){var t={};return s[g].call(t)!==t}))?s={}:p&&(s=h(s));o(s[g])||d(s,g,(function(){return this}));t.exports={IteratorPrototype:s,BUGGY_SAFARI_ITERATORS:f}},6269:t=>{t.exports={}},6198:(t,e,i)=>{var s=i(8014);t.exports=function(t){return s(t.length)}},283:(t,e,i)=>{var s=i(9504),n=i(9039),r=i(4901),a=i(9297),o=i(3724),l=i(350).CONFIGURABLE,h=i(3706),c=i(1181),d=c.enforce,u=c.get,p=String,g=Object.defineProperty,f=s("".slice),m=s("".replace),b=s([].join),v=o&&!n((function(){return 8!==g((function(){}),"length",{value:8}).length})),y=String(String).split("String"),w=t.exports=function(t,e,i){"Symbol("===f(p(e),0,7)&&(e="["+m(p(e),/^Symbol\(([^)]*)\).*$/,"$1")+"]");i&&i.getter&&(e="get "+e);i&&i.setter&&(e="set "+e);(!a(t,"name")||l&&t.name!==e)&&(o?g(t,"name",{value:e,configurable:!0}):t.name=e);v&&i&&a(i,"arity")&&t.length!==i.arity&&g(t,"length",{value:i.arity});try{i&&a(i,"constructor")&&i.constructor?o&&g(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=void 0)}catch(t){}var s=d(t);a(s,"source")||(s.source=b(y,"string"==typeof e?e:""));return t};Function.prototype.toString=w((function toString(){return r(this)&&u(this).source||h(this)}),"toString")},741:t=>{var e=Math.ceil,i=Math.floor;t.exports=Math.trunc||function trunc(t){var s=+t;return(s>0?i:e)(s)}},6043:(t,e,i)=>{var s=i(9306),n=TypeError,PromiseCapability=function(t){var e,i;this.promise=new t((function(t,s){if(void 0!==e||void 0!==i)throw new n("Bad Promise constructor");e=t;i=s}));this.resolve=s(e);this.reject=s(i)};t.exports.f=function(t){return new PromiseCapability(t)}},2603:(t,e,i)=>{var s=i(655);t.exports=function(t,e){return void 0===t?arguments.length<2?"":e:s(t)}},4149:t=>{var e=RangeError;t.exports=function(t){if(t==t)return t;throw new e("NaN is not allowed")}},2360:(t,e,i)=>{var s,n=i(8551),r=i(6801),a=i(8727),o=i(421),l=i(397),h=i(4055),c=i(6119),d="prototype",u="script",p=c("IE_PROTO"),EmptyConstructor=function(){},scriptTag=function(t){return"<"+u+">"+t+""},NullProtoObjectViaActiveX=function(t){t.write(scriptTag(""));t.close();var e=t.parentWindow.Object;t=null;return e},NullProtoObject=function(){try{s=new ActiveXObject("htmlfile")}catch(t){}NullProtoObject="undefined"!=typeof document?document.domain&&s?NullProtoObjectViaActiveX(s):function(){var t,e=h("iframe"),i="java"+u+":";e.style.display="none";l.appendChild(e);e.src=String(i);(t=e.contentWindow.document).open();t.write(scriptTag("document.F=Object"));t.close();return t.F}():NullProtoObjectViaActiveX(s);for(var t=a.length;t--;)delete NullProtoObject[d][a[t]];return NullProtoObject()};o[p]=!0;t.exports=Object.create||function create(t,e){var i;if(null!==t){EmptyConstructor[d]=n(t);i=new EmptyConstructor;EmptyConstructor[d]=null;i[p]=t}else i=NullProtoObject();return void 0===e?i:r.f(i,e)}},6801:(t,e,i)=>{var s=i(3724),n=i(8686),r=i(4913),a=i(8551),o=i(5397),l=i(1072);e.f=s&&!n?Object.defineProperties:function defineProperties(t,e){a(t);for(var i,s=o(e),n=l(e),h=n.length,c=0;h>c;)r.f(t,i=n[c++],s[i]);return t}},4913:(t,e,i)=>{var s=i(3724),n=i(5917),r=i(8686),a=i(8551),o=i(6969),l=TypeError,h=Object.defineProperty,c=Object.getOwnPropertyDescriptor,d="enumerable",u="configurable",p="writable";e.f=s?r?function defineProperty(t,e,i){a(t);e=o(e);a(i);if("function"==typeof t&&"prototype"===e&&"value"in i&&p in i&&!i[p]){var s=c(t,e);if(s&&s[p]){t[e]=i.value;i={configurable:u in i?i[u]:s[u],enumerable:d in i?i[d]:s[d],writable:!1}}}return h(t,e,i)}:h:function defineProperty(t,e,i){a(t);e=o(e);a(i);if(n)try{return h(t,e,i)}catch(t){}if("get"in i||"set"in i)throw new l("Accessors not supported");"value"in i&&(t[e]=i.value);return t}},7347:(t,e,i)=>{var s=i(3724),n=i(9565),r=i(8773),a=i(6980),o=i(5397),l=i(6969),h=i(9297),c=i(5917),d=Object.getOwnPropertyDescriptor;e.f=s?d:function getOwnPropertyDescriptor(t,e){t=o(t);e=l(e);if(c)try{return d(t,e)}catch(t){}if(h(t,e))return a(!n(r.f,t,e),t[e])}},8480:(t,e,i)=>{var s=i(1828),n=i(8727).concat("length","prototype");e.f=Object.getOwnPropertyNames||function getOwnPropertyNames(t){return s(t,n)}},3717:(t,e)=>{e.f=Object.getOwnPropertySymbols},2787:(t,e,i)=>{var s=i(9297),n=i(4901),r=i(8981),a=i(6119),o=i(2211),l=a("IE_PROTO"),h=Object,c=h.prototype;t.exports=o?h.getPrototypeOf:function(t){var e=r(t);if(s(e,l))return e[l];var i=e.constructor;return n(i)&&e instanceof i?i.prototype:e instanceof h?c:null}},1625:(t,e,i)=>{var s=i(9504);t.exports=s({}.isPrototypeOf)},1828:(t,e,i)=>{var s=i(9504),n=i(9297),r=i(5397),a=i(9617).indexOf,o=i(421),l=s([].push);t.exports=function(t,e){var i,s=r(t),h=0,c=[];for(i in s)!n(o,i)&&n(s,i)&&l(c,i);for(;e.length>h;)n(s,i=e[h++])&&(~a(c,i)||l(c,i));return c}},1072:(t,e,i)=>{var s=i(1828),n=i(8727);t.exports=Object.keys||function keys(t){return s(t,n)}},8773:(t,e)=>{var i={}.propertyIsEnumerable,s=Object.getOwnPropertyDescriptor,n=s&&!i.call({1:2},1);e.f=n?function propertyIsEnumerable(t){var e=s(this,t);return!!e&&e.enumerable}:i},2967:(t,e,i)=>{var s=i(6706),n=i(34),r=i(7750),a=i(3506);t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var t,e=!1,i={};try{(t=s(Object.prototype,"__proto__","set"))(i,[]);e=i instanceof Array}catch(t){}return function setPrototypeOf(i,s){r(i);a(s);if(!n(i))return i;e?t(i,s):i.__proto__=s;return i}}():void 0)},4270:(t,e,i)=>{var s=i(9565),n=i(4901),r=i(34),a=TypeError;t.exports=function(t,e){var i,o;if("string"===e&&n(i=t.toString)&&!r(o=s(i,t)))return o;if(n(i=t.valueOf)&&!r(o=s(i,t)))return o;if("string"!==e&&n(i=t.toString)&&!r(o=s(i,t)))return o;throw new a("Can't convert object to primitive value")}},5031:(t,e,i)=>{var s=i(7751),n=i(9504),r=i(8480),a=i(3717),o=i(8551),l=n([].concat);t.exports=s("Reflect","ownKeys")||function ownKeys(t){var e=r.f(o(t)),i=a.f;return i?l(e,i(t)):e}},8235:(t,e,i)=>{var s=i(9504),n=i(9297),r=SyntaxError,a=parseInt,o=String.fromCharCode,l=s("".charAt),h=s("".slice),c=s(/./.exec),d={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":"\n","\\r":"\r","\\t":"\t"},u=/^[\da-f]{4}$/i,p=/^[\u0000-\u001F]$/;t.exports=function(t,e){for(var i=!0,s="";e{t.exports=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}}},7750:(t,e,i)=>{var s=i(4117),n=TypeError;t.exports=function(t){if(s(t))throw new n("Can't call method on "+t);return t}},9286:(t,e,i)=>{var s=i(4402),n=i(8469),r=s.Set,a=s.add;t.exports=function(t){var e=new r;n(t,(function(t){a(e,t)}));return e}},3440:(t,e,i)=>{var s=i(7080),n=i(4402),r=i(9286),a=i(5170),o=i(3789),l=i(8469),h=i(507),c=n.has,d=n.remove;t.exports=function difference(t){var e=s(this),i=o(t),n=r(e);a(e)<=i.size?l(e,(function(t){i.includes(t)&&d(n,t)})):h(i.getIterator(),(function(t){c(e,t)&&d(n,t)}));return n}},4402:(t,e,i)=>{var s=i(9504),n=Set.prototype;t.exports={Set,add:s(n.add),has:s(n.has),remove:s(n.delete),proto:n}},8750:(t,e,i)=>{var s=i(7080),n=i(4402),r=i(5170),a=i(3789),o=i(8469),l=i(507),h=n.Set,c=n.add,d=n.has;t.exports=function intersection(t){var e=s(this),i=a(t),n=new h;r(e)>i.size?l(i.getIterator(),(function(t){d(e,t)&&c(n,t)})):o(e,(function(t){i.includes(t)&&c(n,t)}));return n}},4449:(t,e,i)=>{var s=i(7080),n=i(4402).has,r=i(5170),a=i(3789),o=i(8469),l=i(507),h=i(9539);t.exports=function isDisjointFrom(t){var e=s(this),i=a(t);if(r(e)<=i.size)return!1!==o(e,(function(t){if(i.includes(t))return!1}),!0);var c=i.getIterator();return!1!==l(c,(function(t){if(n(e,t))return h(c,"normal",!1)}))}},3838:(t,e,i)=>{var s=i(7080),n=i(5170),r=i(8469),a=i(3789);t.exports=function isSubsetOf(t){var e=s(this),i=a(t);return!(n(e)>i.size)&&!1!==r(e,(function(t){if(!i.includes(t))return!1}),!0)}},8527:(t,e,i)=>{var s=i(7080),n=i(4402).has,r=i(5170),a=i(3789),o=i(507),l=i(9539);t.exports=function isSupersetOf(t){var e=s(this),i=a(t);if(r(e){var s=i(9504),n=i(507),r=i(4402),a=r.Set,o=r.proto,l=s(o.forEach),h=s(o.keys),c=h(new a).next;t.exports=function(t,e,i){return i?n({iterator:h(t),next:c},e):l(t,e)}},4916:(t,e,i)=>{var s=i(7751),createSetLike=function(t){return{size:t,has:function(){return!1},keys:function(){return{next:function(){return{done:!0}}}}}};t.exports=function(t){var e=s("Set");try{(new e)[t](createSetLike(0));try{(new e)[t](createSetLike(-1));return!1}catch(t){return!0}}catch(t){return!1}}},5170:(t,e,i)=>{var s=i(6706),n=i(4402);t.exports=s(n.proto,"size","get")||function(t){return t.size}},3650:(t,e,i)=>{var s=i(7080),n=i(4402),r=i(9286),a=i(3789),o=i(507),l=n.add,h=n.has,c=n.remove;t.exports=function symmetricDifference(t){var e=s(this),i=a(t).getIterator(),n=r(e);o(i,(function(t){h(e,t)?c(n,t):l(n,t)}));return n}},4204:(t,e,i)=>{var s=i(7080),n=i(4402).add,r=i(9286),a=i(3789),o=i(507);t.exports=function union(t){var e=s(this),i=a(t).getIterator(),l=r(e);o(i,(function(t){n(l,t)}));return l}},6119:(t,e,i)=>{var s=i(5745),n=i(3392),r=s("keys");t.exports=function(t){return r[t]||(r[t]=n(t))}},7629:(t,e,i)=>{var s=i(6395),n=i(4576),r=i(9433),a="__core-js_shared__",o=t.exports=n[a]||r(a,{});(o.versions||(o.versions=[])).push({version:"3.39.0",mode:s?"pure":"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.39.0/LICENSE",source:"https://github.com/zloirock/core-js"})},5745:(t,e,i)=>{var s=i(7629);t.exports=function(t,e){return s[t]||(s[t]=e||{})}},1548:(t,e,i)=>{var s=i(4576),n=i(9039),r=i(9519),a=i(4215),o=s.structuredClone;t.exports=!!o&&!n((function(){if("DENO"===a&&r>92||"NODE"===a&&r>94||"BROWSER"===a&&r>97)return!1;var t=new ArrayBuffer(8),e=o(t,{transfer:[t]});return 0!==t.byteLength||8!==e.byteLength}))},4495:(t,e,i)=>{var s=i(9519),n=i(9039),r=i(4576).String;t.exports=!!Object.getOwnPropertySymbols&&!n((function(){var t=Symbol("symbol detection");return!r(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&s&&s<41}))},5610:(t,e,i)=>{var s=i(1291),n=Math.max,r=Math.min;t.exports=function(t,e){var i=s(t);return i<0?n(i+e,0):r(i,e)}},5854:(t,e,i)=>{var s=i(2777),n=TypeError;t.exports=function(t){var e=s(t,"number");if("number"==typeof e)throw new n("Can't convert number to bigint");return BigInt(e)}},7696:(t,e,i)=>{var s=i(1291),n=i(8014),r=RangeError;t.exports=function(t){if(void 0===t)return 0;var e=s(t),i=n(e);if(e!==i)throw new r("Wrong length or index");return i}},5397:(t,e,i)=>{var s=i(7055),n=i(7750);t.exports=function(t){return s(n(t))}},1291:(t,e,i)=>{var s=i(741);t.exports=function(t){var e=+t;return e!=e||0===e?0:s(e)}},8014:(t,e,i)=>{var s=i(1291),n=Math.min;t.exports=function(t){var e=s(t);return e>0?n(e,9007199254740991):0}},8981:(t,e,i)=>{var s=i(7750),n=Object;t.exports=function(t){return n(s(t))}},9590:(t,e,i)=>{var s=i(1291),n=RangeError;t.exports=function(t){var e=s(t);if(e<0)throw new n("The argument can't be less than 0");return e}},2777:(t,e,i)=>{var s=i(9565),n=i(34),r=i(757),a=i(5966),o=i(4270),l=i(8227),h=TypeError,c=l("toPrimitive");t.exports=function(t,e){if(!n(t)||r(t))return t;var i,l=a(t,c);if(l){void 0===e&&(e="default");i=s(l,t,e);if(!n(i)||r(i))return i;throw new h("Can't convert object to primitive value")}void 0===e&&(e="number");return o(t,e)}},6969:(t,e,i)=>{var s=i(2777),n=i(757);t.exports=function(t){var e=s(t,"string");return n(e)?e:e+""}},2140:(t,e,i)=>{var s={};s[i(8227)("toStringTag")]="z";t.exports="[object z]"===String(s)},655:(t,e,i)=>{var s=i(6955),n=String;t.exports=function(t){if("Symbol"===s(t))throw new TypeError("Cannot convert a Symbol value to a string");return n(t)}},6823:t=>{var e=String;t.exports=function(t){try{return e(t)}catch(t){return"Object"}}},3392:(t,e,i)=>{var s=i(9504),n=0,r=Math.random(),a=s(1..toString);t.exports=function(t){return"Symbol("+(void 0===t?"":t)+")_"+a(++n+r,36)}},7040:(t,e,i)=>{var s=i(4495);t.exports=s&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},8686:(t,e,i)=>{var s=i(3724),n=i(9039);t.exports=s&&n((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype}))},2812:t=>{var e=TypeError;t.exports=function(t,i){if(t{var s=i(4576),n=i(4901),r=s.WeakMap;t.exports=n(r)&&/native code/.test(String(r))},8227:(t,e,i)=>{var s=i(4576),n=i(5745),r=i(9297),a=i(3392),o=i(4495),l=i(7040),h=s.Symbol,c=n("wks"),d=l?h.for||h:h&&h.withoutSetter||a;t.exports=function(t){r(c,t)||(c[t]=o&&r(h,t)?h[t]:d("Symbol."+t));return c[t]}},6573:(t,e,i)=>{var s=i(3724),n=i(2106),r=i(3238),a=ArrayBuffer.prototype;s&&!("detached"in a)&&n(a,"detached",{configurable:!0,get:function detached(){return r(this)}})},7936:(t,e,i)=>{var s=i(6518),n=i(5636);n&&s({target:"ArrayBuffer",proto:!0},{transferToFixedLength:function transferToFixedLength(){return n(this,arguments.length?arguments[0]:void 0,!1)}})},8100:(t,e,i)=>{var s=i(6518),n=i(5636);n&&s({target:"ArrayBuffer",proto:!0},{transfer:function transfer(){return n(this,arguments.length?arguments[0]:void 0,!0)}})},4114:(t,e,i)=>{var s=i(6518),n=i(8981),r=i(6198),a=i(4527),o=i(6837);s({target:"Array",proto:!0,arity:1,forced:i(9039)((function(){return 4294967297!==[].push.call({length:4294967296},1)}))||!function(){try{Object.defineProperty([],"length",{writable:!1}).push()}catch(t){return t instanceof TypeError}}()},{push:function push(t){var e=n(this),i=r(e),s=arguments.length;o(i+s);for(var l=0;l{var s=i(6518),n=i(4576),r=i(679),a=i(8551),o=i(4901),l=i(2787),h=i(2106),c=i(4659),d=i(9039),u=i(9297),p=i(8227),g=i(7657).IteratorPrototype,f=i(3724),m=i(6395),b="constructor",v="Iterator",y=p("toStringTag"),w=TypeError,A=n[v],x=m||!o(A)||A.prototype!==g||!d((function(){A({})})),_=function Iterator(){r(this,g);if(l(this)===g)throw new w("Abstract class Iterator not directly constructable")},defineIteratorPrototypeAccessor=function(t,e){f?h(g,t,{configurable:!0,get:function(){return e},set:function(e){a(this);if(this===g)throw new w("You can't redefine this property");u(this,t)?this[t]=e:c(this,t,e)}}):g[t]=e};u(g,y)||defineIteratorPrototypeAccessor(y,v);!x&&u(g,b)&&g[b]!==Object||defineIteratorPrototypeAccessor(b,_);_.prototype=g;s({global:!0,constructor:!0,forced:x},{Iterator:_})},9314:(t,e,i)=>{var s=i(6518),n=i(9565),r=i(8551),a=i(1767),o=i(4149),l=i(9590),h=i(9462),c=i(6395),d=h((function(){for(var t,e=this.iterator,i=this.next;this.remaining;){this.remaining--;t=r(n(i,e));if(this.done=!!t.done)return}t=r(n(i,e));if(!(this.done=!!t.done))return t.value}));s({target:"Iterator",proto:!0,real:!0,forced:c},{drop:function drop(t){r(this);var e=l(o(+t));return new d(a(this),{remaining:e})}})},1148:(t,e,i)=>{var s=i(6518),n=i(2652),r=i(9306),a=i(8551),o=i(1767);s({target:"Iterator",proto:!0,real:!0},{every:function every(t){a(this);r(t);var e=o(this),i=0;return!n(e,(function(e,s){if(!t(e,i++))return s()}),{IS_RECORD:!0,INTERRUPTED:!0}).stopped}})},2489:(t,e,i)=>{var s=i(6518),n=i(9565),r=i(9306),a=i(8551),o=i(1767),l=i(9462),h=i(6319),c=i(6395),d=l((function(){for(var t,e,i=this.iterator,s=this.predicate,r=this.next;;){t=a(n(r,i));if(this.done=!!t.done)return;e=t.value;if(h(i,s,[e,this.counter++],!0))return e}}));s({target:"Iterator",proto:!0,real:!0,forced:c},{filter:function filter(t){a(this);r(t);return new d(o(this),{predicate:t})}})},531:(t,e,i)=>{var s=i(6518),n=i(9565),r=i(9306),a=i(8551),o=i(1767),l=i(8646),h=i(9462),c=i(9539),d=i(6395),u=h((function(){for(var t,e,i=this.iterator,s=this.mapper;;){if(e=this.inner)try{if(!(t=a(n(e.next,e.iterator))).done)return t.value;this.inner=null}catch(t){c(i,"throw",t)}t=a(n(this.next,i));if(this.done=!!t.done)return;try{this.inner=l(s(t.value,this.counter++),!1)}catch(t){c(i,"throw",t)}}}));s({target:"Iterator",proto:!0,real:!0,forced:d},{flatMap:function flatMap(t){a(this);r(t);return new u(o(this),{mapper:t,inner:null})}})},1701:(t,e,i)=>{var s=i(6518),n=i(713);s({target:"Iterator",proto:!0,real:!0,forced:i(6395)},{map:n})},3579:(t,e,i)=>{var s=i(6518),n=i(2652),r=i(9306),a=i(8551),o=i(1767);s({target:"Iterator",proto:!0,real:!0},{some:function some(t){a(this);r(t);var e=o(this),i=0;return n(e,(function(e,s){if(t(e,i++))return s()}),{IS_RECORD:!0,INTERRUPTED:!0}).stopped}})},1689:(t,e,i)=>{var s=i(6518),n=i(4576),r=i(8745),a=i(7680),o=i(6043),l=i(9306),h=i(1103),c=n.Promise,d=!1;s({target:"Promise",stat:!0,forced:!c||!c.try||h((function(){c.try((function(t){d=8===t}),8)})).error||!d},{try:function(t){var e=arguments.length>1?a(arguments,1):[],i=o.f(this),s=h((function(){return r(l(t),void 0,e)}));(s.error?i.reject:i.resolve)(s.value);return i.promise}})},4628:(t,e,i)=>{var s=i(6518),n=i(6043);s({target:"Promise",stat:!0},{withResolvers:function withResolvers(){var t=n.f(this);return{promise:t.promise,resolve:t.resolve,reject:t.reject}}})},7642:(t,e,i)=>{var s=i(6518),n=i(3440);s({target:"Set",proto:!0,real:!0,forced:!i(4916)("difference")},{difference:n})},8004:(t,e,i)=>{var s=i(6518),n=i(9039),r=i(8750);s({target:"Set",proto:!0,real:!0,forced:!i(4916)("intersection")||n((function(){return"3,2"!==String(Array.from(new Set([1,2,3]).intersection(new Set([3,2]))))}))},{intersection:r})},3853:(t,e,i)=>{var s=i(6518),n=i(4449);s({target:"Set",proto:!0,real:!0,forced:!i(4916)("isDisjointFrom")},{isDisjointFrom:n})},5876:(t,e,i)=>{var s=i(6518),n=i(3838);s({target:"Set",proto:!0,real:!0,forced:!i(4916)("isSubsetOf")},{isSubsetOf:n})},2475:(t,e,i)=>{var s=i(6518),n=i(8527);s({target:"Set",proto:!0,real:!0,forced:!i(4916)("isSupersetOf")},{isSupersetOf:n})},5024:(t,e,i)=>{var s=i(6518),n=i(3650);s({target:"Set",proto:!0,real:!0,forced:!i(4916)("symmetricDifference")},{symmetricDifference:n})},1698:(t,e,i)=>{var s=i(6518),n=i(4204);s({target:"Set",proto:!0,real:!0,forced:!i(4916)("union")},{union:n})},7467:(t,e,i)=>{var s=i(7628),n=i(4644),r=n.aTypedArray,a=n.exportTypedArrayMethod,o=n.getTypedArrayConstructor;a("toReversed",(function toReversed(){return s(r(this),o(this))}))},4732:(t,e,i)=>{var s=i(4644),n=i(9504),r=i(9306),a=i(5370),o=s.aTypedArray,l=s.getTypedArrayConstructor,h=s.exportTypedArrayMethod,c=n(s.TypedArrayPrototype.sort);h("toSorted",(function toSorted(t){void 0!==t&&r(t);var e=o(this),i=a(l(e),e);return c(i,t)}))},9577:(t,e,i)=>{var s=i(9928),n=i(4644),r=i(1108),a=i(1291),o=i(5854),l=n.aTypedArray,h=n.getTypedArrayConstructor,c=n.exportTypedArrayMethod,d=!!function(){try{new Int8Array(1).with(2,{valueOf:function(){throw 8}})}catch(t){return 8===t}}();c("with",{with:function(t,e){var i=l(this),n=a(t),c=r(i)?o(e):+e;return s(i,h(i),n,c)}}.with,!d)},8992:(t,e,i)=>{i(8111)},4743:(t,e,i)=>{i(9314)},3215:(t,e,i)=>{i(1148)},4520:(t,e,i)=>{i(2489)},670:(t,e,i)=>{i(531)},1454:(t,e,i)=>{i(1701)},7550:(t,e,i)=>{i(3579)},8335:(t,e,i)=>{var s=i(6518),n=i(3724),r=i(4576),a=i(7751),o=i(9504),l=i(9565),h=i(4901),c=i(34),d=i(4376),u=i(9297),p=i(655),g=i(6198),f=i(4659),m=i(9039),b=i(8235),v=i(4495),y=r.JSON,w=r.Number,A=r.SyntaxError,x=y&&y.parse,_=a("Object","keys"),E=Object.getOwnPropertyDescriptor,S=o("".charAt),C=o("".slice),T=o(/./.exec),M=o([].push),P=/^\d$/,D=/^[1-9]$/,k=/^[\d-]$/,R=/^[\t\n\r ]$/,internalize=function(t,e,i,s){var n,r,a,o,h,p=t[e],f=s&&p===s.value,m=f&&"string"==typeof s.source?{source:s.source}:{};if(c(p)){var b=d(p),v=f?s.nodes:b?[]:{};if(b){n=v.length;a=g(p);for(o=0;o{i(1689)},4979:(t,e,i)=>{var s=i(6518),n=i(4576),r=i(7751),a=i(6980),o=i(4913).f,l=i(9297),h=i(679),c=i(3167),d=i(2603),u=i(5002),p=i(8574),g=i(3724),f=i(6395),m="DOMException",b=r("Error"),v=r(m),y=function DOMException(){h(this,w);var t=arguments.length,e=d(t<1?void 0:arguments[0]),i=d(t<2?void 0:arguments[1],"Error"),s=new v(e,i),n=new b(e);n.name=m;o(s,"stack",a(1,p(n.stack,1)));c(s,this,y);return s},w=y.prototype=v.prototype,A="stack"in new b(m),x="stack"in new v(1,2),_=v&&g&&Object.getOwnPropertyDescriptor(n,m),E=!(!_||_.writable&&_.configurable),S=A&&!E&&!x;s({global:!0,constructor:!0,forced:f||S},{DOMException:S?y:v});var C=r(m),T=C.prototype;if(T.constructor!==C){f||o(T,"constructor",a(1,C));for(var M in u)if(l(u,M)){var P=u[M],D=P.s;l(C,D)||o(C,D,a(6,P.c))}}},4603:(t,e,i)=>{var s=i(6840),n=i(9504),r=i(655),a=i(2812),o=URLSearchParams,l=o.prototype,h=n(l.append),c=n(l.delete),d=n(l.forEach),u=n([].push),p=new o("a=1&a=2&b=3");p.delete("a",1);p.delete("b",void 0);p+""!="a=2"&&s(l,"delete",(function(t){var e=arguments.length,i=e<2?void 0:arguments[1];if(e&&void 0===i)return c(this,t);var s=[];d(this,(function(t,e){u(s,{key:e,value:t})}));a(e,1);for(var n,o=r(t),l=r(i),p=0,g=0,f=!1,m=s.length;p{var s=i(6840),n=i(9504),r=i(655),a=i(2812),o=URLSearchParams,l=o.prototype,h=n(l.getAll),c=n(l.has),d=new o("a=1");!d.has("a",2)&&d.has("a",void 0)||s(l,"has",(function has(t){var e=arguments.length,i=e<2?void 0:arguments[1];if(e&&void 0===i)return c(this,t);var s=h(this,t);a(e,1);for(var n=r(i),o=0;o{var s=i(3724),n=i(9504),r=i(2106),a=URLSearchParams.prototype,o=n(a.forEach);s&&!("size"in a)&&r(a,"size",{get:function size(){var t=0;o(this,(function(){t++}));return t},configurable:!0,enumerable:!0})}},e={};function __webpack_require__(i){var s=e[i];if(void 0!==s)return s.exports;var n=e[i]={exports:{}};t[i].call(n.exports,n,n.exports,__webpack_require__);return n.exports}__webpack_require__.d=(t,e)=>{for(var i in e)__webpack_require__.o(e,i)&&!__webpack_require__.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})};__webpack_require__.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var __webpack_exports__ = globalThis.pdfjsLib = {};__webpack_require__.d(__webpack_exports__,{AbortException:()=>AbortException,AnnotationEditorLayer:()=>AnnotationEditorLayer,AnnotationEditorParamsType:()=>m,AnnotationEditorType:()=>f,AnnotationEditorUIManager:()=>AnnotationEditorUIManager,AnnotationLayer:()=>AnnotationLayer,AnnotationMode:()=>g,ColorPicker:()=>ColorPicker,DOMSVGFactory:()=>DOMSVGFactory,DrawLayer:()=>DrawLayer,FeatureTest:()=>util_FeatureTest,GlobalWorkerOptions:()=>GlobalWorkerOptions,ImageKind:()=>E,InvalidPDFException:()=>InvalidPDFException,MissingPDFException:()=>MissingPDFException,OPS:()=>K,OutputScale:()=>OutputScale,PDFDataRangeTransport:()=>PDFDataRangeTransport,PDFDateString:()=>PDFDateString,PDFWorker:()=>PDFWorker,PasswordResponses:()=>Q,PermissionFlag:()=>b,PixelsPerInch:()=>PixelsPerInch,RenderingCancelledException:()=>RenderingCancelledException,TextLayer:()=>TextLayer,TouchManager:()=>TouchManager,UnexpectedResponseException:()=>UnexpectedResponseException,Util:()=>Util,VerbosityLevel:()=>Y,XfaLayer:()=>XfaLayer,build:()=>Ht,createValidAbsoluteUrl:()=>createValidAbsoluteUrl,fetchData:()=>fetchData,getDocument:()=>getDocument,getFilenameFromUrl:()=>getFilenameFromUrl,getPdfFilenameFromUrl:()=>getPdfFilenameFromUrl,getXfaPageViewport:()=>getXfaPageViewport,isDataScheme:()=>isDataScheme,isPdfFile:()=>isPdfFile,noContextMenu:()=>noContextMenu,normalizeUnicode:()=>normalizeUnicode,setLayerDimensions:()=>setLayerDimensions,shadow:()=>shadow,stopEvent:()=>stopEvent,version:()=>Bt});__webpack_require__(4114),__webpack_require__(6573),__webpack_require__(8100),__webpack_require__(7936),__webpack_require__(7467),__webpack_require__(4732),__webpack_require__(9577),__webpack_require__(5247),__webpack_require__(4979),__webpack_require__(4603),__webpack_require__(7566),__webpack_require__(8721);const i=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),s=[1,0,0,1,0,0],n=[.001,0,0,.001,0,0],r=1.35,a=1,o=2,l=4,h=16,c=32,d=64,u=128,p=256,g={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},f={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},m={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},b={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},v=0,y=1,w=2,A=3,x=3,_=4,E={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},S=1,C=2,T=3,M=4,P=5,D=6,k=7,R=8,I=9,L=10,O=11,N=12,B=13,H=14,U=15,z=16,j=17,G=20,V=1,$=2,W=3,q=4,X=5,Y={ERRORS:0,WARNINGS:1,INFOS:5},K={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},Q={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let J=Y.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(J=t)}function getVerbosityLevel(){return J}function info(t){J>=Y.INFOS&&console.log(`Info: ${t}`)}function warn(t){J>=Y.WARNINGS&&console.log(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;try{if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const s=e?new URL(t,e):new URL(t);if(function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(s))return s}catch{}return null}function shadow(t,e,i,s=!1){Object.defineProperty(t,e,{value:i,enumerable:!s,configurable:!0,writable:!1});return i}const Z=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends Z{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends Z{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends Z{constructor(t){super(t,"InvalidPDFException")}}class MissingPDFException extends Z{constructor(t){super(t,"MissingPDFException")}}class UnexpectedResponseException extends Z{constructor(t,e){super(t,"UnexpectedResponseException");this.status=e}}class FormatError extends Z{constructor(t){super(t,"FormatError")}}class AbortException extends Z{constructor(t){super(t,"AbortException")}}function bytesToString(t){"object"==typeof t&&void 0!==t?.length||unreachable("Invalid argument for bytesToString");const e=t.length,i=8192;if(et.toString(16).padStart(2,"0")));class Util{static makeHexColor(t,e,i){return`#${tt[t]}${tt[e]}${tt[i]}`}static scaleMinMax(t,e){let i;if(t[0]){if(t[0]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[0];e[2]*=t[0];if(t[3]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[3];e[3]*=t[3]}else{i=e[0];e[0]=e[1];e[1]=i;i=e[2];e[2]=e[3];e[3]=i;if(t[1]<0){i=e[1];e[1]=e[3];e[3]=i}e[1]*=t[1];e[3]*=t[1];if(t[2]<0){i=e[0];e[0]=e[2];e[2]=i}e[0]*=t[2];e[2]*=t[2]}e[0]+=t[4];e[1]+=t[5];e[2]+=t[4];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const i=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/i,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/i]}static getAxialAlignedBoundingBox(t,e){const i=this.applyTransform(t,e),s=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),r=this.applyTransform([t[2],t[1]],e);return[Math.min(i[0],s[0],n[0],r[0]),Math.min(i[1],s[1],n[1],r[1]),Math.max(i[0],s[0],n[0],r[0]),Math.max(i[1],s[1],n[1],r[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],i=t[0]*e[0]+t[1]*e[2],s=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],r=t[2]*e[1]+t[3]*e[3],a=(i+r)/2,o=Math.sqrt((i+r)**2-4*(i*r-n*s))/2,l=a+o||1,h=a-o||1;return[Math.sqrt(l),Math.sqrt(h)]}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const i=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),s=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(i>s)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>r?null:[i,n,s,r]}static#t(t,e,i,s,n,r,a,o,l,h){if(l<=0||l>=1)return;const c=1-l,d=l*l,u=d*l,p=c*(c*(c*t+3*l*e)+3*d*i)+u*s,g=c*(c*(c*n+3*l*r)+3*d*a)+u*o;h[0]=Math.min(h[0],p);h[1]=Math.min(h[1],g);h[2]=Math.max(h[2],p);h[3]=Math.max(h[3],g)}static#e(t,e,i,s,n,r,a,o,l,h,c,d){if(Math.abs(l)<1e-12){Math.abs(h)>=1e-12&&this.#t(t,e,i,s,n,r,a,o,-c/h,d);return}const u=h**2-4*c*l;if(u<0)return;const p=Math.sqrt(u),g=2*l;this.#t(t,e,i,s,n,r,a,o,(-h+p)/g,d);this.#t(t,e,i,s,n,r,a,o,(-h-p)/g,d)}static bezierBoundingBox(t,e,i,s,n,r,a,o,l){if(l){l[0]=Math.min(l[0],t,a);l[1]=Math.min(l[1],e,o);l[2]=Math.max(l[2],t,a);l[3]=Math.max(l[3],e,o)}else l=[Math.min(t,a),Math.min(e,o),Math.max(t,a),Math.max(e,o)];this.#e(t,i,n,a,e,s,r,o,3*(3*(i-n)-t+a),6*(t-2*i+n),3*(i-t),l);this.#e(t,i,n,a,e,s,r,o,3*(3*(s-r)-e+o),6*(e-2*s+r),3*(s-e),l);return l}}let et=null,it=null;function normalizeUnicode(t){if(!et){et=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;it=new Map([["ſt","ſt"]])}return t.replaceAll(et,((t,e,i)=>e?e.normalize("NFKC"):it.get(i)))}const st="pdfjs_internal_id_";__webpack_require__(4628),__webpack_require__(7642),__webpack_require__(8004),__webpack_require__(3853),__webpack_require__(5876),__webpack_require__(2475),__webpack_require__(5024),__webpack_require__(1698),__webpack_require__(1454),__webpack_require__(8992),__webpack_require__(4743),__webpack_require__(3215),__webpack_require__(7550),__webpack_require__(8335);const nt="http://www.w3.org/2000/svg";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function fetchData(t,e="text"){if(isValidFetchUrl(t,document.baseURI)){const i=await fetch(t);if(!i.ok)throw new Error(i.statusText);switch(e){case"arraybuffer":return i.arrayBuffer();case"blob":return i.blob();case"json":return i.json()}return i.text()}return new Promise(((i,s)=>{const n=new XMLHttpRequest;n.open("GET",t,!0);n.responseType=e;n.onreadystatechange=()=>{if(n.readyState===XMLHttpRequest.DONE)if(200!==n.status&&0!==n.status)s(new Error(n.statusText));else{switch(e){case"arraybuffer":case"blob":case"json":i(n.response);return}i(n.responseText)}};n.send(null)}))}class PageViewport{constructor({viewBox:t,userUnit:e,scale:i,rotation:s,offsetX:n=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t;this.userUnit=e;this.scale=i;this.rotation=s;this.offsetX=n;this.offsetY=r;i*=e;const o=(t[2]+t[0])/2,l=(t[3]+t[1])/2;let h,c,d,u,p,g,f,m;(s%=360)<0&&(s+=360);switch(s){case 180:h=-1;c=0;d=0;u=1;break;case 90:h=0;c=1;d=1;u=0;break;case 270:h=0;c=-1;d=-1;u=0;break;case 0:h=1;c=0;d=0;u=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(a){d=-d;u=-u}if(0===h){p=Math.abs(l-t[1])*i+n;g=Math.abs(o-t[0])*i+r;f=(t[3]-t[1])*i;m=(t[2]-t[0])*i}else{p=Math.abs(o-t[0])*i+n;g=Math.abs(l-t[1])*i+r;f=(t[2]-t[0])*i;m=(t[3]-t[1])*i}this.transform=[h*i,c*i,d*i,u*i,p-h*i*o-d*i*l,g-c*i*o-u*i*l];this.width=f;this.height=m}get rawDims(){const{userUnit:t,viewBox:e}=this,i=e.map((e=>e*t));return shadow(this,"rawDims",{pageWidth:i[2]-i[0],pageHeight:i[3]-i[1],pageX:i[0],pageY:i[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:i=this.offsetX,offsetY:s=this.offsetY,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}convertToViewportPoint(t,e){return Util.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=Util.applyTransform([t[0],t[1]],this.transform),i=Util.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],i[0],i[1]]}convertToPdfPoint(t,e){return Util.applyInverseTransform([t,e],this.transform)}}class RenderingCancelledException extends Z{constructor(t,e=0){super(t,"RenderingCancelledException");this.extraDelay=e}}function isDataScheme(t){const e=t.length;let i=0;for(;i=1&&s<=12?s-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let a=parseInt(e[5],10);a=a>=0&&a<=59?a:0;let o=parseInt(e[6],10);o=o>=0&&o<=59?o:0;const l=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let c=parseInt(e[9],10)||0;c=c>=0&&c<=59?c:0;if("-"===l){r+=h;a+=c}else if("+"===l){r-=h;a-=c}return new Date(Date.UTC(i,s,n,r,a,o))}}function getXfaPageViewport(t,{scale:e=1,rotation:i=0}){const{width:s,height:n}=t.attributes.style,r=[0,0,parseInt(s),parseInt(n)];return new PageViewport({viewBox:r,userUnit:1,scale:e,rotation:i})}function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map((t=>parseInt(t)));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3);warn(`Not a valid color format: "${t}"`);return[0,0,0]}function getCurrentTransform(t){const{a:e,b:i,c:s,d:n,e:r,f:a}=t.getTransform();return[e,i,s,n,r,a]}function getCurrentTransformInverse(t){const{a:e,b:i,c:s,d:n,e:r,f:a}=t.getTransform().invertSelf();return[e,i,s,n,r,a]}function setLayerDimensions(t,e,i=!1,s=!0){if(e instanceof PageViewport){const{pageWidth:s,pageHeight:n}=e.rawDims,{style:r}=t,a=util_FeatureTest.isCSSRoundSupported,o=`var(--scale-factor) * ${s}px`,l=`var(--scale-factor) * ${n}px`,h=a?`round(down, ${o}, var(--scale-round-x, 1px))`:`calc(${o})`,c=a?`round(down, ${l}, var(--scale-round-y, 1px))`:`calc(${l})`;if(i&&e.rotation%180!=0){r.width=c;r.height=h}else{r.width=h;r.height=c}}s&&t.setAttribute("data-main-rotation",e.rotation)}class OutputScale{constructor(){const t=window.devicePixelRatio||1;this.sx=t;this.sy=t}get scaled(){return 1!==this.sx||1!==this.sy}get symmetric(){return this.sx===this.sy}}class EditorToolbar{#s=null;#n=null;#r;#a=null;#o=null;static#l=null;constructor(t){this.#r=t;EditorToolbar.#l||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#s=document.createElement("div");t.classList.add("editToolbar","hidden");t.setAttribute("role","toolbar");const e=this.#r._uiManager._signal;t.addEventListener("contextmenu",noContextMenu,{signal:e});t.addEventListener("pointerdown",EditorToolbar.#h,{signal:e});const i=this.#a=document.createElement("div");i.className="buttons";t.append(i);const s=this.#r.toolbarPosition;if(s){const{style:e}=t,i="ltr"===this.#r._uiManager.direction?1-s[0]:s[0];e.insetInlineEnd=100*i+"%";e.top=`calc(${100*s[1]}% + var(--editor-toolbar-vert-offset))`}this.#c();return t}get div(){return this.#s}static#h(t){t.stopPropagation()}#d(t){this.#r._focusEventsAllowed=!1;stopEvent(t)}#u(t){this.#r._focusEventsAllowed=!0;stopEvent(t)}#p(t){const e=this.#r._uiManager._signal;t.addEventListener("focusin",this.#d.bind(this),{capture:!0,signal:e});t.addEventListener("focusout",this.#u.bind(this),{capture:!0,signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e})}hide(){this.#s.classList.add("hidden");this.#n?.hideDropdown()}show(){this.#s.classList.remove("hidden");this.#o?.shown()}#c(){const{editorType:t,_uiManager:e}=this.#r,i=document.createElement("button");i.className="delete";i.tabIndex=0;i.setAttribute("data-l10n-id",EditorToolbar.#l[t]);this.#p(i);i.addEventListener("click",(t=>{e.delete()}),{signal:e._signal});this.#a.append(i)}get#g(){const t=document.createElement("div");t.className="divider";return t}async addAltText(t){const e=await t.render();this.#p(e);this.#a.prepend(e,this.#g);this.#o=t}addColorPicker(t){this.#n=t;const e=t.renderButton();this.#p(e);this.#a.prepend(e,this.#g)}remove(){this.#s.remove();this.#n?.destroy();this.#n=null}}class HighlightToolbar{#a=null;#s=null;#f;constructor(t){this.#f=t}#m(){const t=this.#s=document.createElement("div");t.className="editToolbar";t.setAttribute("role","toolbar");t.addEventListener("contextmenu",noContextMenu,{signal:this.#f._signal});const e=this.#a=document.createElement("div");e.className="buttons";t.append(e);this.#b();return t}#v(t,e){let i=0,s=0;for(const n of t){const t=n.y+n.height;if(ti){s=r;i=t}else e?r>s&&(s=r):r{this.#f.highlightSelection("floating_button")}),{signal:i});this.#a.append(t)}}function bindEvents(t,e,i){for(const s of i)e.addEventListener(s,t[s].bind(t))}class IdManager{#y=0;get id(){return"pdfjs_internal_editor_"+this.#y++}}class ImageManager{#w=function getUuid(){if("function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=new Uint8Array(32);crypto.getRandomValues(t);return bytesToString(t)}();#y=0;#A=null;static get _isSVGFittingCanvas(){const t=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),e=new Image;e.src='data:image/svg+xml;charset=UTF-8,';return shadow(this,"_isSVGFittingCanvas",e.decode().then((()=>{t.drawImage(e,0,0,1,1,0,0,1,3);return 0===new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]})))}async#x(t,e){this.#A||=new Map;let i=this.#A.get(t);if(null===i)return null;if(i?.bitmap){i.refCounter+=1;return i}try{i||={bitmap:null,id:`image_${this.#w}_${this.#y++}`,refCounter:0,isSvg:!1};let t;if("string"==typeof e){i.url=e;t=await fetchData(e,"blob")}else e instanceof File?t=i.file=e:e instanceof Blob&&(t=e);if("image/svg+xml"===t.type){const e=ImageManager._isSVGFittingCanvas,s=new FileReader,n=new Image,r=new Promise(((t,r)=>{n.onload=()=>{i.bitmap=n;i.isSvg=!0;t()};s.onload=async()=>{const t=i.svgUrl=s.result;n.src=await e?`${t}#svgView(preserveAspectRatio(none))`:t};n.onerror=s.onerror=r}));s.readAsDataURL(t);await r}else i.bitmap=await createImageBitmap(t);i.refCounter=1}catch(t){warn(t);i=null}this.#A.set(t,i);i&&this.#A.set(i.id,i);return i}async getFromFile(t){const{lastModified:e,name:i,size:s,type:n}=t;return this.#x(`${e}_${i}_${s}_${n}`,t)}async getFromUrl(t){return this.#x(t,t)}async getFromBlob(t,e){const i=await e;return this.#x(t,i)}async getFromId(t){this.#A||=new Map;const e=this.#A.get(t);if(!e)return null;if(e.bitmap){e.refCounter+=1;return e}if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:t}=e;delete e.blobPromise;return this.getFromBlob(e.id,t)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#A||=new Map;let i=this.#A.get(t);if(i?.bitmap){i.refCounter+=1;return i}const s=new OffscreenCanvas(e.width,e.height);s.getContext("2d").drawImage(e,0,0);i={bitmap:s.transferToImageBitmap(),id:`image_${this.#w}_${this.#y++}`,refCounter:1,isSvg:!1};this.#A.set(t,i);this.#A.set(i.id,i);return i}getSvgUrl(t){const e=this.#A.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#A||=new Map;const e=this.#A.get(t);if(!e)return;e.refCounter-=1;if(0!==e.refCounter)return;const{bitmap:i}=e;if(!e.url&&!e.file){const t=new OffscreenCanvas(i.width,i.height);t.getContext("bitmaprenderer").transferFromImageBitmap(i);e.blobPromise=t.convertToBlob()}i.close?.();e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#w}_`)}}class CommandManager{#_=[];#E=!1;#S;#C=-1;constructor(t=128){this.#S=t}add({cmd:t,undo:e,post:i,mustExec:s,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){s&&t();if(this.#E)return;const o={cmd:t,undo:e,post:i,type:n};if(-1===this.#C){this.#_.length>0&&(this.#_.length=0);this.#C=0;this.#_.push(o);return}if(r&&this.#_[this.#C].type===n){a&&(o.undo=this.#_[this.#C].undo);this.#_[this.#C]=o;return}const l=this.#C+1;if(l===this.#S)this.#_.splice(0,1);else{this.#C=l;l=0;e--)if(this.#_[e].type!==t){this.#_.splice(e+1,this.#C-e);this.#C=e;return}this.#_.length=0;this.#C=-1}}destroy(){this.#_=null}}class KeyboardManager{constructor(t){this.buffer=[];this.callbacks=new Map;this.allKeys=new Set;const{isMac:e}=util_FeatureTest.platform;for(const[i,s,n={}]of t)for(const t of i){const i=t.startsWith("mac+");if(e&&i){this.callbacks.set(t.slice(4),{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}else if(!e&&!i){this.callbacks.set(t,{callback:s,options:n});this.allKeys.add(t.split("+").at(-1))}}}#T(t){t.altKey&&this.buffer.push("alt");t.ctrlKey&&this.buffer.push("ctrl");t.metaKey&&this.buffer.push("meta");t.shiftKey&&this.buffer.push("shift");this.buffer.push(t.key);const e=this.buffer.join("+");this.buffer.length=0;return e}exec(t,e){if(!this.allKeys.has(e.key))return;const i=this.callbacks.get(this.#T(e));if(!i)return;const{callback:s,options:{bubbles:n=!1,args:r=[],checker:a=null}}=i;if(!a||a(t,e)){s.bind(t,...r,e)();n||stopEvent(e)}}}class ColorManager{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);!function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";document.body.append(e);for(const i of t.keys()){e.style.color=i;const s=window.getComputedStyle(e).color;t.set(i,getRGB(s))}e.remove()}(t);return shadow(this,"_colors",t)}convert(t){const e=getRGB(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[t,i]of this._colors)if(i.every(((t,i)=>t===e[i])))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?Util.makeHexColor(...e):t}}class AnnotationEditorUIManager{#M=new AbortController;#P=null;#D=new Map;#k=new Map;#R=null;#I=null;#F=null;#L=new CommandManager;#O=null;#N=null;#B=0;#H=new Set;#U=null;#z=null;#j=new Set;_editorUndoBar=null;#G=!1;#V=!1;#$=!1;#W=null;#q=null;#X=null;#Y=null;#K=!1;#Q=null;#J=new IdManager;#Z=!1;#tt=!1;#et=null;#it=null;#st=null;#nt=null;#rt=f.NONE;#at=new Set;#ot=null;#lt=null;#ht=null;#ct={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#dt=[0,0];#ut=null;#pt=null;#gt=null;#ft=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=AnnotationEditorUIManager.prototype,arrowChecker=t=>t.#pt.contains(document.activeElement)&&"BUTTON"!==document.activeElement.tagName&&t.hasSomethingToControl(),textInputChecker=(t,{target:e})=>{if(e instanceof HTMLInputElement){const{type:t}=e;return"text"!==t&&"number"!==t}return!0},e=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:textInputChecker}],[["ctrl+z","mac+meta+z"],t.undo,{checker:textInputChecker}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:textInputChecker}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:textInputChecker}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(e)&&!t.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(t,{target:e})=>!(e instanceof HTMLButtonElement)&&t.#pt.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:arrowChecker}]]))}constructor(t,e,i,s,n,r,a,o,l,h,c,d,u){const p=this._signal=this.#M.signal;this.#pt=t;this.#gt=e;this.#R=i;this._eventBus=s;s._on("editingaction",this.onEditingAction.bind(this),{signal:p});s._on("pagechanging",this.onPageChanging.bind(this),{signal:p});s._on("scalechanging",this.onScaleChanging.bind(this),{signal:p});s._on("rotationchanging",this.onRotationChanging.bind(this),{signal:p});s._on("setpreference",this.onSetPreference.bind(this),{signal:p});s._on("switchannotationeditorparams",(t=>this.updateParams(t.type,t.value)),{signal:p});this.#mt();this.#bt();this.#vt();this.#I=n.annotationStorage;this.#W=n.filterFactory;this.#lt=r;this.#Y=a||null;this.#G=o;this.#V=l;this.#$=h;this.#nt=c||null;this.viewParameters={realScale:PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0};this.isShiftKeyDown=!1;this._editorUndoBar=d||null;this._supportsPinchToZoom=!1!==u}destroy(){this.#ft?.resolve();this.#ft=null;this.#M?.abort();this.#M=null;this._signal=null;for(const t of this.#k.values())t.destroy();this.#k.clear();this.#D.clear();this.#j.clear();this.#P=null;this.#at.clear();this.#L.destroy();this.#R?.destroy();this.#Q?.hide();this.#Q=null;if(this.#q){clearTimeout(this.#q);this.#q=null}if(this.#ut){clearTimeout(this.#ut);this.#ut=null}this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#nt}get useNewAltTextFlow(){return this.#V}get useNewAltTextWhenAddingImage(){return this.#$}get hcmFilter(){return shadow(this,"hcmFilter",this.#lt?this.#W.addHCMFilter(this.#lt.foreground,this.#lt.background):"none")}get direction(){return shadow(this,"direction",getComputedStyle(this.#pt).direction)}get highlightColors(){return shadow(this,"highlightColors",this.#Y?new Map(this.#Y.split(",").map((t=>t.split("=").map((t=>t.trim()))))):null)}get highlightColorNames(){return shadow(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(t=>t.reverse()))):null)}setCurrentDrawingSession(t){if(t){this.unselectAll();this.disableUserSelect(!0)}else this.disableUserSelect(!1);this.#N=t}setMainHighlightColorPicker(t){this.#st=t}editAltText(t,e=!1){this.#R?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal});this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){if("enableNewAltTextWhenAddingImage"===t)this.#$=e}onPageChanging({pageNumber:t}){this.#B=t-1}focusMainContainer(){this.#pt.focus()}findParent(t,e){for(const i of this.#k.values()){const{x:s,y:n,width:r,height:a}=i.div.getBoundingClientRect();if(t>=s&&t<=s+r&&e>=n&&e<=n+a)return i}return null}disableUserSelect(t=!1){this.#gt.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#j.add(t)}removeShouldRescale(t){this.#j.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#j)t.onScaleChanging();this.#N?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}#yt({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#wt(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const e of this.#k.values())if(e.hasTextLayer(t))return e;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:r}=e,a=e.toString(),o=this.#yt(e).closest(".textLayer"),l=this.getSelectionBoxes(o);if(!l)return;e.empty();const h=this.#wt(o),c=this.#rt===f.NONE,callback=()=>{h?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:l,anchorNode:i,anchorOffset:s,focusNode:n,focusOffset:r,text:a});c&&this.showAllEditors("highlight",!0,!0)};c?this.switchToMode(f.HIGHLIGHT,callback):callback()}#At(){const t=document.getSelection();if(!t||t.isCollapsed)return;const e=this.#yt(t).closest(".textLayer"),i=this.getSelectionBoxes(e);if(i){this.#Q||=new HighlightToolbar(this);this.#Q.show(e,i,"ltr"===this.direction)}}addToAnnotationStorage(t){t.isEmpty()||!this.#I||this.#I.has(t.id)||this.#I.setValue(t.id,t)}#xt(){const t=document.getSelection();if(!t||t.isCollapsed){if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}return}const{anchorNode:e}=t;if(e===this.#ot)return;const i=this.#yt(t).closest(".textLayer");if(i){this.#Q?.hide();this.#ot=e;this.#_t({hasSelectedText:!0});if(this.#rt===f.HIGHLIGHT||this.#rt===f.NONE){this.#rt===f.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0);this.#K=this.isShiftKeyDown;if(!this.isShiftKeyDown){const t=this.#rt===f.HIGHLIGHT?this.#wt(i):null;t?.toggleDrawing();const e=new AbortController,s=this.combinedSignal(e),pointerup=i=>{if("pointerup"!==i.type||0===i.button){e.abort();t?.toggleDrawing(!0);"pointerup"===i.type&&this.#Et("main_toolbar")}};window.addEventListener("pointerup",pointerup,{signal:s});window.addEventListener("blur",pointerup,{signal:s})}}}else if(this.#ot){this.#Q?.hide();this.#ot=null;this.#_t({hasSelectedText:!1})}}#Et(t=""){this.#rt===f.HIGHLIGHT?this.highlightSelection(t):this.#G&&this.#At()}#mt(){document.addEventListener("selectionchange",this.#xt.bind(this),{signal:this._signal})}#St(){if(this.#X)return;this.#X=new AbortController;const t=this.combinedSignal(this.#X);window.addEventListener("focus",this.focus.bind(this),{signal:t});window.addEventListener("blur",this.blur.bind(this),{signal:t})}#Ct(){this.#X?.abort();this.#X=null}blur(){this.isShiftKeyDown=!1;if(this.#K){this.#K=!1;this.#Et("main_toolbar")}if(!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#at)if(e.div.contains(t)){this.#it=[e,t];e._focusEventsAllowed=!1;break}}focus(){if(!this.#it)return;const[t,e]=this.#it;this.#it=null;e.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this._signal});e.focus()}#vt(){if(this.#et)return;this.#et=new AbortController;const t=this.combinedSignal(this.#et);window.addEventListener("keydown",this.keydown.bind(this),{signal:t});window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#Tt(){this.#et?.abort();this.#et=null}#Mt(){if(this.#O)return;this.#O=new AbortController;const t=this.combinedSignal(this.#O);document.addEventListener("copy",this.copy.bind(this),{signal:t});document.addEventListener("cut",this.cut.bind(this),{signal:t});document.addEventListener("paste",this.paste.bind(this),{signal:t})}#Pt(){this.#O?.abort();this.#O=null}#bt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t});document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#vt();this.#Mt()}removeEditListeners(){this.#Tt();this.#Pt()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const i of this.#z)if(i.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy";t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const i of this.#z)if(i.isHandlingMimeForPasting(e.type)){i.paste(e,this.currentLayer);t.preventDefault();return}}copy(t){t.preventDefault();this.#P?.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#at){const i=t.serialize(!0);i&&e.push(i)}0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t);this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const t of e.items)for(const e of this.#z)if(e.isHandlingMimeForPasting(t.type)){e.paste(t,this.currentLayer);return}let i=e.getData("application/pdfjs");if(!i)return;try{i=JSON.parse(i)}catch(t){warn(`paste: "${t.message}".`);return}if(!Array.isArray(i))return;this.unselectAll();const s=this.currentLayer;try{const t=[];for(const e of i){const i=await s.deserialize(e);if(!i)return;t.push(i)}const cmd=()=>{for(const e of t)this.#Dt(e);this.#kt(t)},undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd,undo,mustExec:!0})}catch(t){warn(`paste: "${t.message}".`)}}keydown(t){this.isShiftKeyDown||"Shift"!==t.key||(this.isShiftKeyDown=!0);this.#rt===f.NONE||this.isEditorHandlingKeyboard||AnnotationEditorUIManager._keyboardManager.exec(this,t)}keyup(t){if(this.isShiftKeyDown&&"Shift"===t.key){this.isShiftKeyDown=!1;if(this.#K){this.#K=!1;this.#Et("main_toolbar")}}}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#_t(t){if(Object.entries(t).some((([t,e])=>this.#ct[t]!==e))){this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#ct,t)});this.#rt===f.HIGHLIGHT&&!1===t.hasSelectedEditor&&this.#Rt([[m.HIGHLIGHT_FREE,!0]])}}#Rt(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#St();this.#Mt();this.#_t({isEditing:this.#rt!==f.NONE,isEmpty:this.#It(),hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:this.#L.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Ct();this.#Pt();this.#_t({isEditing:!1});this.disableUserSelect(!1)}}registerEditorTypes(t){if(!this.#z){this.#z=t;for(const t of this.#z)this.#Rt(t.defaultPropertiesToUpdate)}}getId(){return this.#J.id}get currentLayer(){return this.#k.get(this.#B)}getLayer(t){return this.#k.get(t)}get currentPageIndex(){return this.#B}addLayer(t){this.#k.set(t.pageIndex,t);this.#Z?t.enable():t.disable()}removeLayer(t){this.#k.delete(t.pageIndex)}async updateMode(t,e=null,i=!1){if(this.#rt!==t){if(this.#ft){await this.#ft.promise;if(!this.#ft)return}this.#ft=Promise.withResolvers();this.#rt=t;if(t!==f.NONE){this.setEditingState(!0);await this.#Ft();this.unselectAll();for(const e of this.#k.values())e.updateMode(t);if(e){for(const t of this.#D.values())if(t.annotationElementId===e){this.setSelected(t);t.enterInEditMode()}else t.unselect();this.#ft.resolve()}else{i&&this.addNewEditorFromKeyboard();this.#ft.resolve()}}else{this.setEditingState(!1);this.#Lt();this._editorUndoBar?.hide();this.#ft.resolve()}}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#rt&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#z){switch(t){case m.CREATE:this.currentLayer.addNewEditor();return;case m.HIGHLIGHT_DEFAULT_COLOR:this.#st?.updateColor(e);break;case m.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}});(this.#ht||=new Map).set(t,e);this.showAllEditors("highlight",e)}for(const i of this.#at)i.updateParams(t,e);for(const i of this.#z)i.updateDefaultParams(t,e)}}showAllEditors(t,e,i=!1){for(const i of this.#D.values())i.editorType===t&&i.show(e);(this.#ht?.get(m.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#Rt([[m.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#tt!==t){this.#tt=t;for(const e of this.#k.values()){t?e.disableClick():e.enableClick();e.div.classList.toggle("waiting",t)}}}async#Ft(){if(!this.#Z){this.#Z=!0;const t=[];for(const e of this.#k.values())t.push(e.enable());await Promise.all(t);for(const t of this.#D.values())t.enable()}}#Lt(){this.unselectAll();if(this.#Z){this.#Z=!1;for(const t of this.#k.values())t.disable();for(const t of this.#D.values())t.disable()}}getEditors(t){const e=[];for(const i of this.#D.values())i.pageIndex===t&&e.push(i);return e}getEditor(t){return this.#D.get(t)}addEditor(t){this.#D.set(t.id,t)}removeEditor(t){if(t.div.contains(document.activeElement)){this.#q&&clearTimeout(this.#q);this.#q=setTimeout((()=>{this.focusMainContainer();this.#q=null}),0)}this.#D.delete(t.id);this.unselect(t);t.annotationElementId&&this.#H.has(t.annotationElementId)||this.#I?.remove(t.id)}addDeletedAnnotationElement(t){this.#H.add(t.annotationElementId);this.addChangedExistingAnnotation(t);t.deleted=!0}isDeletedAnnotationElement(t){return this.#H.has(t)}removeDeletedAnnotationElement(t){this.#H.delete(t.annotationElementId);this.removeChangedExistingAnnotation(t);t.deleted=!1}#Dt(t){const e=this.#k.get(t.pageIndex);if(e)e.addOrRebuild(t);else{this.addEditor(t);this.addToAnnotationStorage(t)}}setActiveEditor(t){if(this.#P!==t){this.#P=t;t&&this.#Rt(t.propertiesToUpdate)}}get#Ot(){let t=null;for(t of this.#at);return t}updateUI(t){this.#Ot===t&&this.#Rt(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#Rt(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#at.has(t)){this.#at.delete(t);t.unselect();this.#_t({hasSelectedEditor:this.hasSelection})}else{this.#at.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}}setSelected(t){this.#N?.commitOrRemove();for(const e of this.#at)e!==t&&e.unselect();this.#at.clear();this.#at.add(t);t.select();this.#Rt(t.propertiesToUpdate);this.#_t({hasSelectedEditor:!0})}isSelected(t){return this.#at.has(t)}get firstSelectedEditor(){return this.#at.values().next().value}unselect(t){t.unselect();this.#at.delete(t);this.#_t({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#at.size}get isEnterHandled(){return 1===this.#at.size&&this.firstSelectedEditor.isEnterHandled}undo(){this.#L.undo();this.#_t({hasSomethingToUndo:this.#L.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#It()});this._editorUndoBar?.hide()}redo(){this.#L.redo();this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:this.#L.hasSomethingToRedo(),isEmpty:this.#It()})}addCommands(t){this.#L.add(t);this.#_t({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#It()})}cleanUndoStack(t){this.#L.cleanType(t)}#It(){if(0===this.#D.size)return!0;if(1===this.#D.size)for(const t of this.#D.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#at],undo=()=>{for(const t of e)this.#Dt(t)};this.addCommands({cmd:()=>{this._editorUndoBar?.show(undo,1===e.length?e[0].editorType:e.length);for(const t of e)t.remove()},undo,mustExec:!0})}commitOrRemove(){this.#P?.commitOrRemove()}hasSomethingToControl(){return this.#P||this.hasSelection}#kt(t){for(const t of this.#at)t.unselect();this.#at.clear();for(const e of t)if(!e.isEmpty()){this.#at.add(e);e.select()}this.#_t({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#at)t.commit();this.#kt(this.#D.values())}unselectAll(){if(this.#P){this.#P.commitOrRemove();if(this.#rt!==f.NONE)return}if(!this.#N?.commitOrRemove()&&this.hasSelection){for(const t of this.#at)t.unselect();this.#at.clear();this.#_t({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,i=!1){i||this.commitOrRemove();if(!this.hasSelection)return;this.#dt[0]+=t;this.#dt[1]+=e;const[s,n]=this.#dt,r=[...this.#at];this.#ut&&clearTimeout(this.#ut);this.#ut=setTimeout((()=>{this.#ut=null;this.#dt[0]=this.#dt[1]=0;this.addCommands({cmd:()=>{for(const t of r)this.#D.has(t.id)&&t.translateInPage(s,n)},undo:()=>{for(const t of r)this.#D.has(t.id)&&t.translateInPage(-s,-n)},mustExec:!1})}),1e3);for(const i of r)i.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0);this.#U=new Map;for(const t of this.#at)this.#U.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#U)return!1;this.disableUserSelect(!1);const t=this.#U;this.#U=null;let e=!1;for(const[{x:i,y:s,pageIndex:n},r]of t){r.newX=i;r.newY=s;r.newPageIndex=n;e||=i!==r.savedX||s!==r.savedY||n!==r.savedPageIndex}if(!e)return!1;const move=(t,e,i,s)=>{if(this.#D.has(t.id)){const n=this.#k.get(s);if(n)t._setParentAndPosition(n,e,i);else{t.pageIndex=s;t.x=e;t.y=i}}};this.addCommands({cmd:()=>{for(const[e,{newX:i,newY:s,newPageIndex:n}]of t)move(e,i,s,n)},undo:()=>{for(const[e,{savedX:i,savedY:s,savedPageIndex:n}]of t)move(e,i,s,n)},mustExec:!0});return!0}dragSelectedEditors(t,e){if(this.#U)for(const i of this.#U.keys())i.drag(t,e)}rebuild(t){if(null===t.parent){const e=this.getLayer(t.pageIndex);if(e){e.changeParent(t);e.addOrRebuild(t)}else{this.addEditor(t);this.addToAnnotationStorage(t);t.rebuild()}}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||1===this.#at.size&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#P===t}getActive(){return this.#P}getMode(){return this.#rt}get imageManager(){return shadow(this,"imageManager",new ImageManager)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let i=0,s=e.rangeCount;i({x:(e-s)/r,y:1-(t+a-i)/n,width:o/r,height:a/n});break;case"180":a=(t,e,a,o)=>({x:1-(t+a-i)/n,y:1-(e+o-s)/r,width:a/n,height:o/r});break;case"270":a=(t,e,a,o)=>({x:1-(e+o-s)/r,y:(t-i)/n,width:o/r,height:a/n});break;default:a=(t,e,a,o)=>({x:(t-i)/n,y:(e-s)/r,width:a/n,height:o/r})}const o=[];for(let t=0,i=e.rangeCount;tt.stopPropagation()),{signal:i});const onClick=t=>{t.preventDefault();this.#r._uiManager.editAltText(this.#r);this.#Wt&&this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#Xt}})};t.addEventListener("click",onClick,{capture:!0,signal:i});t.addEventListener("keydown",(e=>{if(e.target===t&&"Enter"===e.key){this.#jt=!0;onClick(e)}}),{signal:i});await this.#Yt();return t}get#Xt(){return(this.#o?"added":null===this.#o&&this.guessedText&&"review")||"missing"}finish(){if(this.#Bt){this.#Bt.focus({focusVisible:this.#jt});this.#jt=!1}}isEmpty(){return this.#Wt?null===this.#o:!this.#o&&!this.#Nt}hasData(){return this.#Wt?null!==this.#o||!!this.#Vt:this.isEmpty()}get guessedText(){return this.#Vt}async setGuessedText(t){if(null===this.#o){this.#Vt=t;this.#$t=await AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t});this.#Yt()}}toggleAltTextBadge(t=!1){if(this.#Wt&&!this.#o){if(!this.#Gt){const t=this.#Gt=document.createElement("div");t.className="noAltTextBadge";this.#r.div.append(t)}this.#Gt.classList.toggle("hidden",!t)}else{this.#Gt?.remove();this.#Gt=null}}serialize(t){let e=this.#o;t||this.#Vt!==e||(e=this.#$t);return{altText:e,decorative:this.#Nt,guessedText:this.#Vt,textWithDisclaimer:this.#$t}}get data(){return{altText:this.#o,decorative:this.#Nt}}set data({altText:t,decorative:e,guessedText:i,textWithDisclaimer:s,cancel:n=!1}){if(i){this.#Vt=i;this.#$t=s}if(this.#o!==t||this.#Nt!==e){if(!n){this.#o=t;this.#Nt=e}this.#Yt()}}toggle(t=!1){if(this.#Bt){if(!t&&this.#zt){clearTimeout(this.#zt);this.#zt=null}this.#Bt.disabled=!t}}shown(){this.#r._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#Xt}})}destroy(){this.#Bt?.remove();this.#Bt=null;this.#Ht=null;this.#Ut=null;this.#Gt?.remove();this.#Gt=null}async#Yt(){const t=this.#Bt;if(!t)return;if(this.#Wt){t.classList.toggle("done",!!this.#o);t.setAttribute("data-l10n-id",AltText.#qt[this.#Xt]);this.#Ht?.setAttribute("data-l10n-id",AltText.#qt[`${this.#Xt}-label`]);if(!this.#o){this.#Ut?.remove();return}}else{if(!this.#o&&!this.#Nt){t.classList.remove("done");this.#Ut?.remove();return}t.classList.add("done");t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#Ut;if(!e){this.#Ut=e=document.createElement("span");e.className="tooltip";e.setAttribute("role","tooltip");e.id=`alt-text-tooltip-${this.#r.id}`;const i=100,s=this.#r._uiManager._signal;s.addEventListener("abort",(()=>{clearTimeout(this.#zt);this.#zt=null}),{once:!0});t.addEventListener("mouseenter",(()=>{this.#zt=setTimeout((()=>{this.#zt=null;this.#Ut.classList.add("show");this.#r._reportTelemetry({action:"alt_text_tooltip"})}),i)}),{signal:s});t.addEventListener("mouseleave",(()=>{if(this.#zt){clearTimeout(this.#zt);this.#zt=null}this.#Ut?.classList.remove("show")}),{signal:s})}if(this.#Nt)e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip");else{e.removeAttribute("data-l10n-id");e.textContent=this.#o}e.parentNode||t.append(e);const i=this.#r.getImageForAltText();i?.setAttribute("aria-describedby",e.id)}}class TouchManager{#pt;#Kt=!1;#Qt=null;#Jt;#Zt;#te;#ee;#ie;#se=null;#ne;#re=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:i=null,onPinchStart:s=null,onPinching:n=null,onPinchEnd:r=null,signal:a}){this.#pt=t;this.#Qt=i;this.#Jt=e;this.#Zt=s;this.#te=n;this.#ee=r;this.#ne=new AbortController;this.#ie=AbortSignal.any([a,this.#ne.signal]);t.addEventListener("touchstart",this.#ae.bind(this),{passive:!1,signal:this.#ie})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return shadow(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#ae(t){if(this.#Jt?.()||t.touches.length<2)return;if(!this.#re){this.#re=new AbortController;const t=AbortSignal.any([this.#ie,this.#re.signal]),e=this.#pt,i={signal:t,passive:!1};e.addEventListener("touchmove",this.#oe.bind(this),i);e.addEventListener("touchend",this.#le.bind(this),i);e.addEventListener("touchcancel",this.#le.bind(this),i);this.#Zt?.()}stopEvent(t);if(2!==t.touches.length||this.#Qt?.()){this.#se=null;return}let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);this.#se={touch0X:e.screenX,touch0Y:e.screenY,touch1X:i.screenX,touch1Y:i.screenY}}#oe(t){if(!this.#se||2!==t.touches.length)return;let[e,i]=t.touches;e.identifier>i.identifier&&([e,i]=[i,e]);const{screenX:s,screenY:n}=e,{screenX:r,screenY:a}=i,o=this.#se,{touch0X:l,touch0Y:h,touch1X:c,touch1Y:d}=o,u=c-l,p=d-h,g=r-s,f=a-n,m=Math.hypot(g,f)||1,b=Math.hypot(u,p)||1;if(!this.#Kt&&Math.abs(b-m)<=TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH)return;o.touch0X=s;o.touch0Y=n;o.touch1X=r;o.touch1Y=a;t.preventDefault();if(!this.#Kt){this.#Kt=!0;return}const v=[(s+r)/2,(n+a)/2];this.#te?.(v,b,m)}#le(t){this.#re.abort();this.#re=null;this.#ee?.();if(this.#se){t.preventDefault();this.#se=null;this.#Kt=!1}}destroy(){this.#ne?.abort();this.#ne=null}}class AnnotationEditor{#he=null;#ce=null;#o=null;#de=!1;#ue=null;#pe="";#ge=!1;#fe=null;#me=null;#be=null;#ve=null;#ye="";#we=!1;#Ae=null;#xe=!1;#_e=!1;#Ee=!1;#Se=null;#Ce=0;#Te=0;#Me=null;#Pe=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#De=!1;#ke=AnnotationEditor._zIndex++;static _borderLineWidth=-1;static _colorManager=new ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=AnnotationEditor.prototype._resizeWithKeyboard,e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_resizerKeyboardManager",new KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-i,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[i,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-i]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,i]}],[["Escape","mac+Escape"],AnnotationEditor.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;this.annotationElementId=null;this._willKeepAspectRatio=!1;this._initialOptions.isCentered=t.isCentered;this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:i,pageHeight:s,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e;this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360;this.pageDimensions=[i,s];this.pageTranslation=[n,r];const[a,o]=this.parentDimensions;this.x=t.x/a;this.y=t.y/o;this.isAttachedToDOM=!1;this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return shadow(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new FakeEditor({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId;e.deleted=!0;e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){AnnotationEditor._l10n??=t;AnnotationEditor._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"});if(-1!==AnnotationEditor._borderLineWidth)return;const i=getComputedStyle(document.documentElement);AnnotationEditor._borderLineWidth=parseFloat(i.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){unreachable("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#De}set _isDraggable(t){this.#De=t;this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(2*t);this.y+=this.width*t/(2*e);break;case 180:this.x+=this.width/2;this.y+=this.height/2;break;case 270:this.x+=this.height*e/(2*t);this.y-=this.width*t/(2*e);break;default:this.x-=this.width/2;this.y-=this.height/2}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#ke}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}else this.#Re();this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#we?this.#we=!1:this.parent.setSelected(this))}focusout(t){if(!this._focusEventsAllowed)return;if(!this.isAttachedToDOM)return;const e=t.relatedTarget;if(!e?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,i,s){const[n,r]=this.parentDimensions;[i,s]=this.screenToPageTranslation(i,s);this.x=(t+i)/n;this.y=(e+s)/r;this.fixAndSetPosition()}#Ie([t,e],i,s){[i,s]=this.screenToPageTranslation(i,s);this.x+=i/t;this.y+=s/e;this._onTranslating(this.x,this.y);this.fixAndSetPosition()}translate(t,e){this.#Ie(this.parentDimensions,t,e)}translateInPage(t,e){this.#Ae||=[this.x,this.y,this.width,this.height];this.#Ie(this.pageDimensions,t,e);this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#Ae||=[this.x,this.y,this.width,this.height];const{div:i,parentDimensions:[s,n]}=this;this.x+=t/s;this.y+=e/n;if(this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:t,y:e}=this.div.getBoundingClientRect();if(this.parent.findNewParent(this,t,e)){this.x-=Math.floor(this.x);this.y-=Math.floor(this.y)}}let{x:r,y:a}=this;const[o,l]=this.getBaseTranslation();r+=o;a+=l;const{style:h}=i;h.left=`${(100*r).toFixed(2)}%`;h.top=`${(100*a).toFixed(2)}%`;this._onTranslating(r,a);i.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#Ae&&(this.#Ae[0]!==this.x||this.#Ae[1]!==this.y)}get _hasBeenResized(){return!!this.#Ae&&(this.#Ae[2]!==this.width||this.#Ae[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:i}=AnnotationEditor,s=i/t,n=i/e;switch(this.rotation){case 90:return[-s,n];case 180:return[s,n];case 270:return[s,-n];default:return[-s,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[i,s]}=this;let{x:n,y:r,width:a,height:o}=this;a*=i;o*=s;n*=i;r*=s;if(this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(i-a,n));r=Math.max(0,Math.min(s-o,r));break;case 90:n=Math.max(0,Math.min(i-o,n));r=Math.min(s,Math.max(a,r));break;case 180:n=Math.min(i,Math.max(a,n));r=Math.min(s,Math.max(o,r));break;case 270:n=Math.min(i,Math.max(o,n));r=Math.max(0,Math.min(s-a,r))}this.x=n/=i;this.y=r/=s;const[l,h]=this.getBaseTranslation();n+=l;r+=h;e.left=`${(100*n).toFixed(2)}%`;e.top=`${(100*r).toFixed(2)}%`;this.moveInDOM()}static#Fe(t,e,i){switch(i){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return AnnotationEditor.#Fe(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return AnnotationEditor.#Fe(t,e,360-this.parentRotation)}#Le(t){switch(t){case 90:{const[t,e]=this.pageDimensions;return[0,-t/e,e/t,0]}case 180:return[-1,0,0,-1];case 270:{const[t,e]=this.pageDimensions;return[0,t/e,-e/t,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,i]}=this;return[e*t,i*t]}setDims(t,e){const[i,s]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/i).toFixed(2)}%`;this.#ge||(n.height=`${(100*e/s).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:i}=t,s=i.endsWith("%"),n=!this.#ge&&e.endsWith("%");if(s&&n)return;const[r,a]=this.parentDimensions;s||(t.width=`${(100*parseFloat(i)/r).toFixed(2)}%`);this.#ge||n||(t.height=`${(100*parseFloat(e)/a).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#Oe(){if(this.#fe)return;this.#fe=document.createElement("div");this.#fe.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const i of t){const t=document.createElement("div");this.#fe.append(t);t.classList.add("resizer",i);t.setAttribute("data-resizer-name",i);t.addEventListener("pointerdown",this.#Ne.bind(this,i),{signal:e});t.addEventListener("contextmenu",noContextMenu,{signal:e});t.tabIndex=-1}this.div.prepend(this.#fe)}#Ne(t,e){e.preventDefault();const{isMac:i}=util_FeatureTest.platform;if(0!==e.button||e.ctrlKey&&i)return;this.#o?.toggle(!1);const s=this._isDraggable;this._isDraggable=!1;this.#me=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1);window.addEventListener("pointermove",this.#Be.bind(this,t),{passive:!0,capture:!0,signal:r});window.addEventListener("touchmove",stopEvent,{passive:!1,signal:r});window.addEventListener("contextmenu",noContextMenu,{signal:r});this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const a=this.parent.div.style.cursor,o=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const pointerUpCallback=()=>{n.abort();this.parent.togglePointerEvents(!0);this.#o?.toggle(!0);this._isDraggable=s;this.parent.div.style.cursor=a;this.div.style.cursor=o;this.#He()};window.addEventListener("pointerup",pointerUpCallback,{signal:r});window.addEventListener("blur",pointerUpCallback,{signal:r})}#Ue(t,e,i,s){this.width=i;this.height=s;this.x=t;this.y=e;const[n,r]=this.parentDimensions;this.setDims(n*i,r*s);this.fixAndSetPosition();this._onResized()}_onResized(){}#He(){if(!this.#be)return;const{savedX:t,savedY:e,savedWidth:i,savedHeight:s}=this.#be;this.#be=null;const n=this.x,r=this.y,a=this.width,o=this.height;n===t&&r===e&&a===i&&o===s||this.addCommands({cmd:this.#Ue.bind(this,n,r,a,o),undo:this.#Ue.bind(this,t,e,i,s),mustExec:!0})}static _round(t){return Math.round(1e4*t)/1e4}#Be(t,e){const[i,s]=this.parentDimensions,n=this.x,r=this.y,a=this.width,o=this.height,l=AnnotationEditor.MIN_SIZE/i,h=AnnotationEditor.MIN_SIZE/s,c=this.#Le(this.rotation),transf=(t,e)=>[c[0]*t+c[2]*e,c[1]*t+c[3]*e],d=this.#Le(360-this.rotation);let u,p,g=!1,f=!1;switch(t){case"topLeft":g=!0;u=(t,e)=>[0,0];p=(t,e)=>[t,e];break;case"topMiddle":u=(t,e)=>[t/2,0];p=(t,e)=>[t/2,e];break;case"topRight":g=!0;u=(t,e)=>[t,0];p=(t,e)=>[0,e];break;case"middleRight":f=!0;u=(t,e)=>[t,e/2];p=(t,e)=>[0,e/2];break;case"bottomRight":g=!0;u=(t,e)=>[t,e];p=(t,e)=>[0,0];break;case"bottomMiddle":u=(t,e)=>[t/2,e];p=(t,e)=>[t/2,0];break;case"bottomLeft":g=!0;u=(t,e)=>[0,e];p=(t,e)=>[t,0];break;case"middleLeft":f=!0;u=(t,e)=>[0,e/2];p=(t,e)=>[t,e/2]}const m=u(a,o),b=p(a,o);let v=transf(...b);const y=AnnotationEditor._round(n+v[0]),w=AnnotationEditor._round(r+v[1]);let A,x,_=1,E=1;if(e.fromKeyboard)({deltaX:A,deltaY:x}=e);else{const{screenX:t,screenY:i}=e,[s,n]=this.#me;[A,x]=this.screenToPageTranslation(t-s,i-n);this.#me[0]=t;this.#me[1]=i}[A,x]=(S=A/i,C=x/s,[d[0]*S+d[2]*C,d[1]*S+d[3]*C]);var S,C;if(g){const t=Math.hypot(a,o);_=E=Math.max(Math.min(Math.hypot(b[0]-m[0]-A,b[1]-m[1]-x)/t,1/a,1/o),l/a,h/o)}else f?_=Math.max(l,Math.min(1,Math.abs(b[0]-m[0]-A)))/a:E=Math.max(h,Math.min(1,Math.abs(b[1]-m[1]-x)))/o;const T=AnnotationEditor._round(a*_),M=AnnotationEditor._round(o*E);v=transf(...p(T,M));const P=y-v[0],D=w-v[1];this.#Ae||=[this.x,this.y,this.width,this.height];this.width=T;this.height=M;this.x=P;this.y=D;this.setDims(i*T,s*M);this.fixAndSetPosition();this._onResizing()}_onResizing(){}altTextFinish(){this.#o?.finish()}async addEditToolbar(){if(this._editToolbar||this.#_e)return this._editToolbar;this._editToolbar=new EditorToolbar(this);this.div.append(this._editToolbar.render());this.#o&&await this._editToolbar.addAltText(this.#o);return this._editToolbar}removeEditToolbar(){if(this._editToolbar){this._editToolbar.remove();this._editToolbar=null;this.#o?.destroy()}}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){if(!this.#o){AltText.initialize(AnnotationEditor._l10n);this.#o=new AltText(this);if(this.#he){this.#o.data=this.#he;this.#he=null}await this.addEditToolbar()}}get altTextData(){return this.#o?.data}set altTextData(t){this.#o&&(this.#o.data=t)}get guessedAltText(){return this.#o?.guessedText}async setGuessedAltText(t){await(this.#o?.setGuessedText(t))}serializeAltText(t){return this.#o?.serialize(t)}hasAltText(){return!!this.#o&&!this.#o.isEmpty()}hasAltTextData(){return this.#o?.hasData()??!1}render(){this.div=document.createElement("div");this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360);this.div.className=this.name;this.div.setAttribute("id",this.id);this.div.tabIndex=this.#de?-1:0;this._isVisible||this.div.classList.add("hidden");this.setInForeground();this.#ze();const[t,e]=this.parentDimensions;if(this.parentRotation%180!=0){this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`;this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`}const[i,s]=this.getInitialTranslation();this.translate(i,s);bindEvents(this,this.div,["pointerdown"]);this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#Pe||=new TouchManager({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#je.bind(this),onPinching:this.#Ge.bind(this),onPinchEnd:this.#Ve.bind(this),signal:this._uiManager._signal}));this._uiManager._editorUndoBar?.hide();return this.div}#je(){this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};this.#o?.toggle(!1);this.parent.togglePointerEvents(!1)}#Ge(t,e,i){let s=i/e*.7+1-.7;if(1===s)return;const n=this.#Le(this.rotation),transf=(t,e)=>[n[0]*t+n[2]*e,n[1]*t+n[3]*e],[r,a]=this.parentDimensions,o=this.x,l=this.y,h=this.width,c=this.height,d=AnnotationEditor.MIN_SIZE/r,u=AnnotationEditor.MIN_SIZE/a;s=Math.max(Math.min(s,1/h,1/c),d/h,u/c);const p=AnnotationEditor._round(h*s),g=AnnotationEditor._round(c*s);if(p===h&&g===c)return;this.#Ae||=[o,l,h,c];const f=transf(h/2,c/2),m=AnnotationEditor._round(o+f[0]),b=AnnotationEditor._round(l+f[1]),v=transf(p/2,g/2);this.x=m-v[0];this.y=b-v[1];this.width=p;this.height=g;this.setDims(r*p,a*g);this.fixAndSetPosition();this._onResizing()}#Ve(){this.#o?.toggle(!0);this.parent.togglePointerEvents(!0);this.#He()}pointerdown(t){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{this.#we=!0;this._isDraggable?this.#$e(t):this.#We(t)}}get isSelected(){return this._uiManager.isSelected(this)}#We(t){const{isMac:e}=util_FeatureTest.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#$e(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let i=!1;const s=new AbortController,n=this._uiManager.combinedSignal(s),r={capture:!0,passive:!1,signal:n},cancelDrag=t=>{s.abort();this.#ue=null;this.#we=!1;this._uiManager.endDragSession()||this.#We(t);i&&this._onStopDragging()};if(e){this.#Ce=t.clientX;this.#Te=t.clientY;this.#ue=t.pointerId;this.#pe=t.pointerType;window.addEventListener("pointermove",(t=>{if(!i){i=!0;this._onStartDragging()}const{clientX:e,clientY:s,pointerId:n}=t;if(n!==this.#ue){stopEvent(t);return}const[r,a]=this.screenToPageTranslation(e-this.#Ce,s-this.#Te);this.#Ce=e;this.#Te=s;this._uiManager.dragSelectedEditors(r,a)}),r);window.addEventListener("touchmove",stopEvent,r);window.addEventListener("pointerdown",(t=>{t.pointerType===this.#pe&&(this.#Pe||t.isPrimary)&&cancelDrag(t);stopEvent(t)}),r)}const pointerUpCallback=t=>{this.#ue&&this.#ue!==t.pointerId?stopEvent(t):cancelDrag(t)};window.addEventListener("pointerup",pointerUpCallback,{signal:n});window.addEventListener("blur",pointerUpCallback,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#Se&&clearTimeout(this.#Se);this.#Se=setTimeout((()=>{this.#Se=null;this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(t,e,i){t.changeParent(this);this.x=e;this.y=i;this.fixAndSetPosition();this._onTranslated()}getRect(t,e,i=this.rotation){const s=this.parentScale,[n,r]=this.pageDimensions,[a,o]=this.pageTranslation,l=t/s,h=e/s,c=this.x*n,d=this.y*r,u=this.width*n,p=this.height*r;switch(i){case 0:return[c+l+a,r-d-h-p+o,c+l+u+a,r-d-h+o];case 90:return[c+h+a,r-d+l+o,c+h+p+a,r-d+l+u+o];case 180:return[c-l-u+a,r-d+h+o,c-l+a,r-d+h+p+o];case 270:return[c-h-p+a,r-d-l-u+o,c-h+a,r-d-l+o];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[i,s,n,r]=t,a=n-i,o=r-s;switch(this.rotation){case 0:return[i,e-r,a,o];case 90:return[i,e-s,o,a];case 180:return[n,e-s,a,o];case 270:return[n,e-r,o,a];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#_e=!0}disableEditMode(){this.#_e=!1}isInEditMode(){return this.#_e}shouldGetKeyboardEvents(){return this.#Ee}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:i,right:s}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e0&&t0}#ze(){if(this.#ve||!this.div)return;this.#ve=new AbortController;const t=this._uiManager.combinedSignal(this.#ve);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t});this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#ze()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){unreachable("An editor must be serializable")}static async deserialize(t,e,i){const s=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:i});s.rotation=t.rotation;s.#he=t.accessibilityData;const[n,r]=s.pageDimensions,[a,o,l,h]=s.getRectInCurrentCoords(t.rect,r);s.x=a/n;s.y=o/r;s.width=l/n;s.height=h/r;return s}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||null!==this.serialize())}remove(){this.#ve?.abort();this.#ve=null;this.isEmpty()||this.commit();this.parent?this.parent.remove(this):this._uiManager.removeEditor(this);if(this.#Se){clearTimeout(this.#Se);this.#Se=null}this.#Re();this.removeEditToolbar();if(this.#Me){for(const t of this.#Me.values())clearTimeout(t);this.#Me=null}this.parent=null;this.#Pe?.destroy();this.#Pe=null}get isResizable(){return!1}makeResizable(){if(this.isResizable){this.#Oe();this.#fe.classList.remove("hidden");bindEvents(this,this.div,["keydown"])}}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||"Enter"!==t.key)return;this._uiManager.setSelected(this);this.#be={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#fe.children;if(!this.#ce){this.#ce=Array.from(e);const t=this.#qe.bind(this),i=this.#Xe.bind(this),s=this._uiManager._signal;for(const e of this.#ce){const n=e.getAttribute("data-resizer-name");e.setAttribute("role","spinbutton");e.addEventListener("keydown",t,{signal:s});e.addEventListener("blur",i,{signal:s});e.addEventListener("focus",this.#Ye.bind(this,n),{signal:s});e.setAttribute("data-l10n-id",AnnotationEditor._l10nResizer[n])}}const i=this.#ce[0];let s=0;for(const t of e){if(t===i)break;s++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#ce.length/4);if(n!==s){if(ns)for(let t=0;t{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()}))}unselect(){this.#fe?.classList.add("hidden");this.div?.classList.remove("selectedEditor");this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0});this._editToolbar?.hide();this.#o?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#xe}set isEditing(t){this.#xe=t;if(this.parent)if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}setAspectRatio(t,e){this.#ge=!0;const i=t/e,{style:s}=this.div;s.aspectRatio=i;s.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#Me||=new Map;const{action:e}=t;let i=this.#Me.get(e);i&&clearTimeout(i);i=setTimeout((()=>{this._reportTelemetry(t);this.#Me.delete(e);0===this.#Me.size&&(this.#Me=null)}),AnnotationEditor._telemetryTimeout);this.#Me.set(e,i)}else{t.type||=this.editorType;this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}}show(t=this._isVisible){this.div.classList.toggle("hidden",!t);this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0);this.#de=!1}disable(){this.div&&(this.div.tabIndex=-1);this.#de=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(e){if("CANVAS"===e.nodeName){const t=e;e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.before(e)}}else{e=document.createElement("div");e.classList.add("annotationContent",this.editorType);t.container.prepend(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;"DIV"===e?.nodeName&&e.classList.contains("annotationContent")&&e.remove()}}class FakeEditor extends AnnotationEditor{constructor(t){super(t);this.annotationElementId=t.annotationElementId;this.deleted=!0}serialize(){return this.serializeDeleted()}}const rt=3285377520,at=4294901760,ot=65535;class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:rt;this.h2=t?4294967295&t:rt}update(t){let e,i;if("string"==typeof t){e=new Uint8Array(2*t.length);i=0;for(let s=0,n=t.length;s>>8;e[i++]=255&n}}}else{if(!ArrayBuffer.isView(t))throw new Error("Invalid data format, must be a string or TypedArray.");e=t.slice();i=e.byteLength}const s=i>>2,n=i-4*s,r=new Uint32Array(e.buffer,0,s);let a=0,o=0,l=this.h1,h=this.h2;const c=3432918353,d=461845907,u=11601,p=13715;for(let t=0;t>>17;a=a*d&at|a*p&ot;l^=a;l=l<<13|l>>>19;l=5*l+3864292196}else{o=r[t];o=o*c&at|o*u&ot;o=o<<15|o>>>17;o=o*d&at|o*p&ot;h^=o;h=h<<13|h>>>19;h=5*h+3864292196}a=0;switch(n){case 3:a^=e[4*s+2]<<16;case 2:a^=e[4*s+1]<<8;case 1:a^=e[4*s];a=a*c&at|a*u&ot;a=a<<15|a>>>17;a=a*d&at|a*p&ot;1&s?l^=a:h^=a}this.h1=l;this.h2=h}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&at|36045*t&ot;e=4283543511*e&at|(2950163797*(e<<16|t>>>16)&at)>>>16;t^=e>>>1;t=444984403*t&at|60499*t&ot;e=3301882366*e&at|(3120437893*(e<<16|t>>>16)&at)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const lt=Object.freeze({map:null,hash:"",transfer:void 0});class AnnotationStorage{#Qe=!1;#Je=null;#Ze=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const i=this.#Ze.get(t);return void 0===i?e:Object.assign(e,i)}getRawValue(t){return this.#Ze.get(t)}remove(t){this.#Ze.delete(t);0===this.#Ze.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#Ze.values())if(t instanceof AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(t,e){const i=this.#Ze.get(t);let s=!1;if(void 0!==i){for(const[t,n]of Object.entries(e))if(i[t]!==n){s=!0;i[t]=n}}else{s=!0;this.#Ze.set(t,e)}s&&this.#ti();e instanceof AnnotationEditor&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#Ze.has(t)}getAll(){return this.#Ze.size>0?objectFromMap(this.#Ze):null}setAll(t){for(const[e,i]of Object.entries(t))this.setValue(e,i)}get size(){return this.#Ze.size}#ti(){if(!this.#Qe){this.#Qe=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#Qe){this.#Qe=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#Ze.size)return lt;const t=new Map,e=new MurmurHash3_64,i=[],s=Object.create(null);let n=!1;for(const[i,r]of this.#Ze){const a=r instanceof AnnotationEditor?r.serialize(!1,s):r;if(a){t.set(i,a);e.update(`${i}:${JSON.stringify(a)}`);n||=!!a.bitmap}}if(n)for(const e of t.values())e.bitmap&&i.push(e.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:i}:lt}get editorStats(){let t=null;const e=new Map;for(const i of this.#Ze.values()){if(!(i instanceof AnnotationEditor))continue;const s=i.telemetryFinalData;if(!s)continue;const{type:n}=s;e.has(n)||e.set(n,Object.getPrototypeOf(i).constructor);t||=Object.create(null);const r=t[n]||=new Map;for(const[t,e]of Object.entries(s)){if("type"===t)continue;let i=r.get(t);if(!i){i=new Map;r.set(t,i)}const s=i.get(e)??0;i.set(e,s+1)}}for(const[i,s]of e)t[i]=s.computeTelemetryFinalData(t[i]);return t}resetModifiedIds(){this.#Je=null}get modifiedIds(){if(this.#Je)return this.#Je;const t=[];for(const e of this.#Ze.values())e instanceof AnnotationEditor&&e.annotationElementId&&e.serialize()&&t.push(e.annotationElementId);return this.#Je={ids:new Set(t),hash:t.join(",")}}}class PrintAnnotationStorage extends AnnotationStorage{#ei;constructor(t){super();const{map:e,hash:i,transfer:s}=t.serializable,n=structuredClone(e,s?{transfer:s}:null);this.#ei={map:n,hash:i,transfer:s}}get print(){unreachable("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#ei}get modifiedIds(){return shadow(this,"modifiedIds",{ids:new Set,hash:""})}}class FontLoader{#ii=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t;this.nativeFontFaces=new Set;this.styleElement=null;this.loadingRequests=[];this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t);this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t);this._document.fonts.delete(t)}insertRule(t){if(!this.styleElement){this.styleElement=this._document.createElement("style");this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)}const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear();this.#ii.clear();if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(t&&!this.#ii.has(t.loadedName)){assert(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set.");if(this.isFontLoadingAPISupported){const{loadedName:i,src:s,style:n}=t,r=new FontFace(i,s,n);this.addNativeFontFace(r);try{await r.load();this.#ii.add(i);e?.(t)}catch{warn(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`);this.removeNativeFontFace(r)}}else unreachable("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;t.attached=!0;if(t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(i){warn(`Failed to load font '${e.family}': '${i}'.`);t.disableFontFace=!0;throw i}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise((e=>{const i=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,i)}))}}get isFontLoadingAPISupported(){return shadow(this,"isFontLoadingAPISupported",!!this._document?.fonts)}get isSyncFontLoadingSupported(){let t=!1;(i||"undefined"!=typeof navigator&&"string"==typeof navigator?.userAgent&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0);return shadow(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,i={done:!1,complete:function completeRequest(){assert(!i.done,"completeRequest() cannot be called twice.");i.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};e.push(i);return i}get _loadTestFont(){return shadow(this,"_loadTestFont",atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="))}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function spliceString(t,e,i,s){return t.substring(0,e)+s+t.substring(e+i)}let i,s;const n=this._document.createElement("canvas");n.width=1;n.height=1;const r=n.getContext("2d");let a=0;const o=`lt${Date.now()}${this.loadTestFontId++}`;let l=this._loadTestFont;l=spliceString(l,976,o.length,o);const h=1482184792;let c=int32(l,16);for(i=0,s=o.length-3;i>24&255,t>>16&255,t>>8&255,255&t)}(c));const d=`@font-face {font-family:"${o}";src:${`url(data:font/opentype;base64,${btoa(l)});`}}`;this.insertRule(d);const u=this._document.createElement("div");u.style.visibility="hidden";u.style.width=u.style.height="10px";u.style.position="absolute";u.style.top=u.style.left="0px";for(const e of[t.loadedName,o]){const t=this._document.createElement("span");t.textContent="Hi";t.style.fontFamily=e;u.append(t)}this._document.body.append(u);!function isFontReady(t,e){if(++a>30){warn("Load test font never loaded.");e();return}r.font="30px "+t;r.fillText(".",0,20);r.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(o,(()=>{u.remove();e.complete()}))}}class FontFaceObject{constructor(t,{disableFontFace:e=!1,fontExtraProperties:i=!1,inspectFont:s=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.disableFontFace=!0===e;this.fontExtraProperties=!0===i;this._inspectFont=s}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`);t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});this._inspectFont?.(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${function toBase64Util(t){return Uint8Array.prototype.toBase64?t.toBase64():btoa(bytesToString(t))}(this.data)});`;let e;if(this.cssFontInfo){let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`);e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}else e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;this._inspectFont?.(this,t);return e}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];const i=this.loadedName+"_path_"+e;let s;try{s=t.get(i)}catch(t){warn(`getPathGenerator - ignoring character: "${t}".`)}const n=new Path2D(s||"");this.fontExtraProperties||t.delete(i);return this.compiledGlyphs[e]=n}}const ht=1,ct=2,dt=1,ut=2,pt=3,gt=4,ft=5,mt=6,bt=7,vt=8;function onFn(){}function wrapReason(t){if(t instanceof AbortException||t instanceof InvalidPDFException||t instanceof MissingPDFException||t instanceof PasswordException||t instanceof UnexpectedResponseException||t instanceof UnknownErrorException)return t;t instanceof Error||"object"==typeof t&&null!==t||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new AbortException(t.message);case"InvalidPDFException":return new InvalidPDFException(t.message);case"MissingPDFException":return new MissingPDFException(t.message);case"PasswordException":return new PasswordException(t.message,t.code);case"UnexpectedResponseException":return new UnexpectedResponseException(t.message,t.status);case"UnknownErrorException":return new UnknownErrorException(t.message,t.details)}return new UnknownErrorException(t.message,t.toString())}class MessageHandler{#si=new AbortController;constructor(t,e,i){this.sourceName=t;this.targetName=e;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#ni.bind(this),{signal:this.#si.signal})}#ni({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#ri(t);return}if(t.callback){const e=t.callbackId,i=this.callbackCapabilities[e];if(!i)throw new Error(`Cannot resolve callback ${e}`);delete this.callbackCapabilities[e];if(t.callback===ht)i.resolve(t.data);else{if(t.callback!==ct)throw new Error("Unexpected callback case");i.reject(wrapReason(t.reason))}return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const i=this.sourceName,s=t.sourceName,n=this.comObj;Promise.try(e,t.data).then((function(e){n.postMessage({sourceName:i,targetName:s,callback:ht,callbackId:t.callbackId,data:e})}),(function(e){n.postMessage({sourceName:i,targetName:s,callback:ct,callbackId:t.callbackId,reason:wrapReason(e)})}))}else t.streamId?this.#ai(t):e(t.data)}on(t,e){const i=this.actionHandler;if(i[t])throw new Error(`There is already an actionName called "${t}"`);i[t]=e}send(t,e,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},i)}sendWithPromise(t,e,i){const s=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[s]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:s,data:e},i)}catch(t){n.reject(t)}return n.promise}sendWithStream(t,e,i,s){const n=this.streamId++,r=this.sourceName,a=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const l=Promise.withResolvers();this.streamControllers[n]={controller:i,startCall:l,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:r,targetName:a,action:t,streamId:n,data:e,desiredSize:i.desiredSize},s);return l.promise},pull:t=>{const e=Promise.withResolvers();this.streamControllers[n].pullCall=e;o.postMessage({sourceName:r,targetName:a,stream:mt,streamId:n,desiredSize:t.desiredSize});return e.promise},cancel:t=>{assert(t instanceof Error,"cancel must have a valid reason");const e=Promise.withResolvers();this.streamControllers[n].cancelCall=e;this.streamControllers[n].isClosed=!0;o.postMessage({sourceName:r,targetName:a,stream:dt,streamId:n,reason:wrapReason(t)});return e.promise}},i)}#ai(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,r=this,a=this.actionHandler[t.action],o={enqueue(t,r=1,a){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=r;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}n.postMessage({sourceName:i,targetName:s,stream:gt,streamId:e,chunk:t},a)},close(){if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:pt,streamId:e});delete r.streamSinks[e]}},error(t){assert(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;n.postMessage({sourceName:i,targetName:s,stream:ft,streamId:e,reason:wrapReason(t)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[e]=o;Promise.try(a,t.data,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:vt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:vt,streamId:e,reason:wrapReason(t)})}))}#ri(t){const e=t.streamId,i=this.sourceName,s=t.sourceName,n=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case vt:t.success?r.startCall.resolve():r.startCall.reject(wrapReason(t.reason));break;case bt:t.success?r.pullCall.resolve():r.pullCall.reject(wrapReason(t.reason));break;case mt:if(!a){n.postMessage({sourceName:i,targetName:s,stream:bt,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve();a.desiredSize=t.desiredSize;Promise.try(a.onPull||onFn).then((function(){n.postMessage({sourceName:i,targetName:s,stream:bt,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:bt,streamId:e,reason:wrapReason(t)})}));break;case gt:assert(r,"enqueue should have stream controller");if(r.isClosed)break;r.controller.enqueue(t.chunk);break;case pt:assert(r,"close should have stream controller");if(r.isClosed)break;r.isClosed=!0;r.controller.close();this.#oi(r,e);break;case ft:assert(r,"error should have stream controller");r.controller.error(wrapReason(t.reason));this.#oi(r,e);break;case ut:t.success?r.cancelCall.resolve():r.cancelCall.reject(wrapReason(t.reason));this.#oi(r,e);break;case dt:if(!a)break;const o=wrapReason(t.reason);Promise.try(a.onCancel||onFn,o).then((function(){n.postMessage({sourceName:i,targetName:s,stream:ut,streamId:e,success:!0})}),(function(t){n.postMessage({sourceName:i,targetName:s,stream:ut,streamId:e,reason:wrapReason(t)})}));a.sinkCapability.reject(o);a.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#oi(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]);delete this.streamControllers[e]}destroy(){this.#si?.abort();this.#si=null}}class BaseCanvasFactory{#li=!1;constructor({enableHWA:t=!1}){this.#li=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const i=this._createCanvas(t,e);return{canvas:i,context:i.getContext("2d",{willReadFrequently:!this.#li})}}reset(t,e,i){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||i<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=i}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){unreachable("Abstract method `_createCanvas` called.")}}class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then((t=>({cMapData:t,isCompressed:this.isCompressed}))).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){const e=await fetchData(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):stringToBytes(e)}}__webpack_require__(4520);class BaseFilterFactory{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,i,s,n){return"none"}destroy(t=!1){}}class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}async _fetch(t){unreachable("Abstract method `_fetch` called.")}}class DOMStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){const e=await fetchData(t,"arraybuffer");return new Uint8Array(e)}}if(i){let t;try{const e=process.getBuiltinModule("module").createRequire(import.meta.url);try{t=e("@napi-rs/canvas")}catch(t){warn(`Cannot load "@napi-rs/canvas" package: "${t}".`)}}catch(t){warn(`Cannot access the \`require\` function: "${t}".`)}globalThis.DOMMatrix||(t?.DOMMatrix?globalThis.DOMMatrix=t.DOMMatrix:warn("Cannot polyfill `DOMMatrix`, rendering may be broken."));globalThis.ImageData||(t?.ImageData?globalThis.ImageData=t.ImageData:warn("Cannot polyfill `ImageData`, rendering may be broken."));globalThis.Path2D||(t?.Path2D?globalThis.Path2D=t.Path2D:warn("Cannot polyfill `Path2D`, rendering may be broken."))}async function node_utils_fetchData(t){const e=process.getBuiltinModule("fs"),i=await e.promises.readFile(t);return new Uint8Array(i)}const yt="Fill",wt="Stroke",At="Shading";function applyBoundingBox(t,e){if(!e)return;const i=e[2]-e[0],s=e[3]-e[1],n=new Path2D;n.rect(e[0],e[1],i,s);t.clip(n)}class BaseShadingPattern{getPattern(){unreachable("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,i,s){let n;if(s===wt||s===yt){const r=e.current.getClippedPathBoundingBox(s,getCurrentTransform(t))||[0,0,0,0],a=Math.ceil(r[2]-r[0])||1,o=Math.ceil(r[3]-r[1])||1,l=e.cachedCanvases.getCanvas("pattern",a,o),h=l.context;h.clearRect(0,0,h.canvas.width,h.canvas.height);h.beginPath();h.rect(0,0,h.canvas.width,h.canvas.height);h.translate(-r[0],-r[1]);i=Util.transform(i,[1,0,0,1,r[0],r[1]]);h.transform(...e.baseTransform);this.matrix&&h.transform(...this.matrix);applyBoundingBox(h,this._bbox);h.fillStyle=this._createGradient(h);h.fill();n=t.createPattern(l.canvas,"no-repeat");const c=new DOMMatrix(i);n.setTransform(c)}else{applyBoundingBox(t,this._bbox);n=this._createGradient(t)}return n}}function drawTriangle(t,e,i,s,n,r,a,o){const l=e.coords,h=e.colors,c=t.data,d=4*t.width;let u;if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=r;r=a;a=u}if(l[s+1]>l[n+1]){u=s;s=n;n=u;u=a;a=o;o=u}if(l[i+1]>l[s+1]){u=i;i=s;s=u;u=r;r=a;a=u}const p=(l[i]+e.offsetX)*e.scaleX,g=(l[i+1]+e.offsetY)*e.scaleY,f=(l[s]+e.offsetX)*e.scaleX,m=(l[s+1]+e.offsetY)*e.scaleY,b=(l[n]+e.offsetX)*e.scaleX,v=(l[n+1]+e.offsetY)*e.scaleY;if(g>=v)return;const y=h[r],w=h[r+1],A=h[r+2],x=h[a],_=h[a+1],E=h[a+2],S=h[o],C=h[o+1],T=h[o+2],M=Math.round(g),P=Math.round(v);let D,k,R,I,L,O,N,B;for(let t=M;t<=P;t++){if(tv?1:m===v?0:(m-t)/(m-v);D=f-(f-b)*e;k=x-(x-S)*e;R=_-(_-C)*e;I=E-(E-T)*e}let e;e=tv?1:(g-t)/(g-v);L=p-(p-b)*e;O=y-(y-S)*e;N=w-(w-C)*e;B=A-(A-T)*e;const i=Math.round(Math.min(D,L)),s=Math.round(Math.max(D,L));let n=d*t+4*i;for(let t=i;t<=s;t++){e=(D-t)/(D-L);e<0?e=0:e>1&&(e=1);c[n++]=k-(k-O)*e|0;c[n++]=R-(R-N)*e|0;c[n++]=I-(I-B)*e|0;c[n++]=255}}}function drawFigure(t,e,i){const s=e.coords,n=e.colors;let r,a;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(s.length/o)-1,h=o-1;for(r=0;r=Math.ceil(p*b)?y=o:A=!0;E>=Math.ceil(g*v)?w=l:x=!0;const S=this.getSizeAndScale(y,this.ctx.canvas.width,b),C=this.getSizeAndScale(w,this.ctx.canvas.height,v),T=t.cachedCanvases.getCanvas("pattern",S.size,C.size),M=T.context,P=a.createCanvasGraphics(M);P.groupLevel=t.groupLevel;this.setFillAndStrokeStyleToContext(P,s,r);M.translate(-S.scale*h,-C.scale*c);P.transform(S.scale,0,0,C.scale,0,0);M.save();this.clipBbox(P,h,c,d,u);P.baseTransform=getCurrentTransform(P.ctx);P.executeOperatorList(i);P.endDrawing();M.restore();if(A||x){const e=T.canvas;A&&(y=o);x&&(w=l);const i=this.getSizeAndScale(y,this.ctx.canvas.width,b),s=this.getSizeAndScale(w,this.ctx.canvas.height,v),n=i.size,r=s.size,a=t.cachedCanvases.getCanvas("pattern-workaround",n,r),d=a.context,u=A?Math.floor(p/o):0,f=x?Math.floor(g/l):0;for(let t=0;t<=u;t++)for(let i=0;i<=f;i++)d.drawImage(e,n*t,r*i,n,r,0,0,n,r);return{canvas:a.canvas,scaleX:i.scale,scaleY:s.scale,offsetX:h,offsetY:c}}return{canvas:T.canvas,scaleX:S.scale,scaleY:C.scale,offsetX:h,offsetY:c}}getSizeAndScale(t,e,i){const s=Math.max(TilingPattern.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*i);n>=s?n=s:i=n/t;return{scale:i,size:n}}clipBbox(t,e,i,s,n){const r=s-e,a=n-i;t.ctx.rect(e,i,r,a);t.current.updateRectMinMax(getCurrentTransform(t.ctx),[e,i,s,n]);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,i){const s=t.ctx,n=t.current;switch(e){case xt:const t=this.ctx;s.fillStyle=t.fillStyle;s.strokeStyle=t.strokeStyle;n.fillColor=t.fillStyle;n.strokeColor=t.strokeStyle;break;case _t:const r=Util.makeHexColor(i[0],i[1],i[2]);s.fillStyle=r;s.strokeStyle=r;n.fillColor=r;n.strokeColor=r;break;default:throw new FormatError(`Unsupported paint type: ${e}`)}}getPattern(t,e,i,s){let n=i;if(s!==At){n=Util.transform(n,e.baseTransform);this.matrix&&(n=Util.transform(n,this.matrix))}const r=this.createPatternCanvas(e);let a=new DOMMatrix(n);a=a.translate(r.offsetX,r.offsetY);a=a.scale(1/r.scaleX,1/r.scaleY);const o=t.createPattern(r.canvas,"repeat");o.setTransform(a);return o}}function convertBlackAndWhiteToRGBA({src:t,srcPos:e=0,dest:i,width:s,height:n,nonBlackColor:r=4294967295,inverseDecode:a=!1}){const o=util_FeatureTest.isLittleEndian?4278190080:255,[l,h]=a?[r,o]:[o,r],c=s>>3,d=7&s,u=t.length;i=new Uint32Array(i.buffer);let p=0;for(let s=0;s>2),f=i.length,m=s+7>>3,b=4294967295,v=util_FeatureTest.isLittleEndian?4278190080:255;for(u=0;um?s:8*t-7,a=-8&r;let o=0,d=0;for(;n>=1}}for(;l=r){g=n;f=s*g}l=0;for(p=f;p--;){d[l++]=c[h++];d[l++]=c[h++];d[l++]=c[h++];d[l++]=255}t.putImageData(o,0,u*Et)}}}function putBinaryImageMask(t,e){if(e.bitmap){t.drawImage(e.bitmap,0,0);return}const i=e.height,s=e.width,n=i%Et,r=(i-n)/Et,a=0===n?r:r+1,o=t.createImageData(s,Et);let l=0;const h=e.data,c=o.data;for(let e=0;e10&&"function"==typeof i,h=l?Date.now()+15:0;let c=0;const d=this.commonObjs,u=this.objs;let p;for(;;){if(void 0!==s&&a===s.nextBreakPoint){s.breakIt(a,i);return a}p=r[a];if(p!==K.dependency)this[p].apply(this,n[a]);else for(const t of n[a]){const e=t.startsWith("g_")?d:u;if(!e.has(t)){e.get(t,i);return a}}a++;if(a===o)return a;if(l&&++c>10){if(Date.now()>h){i();return a}c=0}}}#hi(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null;this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#hi();this.cachedCanvases.clear();this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear();this.#ci()}#ci(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if("none"!==t){const e=this.ctx.filter;this.ctx.filter=t;this.ctx.drawImage(this.ctx.canvas,0,0);this.ctx.filter=e}}}_scaleImage(t,e){const i=t.width??t.displayWidth,s=t.height??t.displayHeight;let n,r,a=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=i,h=s,c="prescale1";for(;a>2&&l>1||o>2&&h>1;){let e=l,i=h;if(a>2&&l>1){e=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l/2);a/=l/e}if(o>2&&h>1){i=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2;o/=h/i}n=this.cachedCanvases.getCanvas(c,e,i);r=n.context;r.clearRect(0,0,e,i);r.drawImage(t,0,0,l,h,0,0,e,i);t=n.canvas;l=e;h=i;c="prescale1"===c?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:i,height:s}=t,n=this.current.fillColor,r=this.current.patternFill,a=getCurrentTransform(e);let o,l,h,c;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;l=JSON.stringify(r?a:[a.slice(0,4),n]);o=this._cachedBitmapsMap.get(e);if(!o){o=new Map;this._cachedBitmapsMap.set(e,o)}const i=o.get(l);if(i&&!r){return{canvas:i,offsetX:Math.round(Math.min(a[0],a[2])+a[4]),offsetY:Math.round(Math.min(a[1],a[3])+a[5])}}h=i}if(!h){c=this.cachedCanvases.getCanvas("maskCanvas",i,s);putBinaryImageMask(c.context,t)}let d=Util.transform(a,[1/i,0,0,-1/s,0,0]);d=Util.transform(d,[1,0,0,1,0,-s]);const[u,p,g,f]=Util.getAxialAlignedBoundingBox([0,0,i,s],d),m=Math.round(g-u)||1,b=Math.round(f-p)||1,v=this.cachedCanvases.getCanvas("fillCanvas",m,b),y=v.context,w=u,A=p;y.translate(-w,-A);y.transform(...d);if(!h){h=this._scaleImage(c.canvas,getCurrentTransformInverse(y));h=h.img;o&&r&&o.set(l,h)}y.imageSmoothingEnabled=getImageSmoothingEnabled(getCurrentTransform(y),t.interpolate);drawImageAtIntegerCoords(y,h,0,0,h.width,h.height,0,0,i,s);y.globalCompositeOperation="source-in";const x=Util.transform(getCurrentTransformInverse(y),[1,0,0,1,-w,-A]);y.fillStyle=r?n.getPattern(e,this,x,yt):n;y.fillRect(0,0,i,s);if(o&&!r){this.cachedCanvases.delete("fillCanvas");o.set(l,v.canvas)}return{canvas:v.canvas,offsetX:Math.round(w),offsetY:Math.round(A)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1);this.current.lineWidth=t;this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=St[t]}setLineJoin(t){this.ctx.lineJoin=Ct[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const i=this.ctx;if(void 0!==i.setLineDash){i.setLineDash(t);i.lineDashOffset=e}}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,i]of t)switch(e){case"LW":this.setLineWidth(i);break;case"LC":this.setLineCap(i);break;case"LJ":this.setLineJoin(i);break;case"ML":this.setMiterLimit(i);break;case"D":this.setDash(i[0],i[1]);break;case"RI":this.setRenderingIntent(i);break;case"FL":this.setFlatness(i);break;case"Font":this.setFont(i[0],i[1]);break;case"CA":this.current.strokeAlpha=i;break;case"ca":this.current.fillAlpha=i;this.ctx.globalAlpha=i;break;case"BM":this.ctx.globalCompositeOperation=i;break;case"SMask":this.current.activeSMask=i?this.tempSMask:null;this.tempSMask=null;this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(i)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,i="smaskGroupAt"+this.groupLevel,s=this.cachedCanvases.getCanvas(i,t,e);this.suspendedCtx=this.ctx;this.ctx=s.context;const n=this.ctx;n.setTransform(...getCurrentTransform(this.suspendedCtx));copyCtxState(this.suspendedCtx,n);!function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function ctxSave(){e.save();this.__originalSave()};t.restore=function ctxRestore(){e.restore();this.__originalRestore()};t.translate=function ctxTranslate(t,i){e.translate(t,i);this.__originalTranslate(t,i)};t.scale=function ctxScale(t,i){e.scale(t,i);this.__originalScale(t,i)};t.transform=function ctxTransform(t,i,s,n,r,a){e.transform(t,i,s,n,r,a);this.__originalTransform(t,i,s,n,r,a)};t.setTransform=function ctxSetTransform(t,i,s,n,r,a){e.setTransform(t,i,s,n,r,a);this.__originalSetTransform(t,i,s,n,r,a)};t.resetTransform=function ctxResetTransform(){e.resetTransform();this.__originalResetTransform()};t.rotate=function ctxRotate(t){e.rotate(t);this.__originalRotate(t)};t.clip=function ctxRotate(t){e.clip(t);this.__originalClip(t)};t.moveTo=function(t,i){e.moveTo(t,i);this.__originalMoveTo(t,i)};t.lineTo=function(t,i){e.lineTo(t,i);this.__originalLineTo(t,i)};t.bezierCurveTo=function(t,i,s,n,r,a){e.bezierCurveTo(t,i,s,n,r,a);this.__originalBezierCurveTo(t,i,s,n,r,a)};t.rect=function(t,i,s,n){e.rect(t,i,s,n);this.__originalRect(t,i,s,n)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(n,this.suspendedCtx);this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,i=this.suspendedCtx;this.composeSMask(i,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}composeSMask(t,e,i,s){const n=s[0],r=s[1],a=s[2]-n,o=s[3]-r;if(0!==a&&0!==o){this.genericComposeSMask(e.context,i,a,o,e.subtype,e.backdrop,e.transferMap,n,r,e.offsetX,e.offsetY);t.save();t.globalAlpha=1;t.globalCompositeOperation="source-over";t.setTransform(1,0,0,1,0,0);t.drawImage(i.canvas,0,0);t.restore()}}genericComposeSMask(t,e,i,s,n,r,a,o,l,h,c){let d=t.canvas,u=o-h,p=l-c;if(r){const e=Util.makeHexColor(...r);if(u<0||p<0||u+i>d.width||p+s>d.height){const t=this.cachedCanvases.getCanvas("maskExtension",i,s),n=t.context;n.drawImage(d,-u,-p);n.globalCompositeOperation="destination-atop";n.fillStyle=e;n.fillRect(0,0,i,s);n.globalCompositeOperation="source-over";d=t.canvas;u=p=0}else{t.save();t.globalAlpha=1;t.setTransform(1,0,0,1,0,0);const n=new Path2D;n.rect(u,p,i,s);t.clip(n);t.globalCompositeOperation="destination-atop";t.fillStyle=e;t.fillRect(u,p,i,s);t.restore()}}e.save();e.globalAlpha=1;e.setTransform(1,0,0,1,0,0);"Alpha"===n&&a?e.filter=this.filterFactory.addAlphaFilter(a):"Luminosity"===n&&(e.filter=this.filterFactory.addLuminosityFilter(a));const g=new Path2D;g.rect(o,l,i,s);e.clip(g);e.globalCompositeOperation="destination-in";e.drawImage(d,u,p,i,s,o,l,i,s);e.restore()}save(){if(this.inSMaskMode){copyCtxState(this.ctx,this.suspendedCtx);this.suspendedCtx.save()}else this.ctx.save();const t=this.current;this.stateStack.push(t);this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode();if(0!==this.stateStack.length){this.current=this.stateStack.pop();if(this.inSMaskMode){this.suspendedCtx.restore();copyCtxState(this.suspendedCtx,this.ctx)}else this.ctx.restore();this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}}transform(t,e,i,s,n,r){this.ctx.transform(t,e,i,s,n,r);this._cachedScaleForStroking[0]=-1;this._cachedGetSinglePixelWidth=null}constructPath(t,e,i){const s=this.ctx,n=this.current;let r,a,o=n.x,l=n.y;const h=getCurrentTransform(s),c=0===h[0]&&0===h[3]||0===h[1]&&0===h[2],d=c?i.slice(0):null;for(let i=0,u=0,p=t.length;i100&&(h=100);this.current.fontSizeScale=e/h;this.ctx.font=`${l} ${o} ${h}px ${a}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t;this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e);this.moveText(t,e)}setTextMatrix(t,e,i,s,n,r){this.current.textMatrix=[t,e,i,s,n,r];this.current.textMatrixScale=Math.hypot(t,e);this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#di(t,e,i){const s=new Path2D;s.addPath(t,new DOMMatrix(i).invertSelf().multiplySelf(e));return s}paintChar(t,e,i,s,n){const r=this.ctx,a=this.current,o=a.font,l=a.textRenderingMode,h=a.fontSize/a.fontSizeScale,c=l&x,d=!!(l&_),u=a.patternFill&&!o.missingFile,p=a.patternStroke&&!o.missingFile;let g;(o.disableFontFace||d||u||p)&&(g=o.getPathGenerator(this.commonObjs,t));if(o.disableFontFace||u||p){r.save();r.translate(e,i);r.scale(h,-h);if(c===v||c===w)if(s){const t=r.getTransform();r.setTransform(...s);r.fill(this.#di(g,t,s))}else r.fill(g);if(c===y||c===w)if(n){const t=r.getTransform();r.setTransform(...n);r.stroke(this.#di(g,t,n))}else{r.lineWidth/=h;r.stroke(g)}r.restore()}else{c!==v&&c!==w||r.fillText(t,e,i);c!==y&&c!==w||r.strokeText(t,e,i)}if(d){(this.pendingTextPaths||=[]).push({transform:getCurrentTransform(r),x:e,y:i,fontSize:h,path:g})}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1);t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let t=3;t0&&e[t]<255){i=!0;break}return shadow(this,"isFontSubpixelAAEnabled",i)}showText(t){const e=this.current,i=e.font;if(i.isType3Font)return this.showType3Text(t);const s=e.fontSize;if(0===s)return;const n=this.ctx,r=e.fontSizeScale,a=e.charSpacing,o=e.wordSpacing,l=e.fontDirection,h=e.textHScale*l,c=t.length,d=i.vertical,u=d?1:-1,p=i.defaultVMetrics,g=s*e.fontMatrix[0],f=e.textRenderingMode===v&&!i.disableFontFace&&!e.patternFill;n.save();n.transform(...e.textMatrix);n.translate(e.x,e.y+e.textRise);l>0?n.scale(h,-1):n.scale(h,1);let m,b;if(e.patternFill){n.save();const t=e.fillColor.getPattern(n,this,getCurrentTransformInverse(n),yt);m=getCurrentTransform(n);n.restore();n.fillStyle=t}if(e.patternStroke){n.save();const t=e.strokeColor.getPattern(n,this,getCurrentTransformInverse(n),wt);b=getCurrentTransform(n);n.restore();n.strokeStyle=t}let A=e.lineWidth;const _=e.textMatrixScale;if(0===_||0===A){const t=e.textRenderingMode&x;t!==y&&t!==w||(A=this.getSinglePixelWidth())}else A/=_;if(1!==r){n.scale(r,r);A/=r}n.lineWidth=A;if(i.isInvalidPDFjsFont){const i=[];let s=0;for(const e of t){i.push(e.unicode);s+=e.width}n.fillText(i.join(""),0,0);e.x+=s*g*h;n.restore();this.compose();return}let E,S=0;for(E=0;E0){const t=1e3*n.measureText(v).width/s*r;if(xnew CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new TilingPattern(t,i,this.ctx,n,s)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments);this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments);this.current.patternFill=!0}setStrokeRGBColor(t,e,i){this.ctx.strokeStyle=this.current.strokeColor=Util.makeHexColor(t,e,i);this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent";this.current.patternStroke=!1}setFillRGBColor(t,e,i){this.ctx.fillStyle=this.current.fillColor=Util.makeHexColor(t,e,i);this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent";this.current.patternFill=!1}_getPattern(t,e=null){let i;if(this.cachedPatterns.has(t))i=this.cachedPatterns.get(t);else{i=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)}(this.getObject(t));this.cachedPatterns.set(t,i)}e&&(i.matrix=e);return i}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const i=this._getPattern(t);e.fillStyle=i.getPattern(e,this,getCurrentTransformInverse(e),At);const s=getCurrentTransformInverse(e);if(s){const{width:t,height:i}=e.canvas,[n,r,a,o]=Util.getAxialAlignedBoundingBox([0,0,t,i],s);this.ctx.fillRect(n,r,a-n,o-r)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox());this.restore()}beginInlineImage(){unreachable("Should not call beginInlineImage")}beginImageData(){unreachable("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible){this.save();this.baseTransformStack.push(this.baseTransform);t&&this.transform(...t);this.baseTransform=getCurrentTransform(this.ctx);if(e){const t=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],t,i);this.current.updateRectMinMax(getCurrentTransform(this.ctx),e);this.clip();this.endPath()}}}paintFormXObjectEnd(){if(this.contentVisible){this.restore();this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t){if(!this.contentVisible)return;this.save();if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const e=this.ctx;t.isolated||info("TODO: Support non-isolated groups.");t.knockout&&warn("Knockout groups not supported.");const i=getCurrentTransform(e);t.matrix&&e.transform(...t.matrix);if(!t.bbox)throw new Error("Bounding box is required.");let s=Util.getAxialAlignedBoundingBox(t.bbox,getCurrentTransform(e));const n=[0,0,e.canvas.width,e.canvas.height];s=Util.intersect(s,n)||[0,0,0,0];const r=Math.floor(s[0]),a=Math.floor(s[1]),o=Math.max(Math.ceil(s[2])-r,1),l=Math.max(Math.ceil(s[3])-a,1);this.current.startNewPathAndClipBox([0,0,o,l]);let h="groupAt"+this.groupLevel;t.smask&&(h+="_smask_"+this.smaskCounter++%2);const c=this.cachedCanvases.getCanvas(h,o,l),d=c.context;d.translate(-r,-a);d.transform(...i);if(t.smask)this.smaskStack.push({canvas:c.canvas,context:d,offsetX:r,offsetY:a,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null});else{e.setTransform(1,0,0,1,0,0);e.translate(r,a);e.save()}copyCtxState(e,d);this.ctx=d;this.setGState([["BM","source-over"],["ca",1],["CA",1]]);this.groupStack.push(e);this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,i=this.groupStack.pop();this.ctx=i;this.ctx.imageSmoothingEnabled=!1;if(t.smask){this.tempSMask=this.smaskStack.pop();this.restore()}else{this.ctx.restore();const t=getCurrentTransform(this.ctx);this.restore();this.ctx.save();this.ctx.setTransform(...t);const i=Util.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0);this.ctx.restore();this.compose(i)}}beginAnnotation(t,e,i,s,n){this.#hi();resetCtxToDefault(this.ctx);this.ctx.save();this.save();this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(e){const s=e[2]-e[0],r=e[3]-e[1];if(n&&this.annotationCanvasMap){(i=i.slice())[4]-=e[0];i[5]-=e[1];(e=e.slice())[0]=e[1]=0;e[2]=s;e[3]=r;const[n,a]=Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx)),{viewportScale:o}=this,l=Math.ceil(s*this.outputScaleX*o),h=Math.ceil(r*this.outputScaleY*o);this.annotationCanvas=this.canvasFactory.create(l,h);const{canvas:c,context:d}=this.annotationCanvas;this.annotationCanvasMap.set(t,c);this.annotationCanvas.savedCtx=this.ctx;this.ctx=d;this.ctx.save();this.ctx.setTransform(n,0,0,-a,0,r*a);resetCtxToDefault(this.ctx)}else{resetCtxToDefault(this.ctx);this.endPath();this.ctx.rect(e[0],e[1],s,r);this.ctx.clip();this.ctx.beginPath()}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(...i);this.transform(...s)}endAnnotation(){if(this.annotationCanvas){this.ctx.restore();this.#ci();this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;(t=this.getObject(t.data,t)).count=e;const i=this.ctx,s=this.processingType3;if(s){void 0===s.compiled&&(s.compiled=function compileType3Glyph(t){const{width:e,height:i}=t;if(e>1e3||i>1e3)return null;const s=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=e+1;let r,a,o,l=new Uint8Array(n*(i+1));const h=e+7&-8;let c=new Uint8Array(h*i),d=0;for(const e of t.data){let t=128;for(;t>0;){c[d++]=e&t?0:255;t>>=1}}let u=0;d=0;if(0!==c[d]){l[0]=1;++u}for(a=1;a>2)+(c[d+1]?4:0)+(c[d-h+1]?8:0);if(s[t]){l[o+a]=s[t];++u}d++}if(c[d-h]!==c[d]){l[o+a]=c[d]?2:4;++u}if(u>1e3)return null}d=h*(i-1);o=r*n;if(0!==c[d]){l[o]=8;++u}for(a=1;a1e3)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),g=new Path2D;for(r=0;u&&r<=i;r++){let t=r*n;const i=t+e;for(;t>4;l[t]&=a>>2|a<<2}g.lineTo(t%n,t/n|0);l[t]||--u}while(s!==t);--r}c=null;l=null;return function(t){t.save();t.scale(1/e,-1/i);t.translate(0,-i);t.fill(g);t.beginPath();t.restore()}}(t));if(s.compiled){s.compiled(i);return}}const n=this._createMaskCanvas(t),r=n.canvas;i.save();i.setTransform(1,0,0,1,0,0);i.drawImage(r,n.offsetX,n.offsetY);i.restore();this.compose()}paintImageMaskXObjectRepeat(t,e,i=0,s=0,n,r){if(!this.contentVisible)return;t=this.getObject(t.data,t);const a=this.ctx;a.save();const o=getCurrentTransform(a);a.transform(e,i,s,n,0,0);const l=this._createMaskCanvas(t);a.setTransform(1,0,0,1,l.offsetX-o[4],l.offsetY-o[5]);for(let t=0,h=r.length;te?h/e:1;a=l>e?l/e:1}}this._cachedScaleForStroking[0]=r;this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:i}=this.current,[s,n]=this.getScaleForStroking();e.lineWidth=i||1;if(1===s&&1===n){e.stroke();return}const r=e.getLineDash();t&&e.save();e.scale(s,n);if(r.length>0){const t=Math.max(s,n);e.setLineDash(r.map((e=>e/t)));e.lineDashOffset/=t}e.stroke();t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const t in K)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[K[t]]=CanvasGraphics.prototype[t]);class GlobalWorkerOptions{static#ui=null;static#pi="";static get workerPort(){return this.#ui}static set workerPort(t){if(!("undefined"!=typeof Worker&&t instanceof Worker)&&null!==t)throw new Error("Invalid `workerPort` type.");this.#ui=t}static get workerSrc(){return this.#pi}static set workerSrc(t){if("string"!=typeof t)throw new Error("Invalid `workerSrc` type.");this.#pi=t}}class Metadata{#gi;#fi;constructor({parsedData:t,rawData:e}){this.#gi=t;this.#fi=e}getRaw(){return this.#fi}get(t){return this.#gi.get(t)??null}getAll(){return objectFromMap(this.#gi)}has(t){return this.#gi.has(t)}}const Pt=Symbol("INTERNAL");class OptionalContentGroup{#mi=!1;#bi=!1;#vi=!1;#yi=!0;constructor(t,{name:e,intent:i,usage:s,rbGroups:n}){this.#mi=!!(t&o);this.#bi=!!(t&l);this.name=e;this.intent=i;this.usage=s;this.rbGroups=n}get visible(){if(this.#vi)return this.#yi;if(!this.#yi)return!1;const{print:t,view:e}=this.usage;return this.#mi?"OFF"!==e?.viewState:!this.#bi||"OFF"!==t?.printState}_setVisible(t,e,i=!1){t!==Pt&&unreachable("Internal method `_setVisible` called.");this.#vi=i;this.#yi=e}}class OptionalContentConfig{#wi=null;#Ai=new Map;#xi=null;#_i=null;constructor(t,e=o){this.renderingIntent=e;this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#_i=t.order;for(const i of t.groups)this.#Ai.set(i.id,new OptionalContentGroup(e,i));if("OFF"===t.baseState)for(const t of this.#Ai.values())t._setVisible(Pt,!1);for(const e of t.on)this.#Ai.get(e)._setVisible(Pt,!0);for(const e of t.off)this.#Ai.get(e)._setVisible(Pt,!1);this.#xi=this.getHash()}}#Ei(t){const e=t.length;if(e<2)return!0;const i=t[0];for(let s=1;s0?objectFromMap(this.#Ai):null}getGroup(t){return this.#Ai.get(t)||null}getHash(){if(null!==this.#wi)return this.#wi;const t=new MurmurHash3_64;for(const[e,i]of this.#Ai)t.update(`${e}:${i.visible}`);return this.#wi=t.hexdigest()}}class PDFDataTransportStream{constructor(t,{disableRange:e=!1,disableStream:i=!1}){assert(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:s,initialData:n,progressiveDone:r,contentDispositionFilename:a}=t;this._queuedChunks=[];this._progressiveDone=r;this._contentDispositionFilename=a;if(n?.length>0){const t=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=t;this._isStreamingSupported=!i;this._isRangeSupported=!e;this._contentLength=s;this._fullRequestReader=null;this._rangeReaders=[];t.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})}));t.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})}));t.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})}));t.addProgressiveDoneListener((()=>{this._onProgressiveDone()}));t.transportReady()}_onReceiveData({begin:t,chunk:e}){const i=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(void 0===t)this._fullRequestReader?this._fullRequestReader._enqueue(i):this._queuedChunks.push(i);else{assert(this._rangeReaders.some((function(e){if(e._begin!==t)return!1;e._enqueue(i);return!0})),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone();this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;this._queuedChunks=null;return new PDFDataTransportStreamReader(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFDataTransportStreamRangeReader(this,t,e);this._pdfDataRangeTransport.requestDataRange(t,e);this._rangeReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class PDFDataTransportStreamReader{constructor(t,e,i=!1,s=null){this._stream=t;this._done=i||!1;this._filename=isPdfFile(s)?s:null;this._queuedChunks=e||[];this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[];this._headersReady=Promise.resolve();t._fullRequestReader=this;this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class PDFDataTransportStreamRangeReader{constructor(t,e,i){this._stream=t;this._begin=e;this._end=i;this._queuedChunk=null;this._requests=[];this._done=!1;this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0;this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._stream._removeRangeReader(this)}}function createHeaders(t,e){const i=new Headers;if(!t||!e||"object"!=typeof e)return i;for(const t in e){const s=e[t];void 0!==s&&i.append(t,s)}return i}function getResponseOrigin(t){try{return new URL(t).origin}catch{}return null}function validateRangeRequestCapabilities({responseHeaders:t,isHttp:e,rangeChunkSize:i,disableRange:s}){const n={allowRangeRequests:!1,suggestedLength:void 0},r=parseInt(t.get("Content-Length"),10);if(!Number.isInteger(r))return n;n.suggestedLength=r;if(r<=2*i)return n;if(s||!e)return n;if("bytes"!==t.get("Accept-Ranges"))return n;if("identity"!==(t.get("Content-Encoding")||"identity"))return n;n.allowRangeRequests=!0;return n}function extractFilenameFromHeader(t){const e=t.get("Content-Disposition");if(e){let t=function getFilenameFromContentDispositionHeader(t){let e=!0,i=toParamRegExp("filename\\*","i").exec(t);if(i){i=i[1];let t=rfc2616unquote(i);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}i=function rfc2231getparam(t){const e=[];let i;const s=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(i=s.exec(t));){let[,t,s,n]=i;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[s,n]}const n=[];for(let t=0;t{t._responseOrigin=getResponseOrigin(e.url);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,s);this._reader=e.body.getReader();this._headersCapability.resolve();const i=e.headers,{allowRangeRequests:n,suggestedLength:r}=validateRangeRequestCapabilities({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=n;this._contentLength=r||this._contentLength;this._filename=extractFilenameFromHeader(i);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject);this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader{constructor(t,e,i){this._stream=t;this._reader=null;this._loaded=0;const s=t.source;this._withCredentials=s.withCredentials||!1;this._readCapability=Promise.withResolvers();this._isStreamingSupported=!s.disableStream;this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${i-1}`);const r=s.url;fetch(r,createFetchOptions(n,this._withCredentials,this._abortController)).then((e=>{const i=getResponseOrigin(e.url);if(i!==t._responseOrigin)throw new Error(`Expected range response-origin "${i}" to match "${t._responseOrigin}".`);if(!validateResponseStatus(e.status))throw createResponseStatusError(e.status,r);this._readCapability.resolve();this._reader=e.body.getReader()})).catch(this._readCapability.reject);this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded});return{value:getArrayBuffer(t),done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class NetworkManager{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:i}){this.url=t;this.isHttp=/^https?:/i.test(t);this.headers=createHeaders(this.isHttp,e);this.withCredentials=i||!1;this.currXhrId=0;this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,i=this.currXhrId++,s=this.pendingRequests[i]={xhr:e};e.open("GET",this.url);e.withCredentials=this.withCredentials;for(const[t,i]of this.headers)e.setRequestHeader(t,i);if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);s.expectedStatus=206}else s.expectedStatus=200;e.responseType="arraybuffer";assert(t.onError,"Expected `onError` callback to be provided.");e.onerror=()=>{t.onError(e.status)};e.onreadystatechange=this.onStateChange.bind(this,i);e.onprogress=this.onProgress.bind(this,i);s.onHeadersReceived=t.onHeadersReceived;s.onDone=t.onDone;s.onError=t.onError;s.onProgress=t.onProgress;e.send(null);return i}onProgress(t,e){const i=this.pendingRequests[t];i&&i.onProgress?.(e)}onStateChange(t,e){const i=this.pendingRequests[t];if(!i)return;const s=i.xhr;if(s.readyState>=2&&i.onHeadersReceived){i.onHeadersReceived();delete i.onHeadersReceived}if(4!==s.readyState)return;if(!(t in this.pendingRequests))return;delete this.pendingRequests[t];if(0===s.status&&this.isHttp){i.onError(s.status);return}const n=s.status||200;if(!(200===n&&206===i.expectedStatus)&&n!==i.expectedStatus){i.onError(s.status);return}const r=function network_getArrayBuffer(t){const e=t.response;return"string"!=typeof e?e:stringToBytes(e).buffer}(s);if(206===n){const t=s.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);if(e)i.onDone({begin:parseInt(e[1],10),chunk:r});else{warn('Missing or invalid "Content-Range" header.');i.onError(0)}}else r?i.onDone({begin:0,chunk:r}):i.onError(s.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t];e.abort()}}class PDFNetworkStream{constructor(t){this._source=t;this._manager=new NetworkManager(t);this._rangeChunkSize=t.rangeChunkSize;this._fullRequestReader=null;this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){assert(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNetworkStreamFullRequestReader(this._manager,this._source);return this._fullRequestReader}getRangeReader(t,e){const i=new PDFNetworkStreamRangeRequestReader(this._manager,t,e);i.onClosed=this._onRangeRequestReaderClosed.bind(this);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNetworkStreamFullRequestReader{constructor(t,e){this._manager=t;this._url=e.url;this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._headersCapability=Promise.withResolvers();this._disableRange=e.disableRange||!1;this._contentLength=e.length;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!1;this._isRangeSupported=!1;this._cachedChunks=[];this._requests=[];this._done=!1;this._storedError=void 0;this._filename=null;this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=getResponseOrigin(e.responseURL);const i=e.getAllResponseHeaders(),s=new Headers(i?i.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map((t=>{const[e,...i]=t.split(": ");return[e,i.join(": ")]})):[]),{allowRangeRequests:n,suggestedLength:r}=validateRangeRequestCapabilities({responseHeaders:s,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0);this._contentLength=r||this._contentLength;this._filename=extractFilenameFromHeader(s);this._isRangeSupported&&this._manager.abortRequest(t);this._headersCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);this._done=!0;if(!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=createResponseStatusError(t,this._url);this._headersCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){await this._headersCapability.promise;if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this._headersCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId);this._fullRequestReader=null}}class PDFNetworkStreamRangeRequestReader{constructor(t,e,i){this._manager=t;this._url=t.url;this._requestId=t.request({begin:e,end:i,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)});this._requests=[];this._queuedChunk=null;this._done=!1;this._storedError=void 0;this.onProgress=null;this.onClosed=null}_onHeadersReceived(){const t=getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL);if(t!==this._manager._responseOrigin){this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`);this._onError(0)}}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else this._queuedChunk=e;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._close()}_onError(t){this._storedError??=createResponseStatusError(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId);this._close()}}const Dt=/^[a-z][a-z0-9\-+.]+:/i;class PDFNodeStream{constructor(t){this.source=t;this.url=function parseUrlOrPath(t){if(Dt.test(t))return new URL(t);const e=process.getBuiltinModule("url");return new URL(e.pathToFileURL(t))}(t.url);assert("file:"===this.url.protocol,"PDFNodeStream only supports file:// URLs.");this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){assert(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNodeStreamFsFullReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const i=new PDFNodeStreamFsRangeReader(this,t,e);this._rangeRequestReaders.push(i);return i}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class PDFNodeStreamFsFullReader{constructor(t){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;const e=t.source;this._contentLength=e.length;this._loaded=0;this._filename=null;this._disableRange=e.disableRange||!1;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;this._readableStream=null;this._readCapability=Promise.withResolvers();this._headersCapability=Promise.withResolvers();const i=process.getBuiltinModule("fs");i.promises.lstat(this._url).then((t=>{this._contentLength=t.size;this._setReadableStream(i.createReadStream(this._url));this._headersCapability.resolve()}),(t=>{"ENOENT"===t.code&&(t=new MissingPDFException(`Missing PDF "${this._url}".`));this._storedError=t;this._headersCapability.reject(t)}))}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));!this._isStreamingSupported&&this._isRangeSupported&&this._error(new AbortException("streaming is disabled"));this._storedError&&this._readableStream.destroy(this._storedError)}}class PDFNodeStreamFsRangeReader{constructor(t,e,i){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;this._loaded=0;this._readableStream=null;this._readCapability=Promise.withResolvers();const s=t.source;this._isStreamingSupported=!s.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:i-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=Promise.withResolvers();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));this._storedError&&this._readableStream.destroy(this._storedError)}}const kt=30;class TextLayer{#Si=Promise.withResolvers();#pt=null;#Ci=!1;#Ti=!!globalThis.FontInspector?.enabled;#Mi=null;#Pi=null;#Di=0;#ki=0;#Ri=null;#Ii=null;#Fi=0;#Li=0;#Oi=Object.create(null);#Ni=[];#Bi=null;#Hi=[];#Ui=new WeakMap;#zi=null;static#ji=new Map;static#Gi=new Map;static#Vi=new WeakMap;static#$i=null;static#Wi=new Set;constructor({textContentSource:t,container:e,viewport:i}){if(t instanceof ReadableStream)this.#Bi=t;else{if("object"!=typeof t)throw new Error('No "textContentSource" parameter specified.');this.#Bi=new ReadableStream({start(e){e.enqueue(t);e.close()}})}this.#pt=this.#Ii=e;this.#Li=i.scale*(globalThis.devicePixelRatio||1);this.#Fi=i.rotation;this.#Pi={div:null,properties:null,ctx:null};const{pageWidth:s,pageHeight:n,pageX:r,pageY:a}=i.rawDims;this.#zi=[1,0,0,-1,-r,a+n];this.#ki=s;this.#Di=n;TextLayer.#qi();setLayerDimensions(e,i);this.#Si.promise.finally((()=>{TextLayer.#Wi.delete(this);this.#Pi=null;this.#Oi=null})).catch((()=>{}))}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=util_FeatureTest.platform;return shadow(this,"fontFamilyMap",new Map([["sans-serif",(t&&e?"Calibri, ":"")+"sans-serif"],["monospace",(t&&e?"Lucida Console, ":"")+"monospace"]]))}render(){const pump=()=>{this.#Ri.read().then((({value:t,done:e})=>{if(e)this.#Si.resolve();else{this.#Mi??=t.lang;Object.assign(this.#Oi,t.styles);this.#Xi(t.items);pump()}}),this.#Si.reject)};this.#Ri=this.#Bi.getReader();TextLayer.#Wi.add(this);pump();return this.#Si.promise}update({viewport:t,onBefore:e=null}){const i=t.scale*(globalThis.devicePixelRatio||1),s=t.rotation;if(s!==this.#Fi){e?.();this.#Fi=s;setLayerDimensions(this.#Ii,{rotation:s})}if(i!==this.#Li){e?.();this.#Li=i;const t={div:null,properties:null,ctx:TextLayer.#Yi(this.#Mi)};for(const e of this.#Hi){t.properties=this.#Ui.get(e);t.div=e;this.#Ki(t)}}}cancel(){const t=new AbortException("TextLayer task cancelled.");this.#Ri?.cancel(t).catch((()=>{}));this.#Ri=null;this.#Si.reject(t)}get textDivs(){return this.#Hi}get textContentItemsStr(){return this.#Ni}#Xi(t){if(this.#Ci)return;this.#Pi.ctx??=TextLayer.#Yi(this.#Mi);const e=this.#Hi,i=this.#Ni;for(const s of t){if(e.length>1e5){warn("Ignoring additional textDivs for performance reasons.");this.#Ci=!0;return}if(void 0!==s.str){i.push(s.str);this.#Qi(s)}else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this.#pt;this.#pt=document.createElement("span");this.#pt.classList.add("markedContent");null!==s.id&&this.#pt.setAttribute("id",`${s.id}`);t.append(this.#pt)}else"endMarkedContent"===s.type&&(this.#pt=this.#pt.parentNode)}}#Qi(t){const e=document.createElement("span"),i={angle:0,canvasWidth:0,hasText:""!==t.str,hasEOL:t.hasEOL,fontSize:0};this.#Hi.push(e);const s=Util.transform(this.#zi,t.transform);let n=Math.atan2(s[1],s[0]);const r=this.#Oi[t.fontName];r.vertical&&(n+=Math.PI/2);let a=this.#Ti&&r.fontSubstitution||r.fontFamily;a=TextLayer.fontFamilyMap.get(a)||a;const o=Math.hypot(s[2],s[3]),l=o*TextLayer.#Ji(a,this.#Mi);let h,c;if(0===n){h=s[4];c=s[5]-l}else{h=s[4]+l*Math.sin(n);c=s[5]-l*Math.cos(n)}const d="calc(var(--scale-factor)*",u=e.style;if(this.#pt===this.#Ii){u.left=`${(100*h/this.#ki).toFixed(2)}%`;u.top=`${(100*c/this.#Di).toFixed(2)}%`}else{u.left=`${d}${h.toFixed(2)}px)`;u.top=`${d}${c.toFixed(2)}px)`}u.fontSize=`${d}${(TextLayer.#$i*o).toFixed(2)}px)`;u.fontFamily=a;i.fontSize=o;e.setAttribute("role","presentation");e.textContent=t.str;e.dir=t.dir;this.#Ti&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName);0!==n&&(i.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(" "!==t.str&&t.transform[0]!==t.transform[3]){const e=Math.abs(t.transform[0]),i=Math.abs(t.transform[3]);e!==i&&Math.max(e,i)/Math.min(e,i)>1.5&&(p=!0)}p&&(i.canvasWidth=r.vertical?t.height:t.width);this.#Ui.set(e,i);this.#Pi.div=e;this.#Pi.properties=i;this.#Ki(this.#Pi);i.hasText&&this.#pt.append(e);if(i.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this.#pt.append(t)}}#Ki(t){const{div:e,properties:i,ctx:s}=t,{style:n}=e;let r="";TextLayer.#$i>1&&(r=`scale(${1/TextLayer.#$i})`);if(0!==i.canvasWidth&&i.hasText){const{fontFamily:t}=n,{canvasWidth:a,fontSize:o}=i;TextLayer.#Zi(s,o*this.#Li,t);const{width:l}=s.measureText(e.textContent);l>0&&(r=`scaleX(${a*this.#Li/l}) ${r}`)}0!==i.angle&&(r=`rotate(${i.angle}deg) ${r}`);r.length>0&&(n.transform=r)}static cleanup(){if(!(this.#Wi.size>0)){this.#ji.clear();for(const{canvas:t}of this.#Gi.values())t.remove();this.#Gi.clear()}}static#Yi(t=null){let e=this.#Gi.get(t||="");if(!e){const i=document.createElement("canvas");i.className="hiddenCanvasElement";i.lang=t;document.body.append(i);e=i.getContext("2d",{alpha:!1,willReadFrequently:!0});this.#Gi.set(t,e);this.#Vi.set(e,{size:0,family:""})}return e}static#Zi(t,e,i){const s=this.#Vi.get(t);if(e!==s.size||i!==s.family){t.font=`${e}px ${i}`;s.size=e;s.family=i}}static#qi(){if(null!==this.#$i)return;const t=document.createElement("div");t.style.opacity=0;t.style.lineHeight=1;t.style.fontSize="1px";t.style.position="absolute";t.textContent="X";document.body.append(t);this.#$i=t.getBoundingClientRect().height;t.remove()}static#Ji(t,e){const i=this.#ji.get(t);if(i)return i;const s=this.#Yi(e);s.canvas.width=s.canvas.height=kt;this.#Zi(s,kt,t);const n=s.measureText("");let r=n.fontBoundingBoxAscent,a=Math.abs(n.fontBoundingBoxDescent);if(r){const e=r/(r+a);this.#ji.set(t,e);s.canvas.width=s.canvas.height=0;return e}s.strokeStyle="red";s.clearRect(0,0,kt,kt);s.strokeText("g",0,0);let o=s.getImageData(0,0,kt,kt).data;a=0;for(let t=o.length-1-3;t>=0;t-=4)if(o[t]>0){a=Math.ceil(t/4/kt);break}s.clearRect(0,0,kt,kt);s.strokeText("A",0,kt);o=s.getImageData(0,0,kt,kt).data;r=0;for(let t=0,e=o.length;t0){r=kt-Math.floor(t/4/kt);break}s.canvas.width=s.canvas.height=0;const l=r?r/(r+a):.8;this.#ji.set(t,l);return l}}class XfaText{static textContent(t){const e=[],i={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let i=null;const s=t.name;if("#text"===s)i=t.value;else{if(!XfaText.shouldBuildText(s))return;t?.attributes?.textContent?i=t.attributes.textContent:t.value&&(i=t.value)}null!==i&&e.push({str:i});if(t.children)for(const e of t.children)walk(e)}(t);return i}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}const Rt=65536,It=i?class NodeCanvasFactory extends BaseCanvasFactory{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(t,e)}}:class DOMCanvasFactory extends BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e});this._document=t}_createCanvas(t,e){const i=this._document.createElement("canvas");i.width=t;i.height=e;return i}},Ft=i?class NodeCMapReaderFactory extends BaseCMapReaderFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMCMapReaderFactory,Lt=i?class NodeFilterFactory extends BaseFilterFactory{}:class DOMFilterFactory extends BaseFilterFactory{#ts;#es;#is;#ss;#ns;#rs;#y=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super();this.#ss=t;this.#ns=e}get#A(){return this.#es||=new Map}get#as(){return this.#rs||=new Map}get#os(){if(!this.#is){const t=this.#ns.createElement("div"),{style:e}=t;e.visibility="hidden";e.contain="strict";e.width=e.height=0;e.position="absolute";e.top=e.left=0;e.zIndex=-1;const i=this.#ns.createElementNS(nt,"svg");i.setAttribute("width",0);i.setAttribute("height",0);this.#is=this.#ns.createElementNS(nt,"defs");t.append(i);i.append(this.#is);this.#ns.body.append(t)}return this.#is}#ls(t){if(1===t.length){const e=t[0],i=new Array(256);for(let t=0;t<256;t++)i[t]=e[t]/255;const s=i.join(",");return[s,s,s]}const[e,i,s]=t,n=new Array(256),r=new Array(256),a=new Array(256);for(let t=0;t<256;t++){n[t]=e[t]/255;r[t]=i[t]/255;a[t]=s[t]/255}return[n.join(","),r.join(","),a.join(",")]}#hs(t){if(void 0===this.#ts){this.#ts="";const t=this.#ns.URL;t!==this.#ns.baseURI&&(isDataScheme(t)?warn('#createUrl: ignore "data:"-URL for performance reasons.'):this.#ts=t.split("#",1)[0])}return`url(${this.#ts}#${t})`}addFilter(t){if(!t)return"none";let e=this.#A.get(t);if(e)return e;const[i,s,n]=this.#ls(t),r=1===t.length?i:`${i}${s}${n}`;e=this.#A.get(r);if(e){this.#A.set(t,e);return e}const a=`g_${this.#ss}_transfer_map_${this.#y++}`,o=this.#hs(a);this.#A.set(t,o);this.#A.set(r,o);const l=this.#cs(a);this.#ds(i,s,n,l);return o}addHCMFilter(t,e){const i=`${t}-${e}`,s="base";let n=this.#as.get(s);if(n?.key===i)return n.url;if(n){n.filter?.remove();n.key=i;n.url="none";n.filter=null}else{n={key:i,url:"none",filter:null};this.#as.set(s,n)}if(!t||!e)return n.url;const r=this.#us(t);t=Util.makeHexColor(...r);const a=this.#us(e);e=Util.makeHexColor(...a);this.#os.style.color="";if("#000000"===t&&"#ffffff"===e||t===e)return n.url;const o=new Array(256);for(let t=0;t<=255;t++){const e=t/255;o[t]=e<=.03928?e/12.92:((e+.055)/1.055)**2.4}const l=o.join(","),h=`g_${this.#ss}_hcm_filter`,c=n.filter=this.#cs(h);this.#ds(l,l,l,c);this.#ps(c);const getSteps=(t,e)=>{const i=r[t]/255,s=a[t]/255,n=new Array(e+1);for(let t=0;t<=e;t++)n[t]=i+t/e*(s-i);return n.join(",")};this.#ds(getSteps(0,5),getSteps(1,5),getSteps(2,5),c);n.url=this.#hs(h);return n.url}addAlphaFilter(t){let e=this.#A.get(t);if(e)return e;const[i]=this.#ls([t]),s=`alpha_${i}`;e=this.#A.get(s);if(e){this.#A.set(t,e);return e}const n=`g_${this.#ss}_alpha_map_${this.#y++}`,r=this.#hs(n);this.#A.set(t,r);this.#A.set(s,r);const a=this.#cs(n);this.#gs(i,a);return r}addLuminosityFilter(t){let e,i,s=this.#A.get(t||"luminosity");if(s)return s;if(t){[e]=this.#ls([t]);i=`luminosity_${e}`}else i="luminosity";s=this.#A.get(i);if(s){this.#A.set(t,s);return s}const n=`g_${this.#ss}_luminosity_map_${this.#y++}`,r=this.#hs(n);this.#A.set(t,r);this.#A.set(i,r);const a=this.#cs(n);this.#fs(a);t&&this.#gs(e,a);return r}addHighlightHCMFilter(t,e,i,s,n){const r=`${e}-${i}-${s}-${n}`;let a=this.#as.get(t);if(a?.key===r)return a.url;if(a){a.filter?.remove();a.key=r;a.url="none";a.filter=null}else{a={key:r,url:"none",filter:null};this.#as.set(t,a)}if(!e||!i)return a.url;const[o,l]=[e,i].map(this.#us.bind(this));let h=Math.round(.2126*o[0]+.7152*o[1]+.0722*o[2]),c=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),[d,u]=[s,n].map(this.#us.bind(this));c{const s=new Array(256),n=(c-h)/i,r=t/255,a=(e-t)/(255*i);let o=0;for(let t=0;t<=i;t++){const e=Math.round(h+t*n),i=r+t*a;for(let t=o;t<=e;t++)s[t]=i;o=e+1}for(let t=o;t<256;t++)s[t]=s[o-1];return s.join(",")},p=`g_${this.#ss}_hcm_${t}_filter`,g=a.filter=this.#cs(p);this.#ps(g);this.#ds(getSteps(d[0],u[0],5),getSteps(d[1],u[1],5),getSteps(d[2],u[2],5),g);a.url=this.#hs(p);return a.url}destroy(t=!1){if(!t||!this.#rs?.size){this.#is?.parentNode.parentNode.remove();this.#is=null;this.#es?.clear();this.#es=null;this.#rs?.clear();this.#rs=null;this.#y=0}}#fs(t){const e=this.#ns.createElementNS(nt,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0");t.append(e)}#ps(t){const e=this.#ns.createElementNS(nt,"feColorMatrix");e.setAttribute("type","matrix");e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0");t.append(e)}#cs(t){const e=this.#ns.createElementNS(nt,"filter");e.setAttribute("color-interpolation-filters","sRGB");e.setAttribute("id",t);this.#os.append(e);return e}#ms(t,e,i){const s=this.#ns.createElementNS(nt,e);s.setAttribute("type","discrete");s.setAttribute("tableValues",i);t.append(s)}#ds(t,e,i,s){const n=this.#ns.createElementNS(nt,"feComponentTransfer");s.append(n);this.#ms(n,"feFuncR",t);this.#ms(n,"feFuncG",e);this.#ms(n,"feFuncB",i)}#gs(t,e){const i=this.#ns.createElementNS(nt,"feComponentTransfer");e.append(i);this.#ms(i,"feFuncA",t)}#us(t){this.#os.style.color=t;return getRGB(getComputedStyle(this.#os).getPropertyValue("color"))}},Ot=i?class NodeStandardFontDataFactory extends BaseStandardFontDataFactory{async _fetch(t){return node_utils_fetchData(t)}}:DOMStandardFontDataFactory;function getDocument(t={}){"string"==typeof t||t instanceof URL?t={url:t}:(t instanceof ArrayBuffer||ArrayBuffer.isView(t))&&(t={data:t});const e=new PDFDocumentLoadingTask,{docId:s}=e,n=t.url?function getUrlProp(t){if(t instanceof URL)return t.href;try{return new URL(t,window.location).href}catch{if(i&&"string"==typeof t)return t}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}(t.url):null,r=t.data?function getDataProp(t){if(i&&"undefined"!=typeof Buffer&&t instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength)return t;if("string"==typeof t)return stringToBytes(t);if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||"object"==typeof t&&!isNaN(t?.length))return new Uint8Array(t);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}(t.data):null,a=t.httpHeaders||null,o=!0===t.withCredentials,l=t.password??null,h=t.range instanceof PDFDataRangeTransport?t.range:null,c=Number.isInteger(t.rangeChunkSize)&&t.rangeChunkSize>0?t.rangeChunkSize:Rt;let d=t.worker instanceof PDFWorker?t.worker:null;const u=t.verbosity,p="string"!=typeof t.docBaseUrl||isDataScheme(t.docBaseUrl)?null:t.docBaseUrl,g="string"==typeof t.cMapUrl?t.cMapUrl:null,f=!1!==t.cMapPacked,m=t.CMapReaderFactory||Ft,b="string"==typeof t.standardFontDataUrl?t.standardFontDataUrl:null,v=t.StandardFontDataFactory||Ot,y=!0!==t.stopAtErrors,w=Number.isInteger(t.maxImageSize)&&t.maxImageSize>-1?t.maxImageSize:-1,A=!1!==t.isEvalSupported,x="boolean"==typeof t.isOffscreenCanvasSupported?t.isOffscreenCanvasSupported:!i,_="boolean"==typeof t.isImageDecoderSupported?t.isImageDecoderSupported:!i&&(util_FeatureTest.platform.isFirefox||!globalThis.chrome),E=Number.isInteger(t.canvasMaxAreaInBytes)?t.canvasMaxAreaInBytes:-1,S="boolean"==typeof t.disableFontFace?t.disableFontFace:i,C=!0===t.fontExtraProperties,T=!0===t.enableXfa,M=t.ownerDocument||globalThis.document,P=!0===t.disableRange,D=!0===t.disableStream,k=!0===t.disableAutoFetch,R=!0===t.pdfBug,I=t.CanvasFactory||It,L=t.FilterFactory||Lt,O=!0===t.enableHWA,N=h?h.length:t.length??NaN,B="boolean"==typeof t.useSystemFonts?t.useSystemFonts:!i&&!S,H="boolean"==typeof t.useWorkerFetch?t.useWorkerFetch:m===DOMCMapReaderFactory&&v===DOMStandardFontDataFactory&&g&&b&&isValidFetchUrl(g,document.baseURI)&&isValidFetchUrl(b,document.baseURI);setVerbosityLevel(u);const U={canvasFactory:new I({ownerDocument:M,enableHWA:O}),filterFactory:new L({docId:s,ownerDocument:M}),cMapReaderFactory:H?null:new m({baseUrl:g,isCompressed:f}),standardFontDataFactory:H?null:new v({baseUrl:b})};if(!d){const t={verbosity:u,port:GlobalWorkerOptions.workerPort};d=t.port?PDFWorker.fromPort(t):new PDFWorker(t);e._worker=d}const z={docId:s,apiVersion:"4.10.38",data:r,password:l,disableAutoFetch:k,rangeChunkSize:c,length:N,docBaseUrl:p,enableXfa:T,evaluatorOptions:{maxImageSize:w,disableFontFace:S,ignoreErrors:y,isEvalSupported:A,isOffscreenCanvasSupported:x,isImageDecoderSupported:_,canvasMaxAreaInBytes:E,fontExtraProperties:C,useSystemFonts:B,cMapUrl:H?g:null,standardFontDataUrl:H?b:null}},j={disableFontFace:S,fontExtraProperties:C,ownerDocument:M,pdfBug:R,styleElement:null,loadingParams:{disableAutoFetch:k,enableXfa:T}};d.promise.then((function(){if(e.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const t=d.messageHandler.sendWithPromise("GetDocRequest",z,r?[r.buffer]:null);let l;if(h)l=new PDFDataTransportStream(h,{disableRange:P,disableStream:D});else if(!r){if(!n)throw new Error("getDocument - no `url` parameter provided.");let t;if(i)if(isValidFetchUrl(n)){if("undefined"==typeof fetch||"undefined"==typeof Response||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");t=PDFFetchStream}else t=PDFNodeStream;else t=isValidFetchUrl(n)?PDFFetchStream:PDFNetworkStream;l=new t({url:n,length:N,httpHeaders:a,withCredentials:o,rangeChunkSize:c,disableRange:P,disableStream:D})}return t.then((t=>{if(e.destroyed)throw new Error("Loading aborted");if(d.destroyed)throw new Error("Worker was destroyed");const i=new MessageHandler(s,t,d.port),n=new WorkerTransport(i,e,l,j,U);e._transport=n;i.send("Ready",null)}))})).catch(e._capability.reject);return e}function isRefProxy(t){return"object"==typeof t&&Number.isInteger(t?.num)&&t.num>=0&&Number.isInteger(t?.gen)&&t.gen>=0}class PDFDocumentLoadingTask{static#ss=0;constructor(){this._capability=Promise.withResolvers();this._transport=null;this._worker=null;this.docId="d"+PDFDocumentLoadingTask.#ss++;this.destroyed=!1;this.onPassword=null;this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0);await(this._transport?.destroy())}catch(t){this._worker?.port&&delete this._worker._pendingDestroy;throw t}this._transport=null;this._worker?.destroy();this._worker=null}}class PDFDataRangeTransport{constructor(t,e,i=!1,s=null){this.length=t;this.initialData=e;this.progressiveDone=i;this.contentDispositionFilename=s;this._rangeListeners=[];this._progressListeners=[];this._progressiveReadListeners=[];this._progressiveDoneListeners=[];this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const i of this._rangeListeners)i(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const i of this._progressListeners)i(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){unreachable("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class PDFPageProxy{#bs=null;#vs=!1;constructor(t,e,i,s=!1){this._pageIndex=t;this._pageInfo=e;this._transport=i;this._stats=s?new StatTimer:null;this._pdfBug=s;this.commonObjs=i.commonObjs;this.objs=new PDFObjects;this._maybeCleanupAfterRender=!1;this._intentStates=new Map;this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:i=0,offsetY:s=0,dontFlip:n=!1}={}){return new PageViewport({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:i,offsetY:s,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return shadow(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:i="display",annotationMode:s=g.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:a=null,annotationCanvasMap:o=null,pageColors:h=null,printAnnotationStorage:c=null,isEditing:d=!1}){this._stats?.time("Overall");const u=this._transport.getRenderingIntent(i,s,c,d),{renderingIntent:p,cacheKey:f}=u;this.#vs=!1;this.#ys();a||=this._transport.getOptionalContentConfig(p);let m=this._intentStates.get(f);if(!m){m=Object.create(null);this._intentStates.set(f,m)}if(m.streamReaderCancelTimeout){clearTimeout(m.streamReaderCancelTimeout);m.streamReaderCancelTimeout=null}const b=!!(p&l);if(!m.displayReadyCapability){m.displayReadyCapability=Promise.withResolvers();m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(u)}const complete=t=>{m.renderTasks.delete(v);(this._maybeCleanupAfterRender||b)&&(this.#vs=!0);this.#ws(!b);if(t){v.capability.reject(t);this._abortOperatorList({intentState:m,reason:t instanceof Error?t:new Error(t)})}else v.capability.resolve();if(this._stats){this._stats.timeEnd("Rendering");this._stats.timeEnd("Overall");globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats)}},v=new InternalRenderTask({callback:complete,params:{canvasContext:t,viewport:e,transform:n,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:o,operatorList:m.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!b,pdfBug:this._pdfBug,pageColors:h});(m.renderTasks||=new Set).add(v);const y=v.task;Promise.all([m.displayReadyCapability.promise,a]).then((([t,e])=>{if(this.destroyed)complete();else{this._stats?.time("Rendering");if(!(e.renderingIntent&p))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:t,optionalContentConfig:e});v.operatorListChanged()}})).catch(complete);return y}getOperatorList({intent:t="display",annotationMode:e=g.ENABLE,printAnnotationStorage:i=null,isEditing:s=!1}={}){const n=this._transport.getRenderingIntent(t,e,i,s,!0);let r,a=this._intentStates.get(n.cacheKey);if(!a){a=Object.create(null);this._intentStates.set(n.cacheKey,a)}if(!a.opListReadCapability){r=Object.create(null);r.operatorListChanged=function operatorListChanged(){if(a.operatorList.lastChunk){a.opListReadCapability.resolve(a.operatorList);a.renderTasks.delete(r)}};a.opListReadCapability=Promise.withResolvers();(a.renderTasks||=new Set).add(r);a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(n)}return a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:!0===t,disableNormalization:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>XfaText.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,i){const s=e.getReader(),n={items:[],styles:Object.create(null),lang:null};!function pump(){s.read().then((function({value:e,done:i}){if(i)t(n);else{n.lang??=e.lang;Object.assign(n.styles,e.styles);n.items.push(...e.items);pump()}}),i)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const i of e.renderTasks){t.push(i.completed);i.cancel()}}this.objs.clear();this.#vs=!1;this.#ys();return Promise.all(t)}cleanup(t=!1){this.#vs=!0;const e=this.#ws(!1);t&&e&&(this._stats&&=new StatTimer);return e}#ws(t=!1){this.#ys();if(!this.#vs||this.destroyed)return!1;if(t){this.#bs=setTimeout((()=>{this.#bs=null;this.#ws(!1)}),5e3);return!1}for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();this.#vs=!1;return!0}#ys(){if(this.#bs){clearTimeout(this.#bs);this.#bs=null}}_startRenderPage(t,e){const i=this._intentStates.get(e);if(i){this._stats?.timeEnd("Page Request");i.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let i=0,s=t.length;i{a.read().then((({value:t,done:e})=>{if(e)o.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,o);pump()}}),(t=>{o.streamReader=null;if(!this._transport.destroyed){if(o.operatorList){o.operatorList.lastChunk=!0;for(const t of o.renderTasks)t.operatorListChanged();this.#ws(!0)}if(o.displayReadyCapability)o.displayReadyCapability.reject(t);else{if(!o.opListReadCapability)throw t;o.opListReadCapability.reject(t)}}}))};pump()}_abortOperatorList({intentState:t,reason:e,force:i=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!i){if(t.renderTasks.size>0)return;if(e instanceof RenderingCancelledException){let i=100;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})}),i);return}}t.streamReader.cancel(new AbortException(e.message)).catch((()=>{}));t.streamReader=null;if(!this._transport.destroyed){for(const[e,i]of this._intentStates)if(i===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}class LoopbackPort{#As=new Map;#xs=Promise.resolve();postMessage(t,e){const i={data:structuredClone(t,e?{transfer:e}:null)};this.#xs.then((()=>{for(const[t]of this.#As)t.call(this,i)}))}addEventListener(t,e,i=null){let s=null;if(i?.signal instanceof AbortSignal){const{signal:n}=i;if(n.aborted){warn("LoopbackPort - cannot use an `aborted` signal.");return}const onAbort=()=>this.removeEventListener(t,e);s=()=>n.removeEventListener("abort",onAbort);n.addEventListener("abort",onAbort)}this.#As.set(e,s)}removeEventListener(t,e){const i=this.#As.get(e);i?.();this.#As.delete(e)}terminate(){for(const[,t]of this.#As)t?.();this.#As.clear()}}class PDFWorker{static#_s=0;static#Es=!1;static#Ss;static{if(i){this.#Es=!0;GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"}this._isSameOrigin=(t,e)=>{let i;try{i=new URL(t);if(!i.origin||"null"===i.origin)return!1}catch{return!1}const s=new URL(e,i);return i.origin===s.origin};this._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))}}constructor({name:t=null,port:e=null,verbosity:i=getVerbosityLevel()}={}){this.name=t;this.destroyed=!1;this.verbosity=i;this._readyCapability=Promise.withResolvers();this._port=null;this._webWorker=null;this._messageHandler=null;if(e){if(PDFWorker.#Ss?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(PDFWorker.#Ss||=new WeakMap).set(e,this);this._initializeFromPort(e)}else this._initialize()}get promise(){return this._readyCapability.promise}#Cs(){this._readyCapability.resolve();this._messageHandler.send("configure",{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t;this._messageHandler=new MessageHandler("main","worker",t);this._messageHandler.on("ready",(function(){}));this.#Cs()}_initialize(){if(PDFWorker.#Es||PDFWorker.#Ts){this._setupFakeWorker();return}let{workerSrc:t}=PDFWorker;try{PDFWorker._isSameOrigin(window.location.href,t)||(t=PDFWorker._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),i=new MessageHandler("main","worker",e),terminateEarly=()=>{s.abort();i.destroy();e.terminate();this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},s=new AbortController;e.addEventListener("error",(()=>{this._webWorker||terminateEarly()}),{signal:s.signal});i.on("test",(t=>{s.abort();if(!this.destroyed&&t){this._messageHandler=i;this._port=e;this._webWorker=e;this.#Cs()}else terminateEarly()}));i.on("ready",(t=>{s.abort();if(this.destroyed)terminateEarly();else try{sendTest()}catch{this._setupFakeWorker()}}));const sendTest=()=>{const t=new Uint8Array;i.send("test",t,[t.buffer])};sendTest();return}catch{info("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){if(!PDFWorker.#Es){warn("Setting up fake worker.");PDFWorker.#Es=!0}PDFWorker._setupFakeWorkerGlobal.then((t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this._port=e;const i="fake"+PDFWorker.#_s++,s=new MessageHandler(i+"_worker",i,e);t.setup(s,e);this._messageHandler=new MessageHandler(i,i+"_worker",e);this.#Cs()})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0;this._webWorker?.terminate();this._webWorker=null;PDFWorker.#Ss?.delete(this._port);this._port=null;this._messageHandler?.destroy();this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=this.#Ss?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new PDFWorker(t)}static get workerSrc(){if(GlobalWorkerOptions.workerSrc)return GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#Ts(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return shadow(this,"_setupFakeWorkerGlobal",(async()=>{if(this.#Ts)return this.#Ts;return(await import(this.workerSrc)).WorkerMessageHandler})())}}class WorkerTransport{#Ms=new Map;#Ps=new Map;#Ds=new Map;#ks=new Map;#Rs=null;constructor(t,e,i,s,n){this.messageHandler=t;this.loadingTask=e;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:s.ownerDocument,styleElement:s.styleElement});this.loadingParams=s.loadingParams;this._params=s;this.canvasFactory=n.canvasFactory;this.filterFactory=n.filterFactory;this.cMapReaderFactory=n.cMapReaderFactory;this.standardFontDataFactory=n.standardFontDataFactory;this.destroyed=!1;this.destroyCapability=null;this._networkStream=i;this._fullReader=null;this._lastProgress=null;this.downloadInfoCapability=Promise.withResolvers();this.setupMessageHandler()}#Is(t,e=null){const i=this.#Ms.get(t);if(i)return i;const s=this.messageHandler.sendWithPromise(t,e);this.#Ms.set(t,s);return s}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=g.ENABLE,i=null,s=!1,n=!1){let r=o,f=lt;switch(t){case"any":r=a;break;case"display":break;case"print":r=l;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const m=r&l&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case g.DISABLE:r+=d;break;case g.ENABLE:break;case g.ENABLE_FORMS:r+=h;break;case g.ENABLE_STORAGE:r+=c;f=m.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}s&&(r+=u);n&&(r+=p);const{ids:b,hash:v}=m.modifiedIds;return{renderingIntent:r,cacheKey:[r,f.hash,v].join("_"),annotationStorageSerializable:f,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#Rs?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Ps.values())t.push(e._destroy());this.#Ps.clear();this.#Ds.clear();this.#ks.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then((()=>{this.commonObjs.clear();this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy();TextLayer.cleanup();this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.destroyCapability.resolve()}),this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{assert(this._networkStream,"GetReader - no `IPDFStream` instance available.");this._fullReader=this._networkStream.getFullReader();this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}};e.onPull=()=>{this._fullReader.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{this._fullReader.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}));t.on("ReaderHeadersReady",(async t=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:s,contentLength:n}=this._fullReader;if(!i||!s){this._lastProgress&&e.onProgress?.(this._lastProgress);this._fullReader.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}}return{isStreamingSupported:i,isRangeSupported:s,contentLength:n}}));t.on("GetRangeReader",((t,e)=>{assert(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then((function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{i.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}else e.close()}));t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))}));t.on("DocException",(t=>{e._capability.reject(wrapReason(t))}));t.on("PasswordRequest",(t=>{this.#Rs=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#Rs.reject(t):this.#Rs.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#Rs.reject(t)}return this.#Rs.promise}));t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)}));t.on("StartRenderPage",(t=>{if(this.destroyed)return;this.#Ps.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}));t.on("commonobj",(([e,i,s])=>{if(this.destroyed)return null;if(this.commonObjs.has(e))return null;switch(i){case"Font":const{disableFontFace:n,fontExtraProperties:r,pdfBug:a}=this._params;if("error"in s){const t=s.error;warn(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}const o=a&&globalThis.FontInspector?.enabled?(t,e)=>globalThis.FontInspector.fontAdded(t,e):null,l=new FontFaceObject(s,{disableFontFace:n,fontExtraProperties:r,inspectFont:o});this.fontLoader.bind(l).catch((()=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!r&&l.data&&(l.data=null);this.commonObjs.resolve(e,l)}));break;case"CopyLocalImage":const{imageRef:h}=s;assert(h,"The imageRef must be defined.");for(const t of this.#Ps.values())for(const[,i]of t.objs)if(i?.ref===h){if(!i.dataLen)return null;this.commonObjs.resolve(e,structuredClone(i));return i.dataLen}break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(e,s);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}));t.on("obj",(([t,e,i,s])=>{if(this.destroyed)return;const n=this.#Ps.get(e);if(!n.objs.has(t))if(0!==n._intentStates.size)switch(i){case"Image":n.objs.resolve(t,s);s?.dataLen>1e7&&(n._maybeCleanupAfterRender=!0);break;case"Pattern":n.objs.resolve(t,s);break;default:throw new Error(`Got unknown object type ${i}`)}else s?.bitmap?.close()}));t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}));t.on("FetchBuiltInCMap",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(t)}));t.on("FetchStandardFontData",(async t=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(t)}))}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,i=this.#Ds.get(e);if(i)return i;const s=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&this.#ks.set(i.refStr,t);const s=new PDFPageProxy(e,i,this,this._params.pdfBug);this.#Ps.set(e,s);return s}));this.#Ds.set(e,s);return s}getPageIndex(t){return isRefProxy(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#Is("GetFieldObjects")}hasJSActions(){return this.#Is("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#Is("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#Is("GetOptionalContentConfig").then((e=>new OptionalContentConfig(e,t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#Ms.get(t);if(e)return e;const i=this.messageHandler.sendWithPromise(t,null).then((t=>({info:t[0],metadata:t[1]?new Metadata(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));this.#Ms.set(t,i);return i}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#Ps.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#Ms.clear();this.filterFactory.destroy(!0);TextLayer.cleanup()}}cachedPageNumber(t){if(!isRefProxy(t))return null;const e=0===t.gen?`${t.num}R`:`${t.num}R${t.gen}`;return this.#ks.get(e)??null}}const Nt=Symbol("INITIAL_DATA");class PDFObjects{#Fs=Object.create(null);#Ls(t){return this.#Fs[t]||={...Promise.withResolvers(),data:Nt}}get(t,e=null){if(e){const i=this.#Ls(t);i.promise.then((()=>e(i.data)));return null}const i=this.#Fs[t];if(!i||i.data===Nt)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return i.data}has(t){const e=this.#Fs[t];return!!e&&e.data!==Nt}delete(t){const e=this.#Fs[t];if(!e||e.data===Nt)return!1;delete this.#Fs[t];return!0}resolve(t,e=null){const i=this.#Ls(t);i.data=e;i.resolve()}clear(){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e?.bitmap?.close()}this.#Fs=Object.create(null)}*[Symbol.iterator](){for(const t in this.#Fs){const{data:e}=this.#Fs[t];e!==Nt&&(yield[t,e])}}}class RenderTask{#Os=null;constructor(t){this.#Os=t;this.onContinue=null}get promise(){return this.#Os.capability.promise}cancel(t=0){this.#Os.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#Os.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#Os;return t.form||t.canvas&&e?.size>0}}class InternalRenderTask{#Ns=null;static#Bs=new WeakSet;constructor({callback:t,params:e,objs:i,commonObjs:s,annotationCanvasMap:n,operatorList:r,pageIndex:a,canvasFactory:o,filterFactory:l,useRequestAnimationFrame:h=!1,pdfBug:c=!1,pageColors:d=null}){this.callback=t;this.params=e;this.objs=i;this.commonObjs=s;this.annotationCanvasMap=n;this.operatorListIdx=null;this.operatorList=r;this._pageIndex=a;this.canvasFactory=o;this.filterFactory=l;this._pdfBug=c;this.pageColors=d;this.running=!1;this.graphicsReadyCallback=null;this.graphicsReady=!1;this._useRequestAnimationFrame=!0===h&&"undefined"!=typeof window;this.cancelled=!1;this.capability=Promise.withResolvers();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#Bs.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#Bs.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{canvasContext:i,viewport:s,transform:n,background:r}=this.params;this.gfx=new CanvasGraphics(i,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors);this.gfx.beginDrawing({transform:n,viewport:s,transparency:t,background:r});this.operatorListIdx=0;this.graphicsReady=!0;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1;this.cancelled=!0;this.gfx?.endDrawing();if(this.#Ns){window.cancelAnimationFrame(this.#Ns);this.#Ns=null}InternalRenderTask.#Bs.delete(this._canvas);this.callback(t||new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(this.graphicsReady){this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||=this._continueBound}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#Ns=window.requestAnimationFrame((()=>{this.#Ns=null;this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();InternalRenderTask.#Bs.delete(this._canvas);this.callback()}}}}}const Bt="4.10.38",Ht="f9bea397f";__webpack_require__(670);function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}function scaleAndClamp(t){return Math.max(0,Math.min(255,255*t))}class ColorConverters{static CMYK_G([t,e,i,s]){return["G",1-Math.min(1,.3*t+.59*i+.11*e+s)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return[t=scaleAndClamp(t),t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,i]){return["G",.3*t+.59*e+.11*i]}static RGB_rgb(t){return t.map(scaleAndClamp)}static RGB_HTML(t){return`#${t.map(makeColorComp).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,i,s]){return["RGB",1-Math.min(1,t+s),1-Math.min(1,i+s),1-Math.min(1,e+s)]}static CMYK_rgb([t,e,i,s]){return[scaleAndClamp(1-Math.min(1,t+s)),scaleAndClamp(1-Math.min(1,i+s)),scaleAndClamp(1-Math.min(1,e+s))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,i]){const s=1-t,n=1-e,r=1-i;return["CMYK",s,n,r,Math.min(s,n,r)]}}class BaseSVGFactory{create(t,e,i=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const s=this._createSVG("svg:svg");s.setAttribute("version","1.1");if(!i){s.setAttribute("width",`${t}px`);s.setAttribute("height",`${e}px`)}s.setAttribute("preserveAspectRatio","none");s.setAttribute("viewBox",`0 0 ${t} ${e}`);return s}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){unreachable("Abstract method `_createSVG` called.")}}class DOMSVGFactory extends BaseSVGFactory{_createSVG(t){return document.createElementNS(nt,t)}}class XfaLayer{static setupStorage(t,e,i,s,n){const r=s.getValue(e,{value:null});switch(i.name){case"textarea":null!==r.value&&(t.textContent=r.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===i.attributes.type||"checkbox"===i.attributes.type){r.value===i.attributes.xfaOn?t.setAttribute("checked",!0):r.value===i.attributes.xfaOff&&t.removeAttribute("checked");if("print"===n)break;t.addEventListener("change",(t=>{s.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{null!==r.value&&t.setAttribute("value",r.value);if("print"===n)break;t.addEventListener("input",(t=>{s.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==r.value){t.setAttribute("value",r.value);for(const t of i.children)t.attributes.value===r.value?t.attributes.selected=!0:t.attributes.hasOwnProperty("selected")&&delete t.attributes.selected}t.addEventListener("input",(t=>{const i=t.target.options,n=-1===i.selectedIndex?"":i[i.selectedIndex].value;s.setValue(e,{value:n})}))}}static setAttributes({html:t,element:e,storage:i=null,intent:s,linkService:n}){const{attributes:r}=e,a=t instanceof HTMLAnchorElement;"radio"===r.type&&(r.name=`${r.name}-${s}`);for(const[e,i]of Object.entries(r))if(null!=i)switch(e){case"class":i.length&&t.setAttribute(e,i.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",i);break;case"style":Object.assign(t.style,i);break;case"textContent":t.textContent=i;break;default:(!a||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,i)}a&&n.addLinkAttributes(t,r.href,r.newWindow);i&&r.dataId&&this.setupStorage(t,r.dataId,e,i)}static render(t){const e=t.annotationStorage,i=t.linkService,s=t.xfaHtml,n=t.intent||"display",r=document.createElement(s.name);s.attributes&&this.setAttributes({html:r,element:s,intent:n,linkService:i});const a="richText"!==n,o=t.div;o.append(r);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;o.style.transform=e}a&&o.setAttribute("class","xfaLayer xfaFont");const l=[];if(0===s.children.length){if(s.value){const t=document.createTextNode(s.value);r.append(t);a&&XfaText.shouldBuildText(s.name)&&l.push(t)}return{textDivs:l}}const h=[[s,-1,r]];for(;h.length>0;){const[t,s,r]=h.at(-1);if(s+1===t.children.length){h.pop();continue}const o=t.children[++h.at(-1)[1]];if(null===o)continue;const{name:c}=o;if("#text"===c){const t=document.createTextNode(o.value);l.push(t);r.append(t);continue}const d=o?.attributes?.xmlns?document.createElementNS(o.attributes.xmlns,c):document.createElement(c);r.append(d);o.attributes&&this.setAttributes({html:d,element:o,storage:e,intent:n,linkService:i});if(o.children?.length>0)h.push([o,-1,d]);else if(o.value){const t=document.createTextNode(o.value);a&&XfaText.shouldBuildText(c)&&l.push(t);d.append(t)}}for(const t of o.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:l}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=!1}}const Ut=1e3,zt=new WeakSet;function getRectDims(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case C:return new LinkAnnotationElement(t);case S:return new TextAnnotationElement(t);case G:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t);case"Sig":return new SignatureWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case z:return new PopupAnnotationElement(t);case T:return new FreeTextAnnotationElement(t);case M:return new LineAnnotationElement(t);case P:return new SquareAnnotationElement(t);case D:return new CircleAnnotationElement(t);case R:return new PolylineAnnotationElement(t);case H:return new CaretAnnotationElement(t);case U:return new InkAnnotationElement(t);case k:return new PolygonAnnotationElement(t);case I:return new HighlightAnnotationElement(t);case L:return new UnderlineAnnotationElement(t);case O:return new SquigglyAnnotationElement(t);case N:return new StrikeOutAnnotationElement(t);case B:return new StampAnnotationElement(t);case j:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{#Hs=null;#Us=!1;#zs=null;constructor(t,{isRenderable:e=!1,ignoreBorder:i=!1,createQuadrilaterals:s=!1}={}){this.isRenderable=e;this.data=t.data;this.layer=t.layer;this.linkService=t.linkService;this.downloadManager=t.downloadManager;this.imageResourcesPath=t.imageResourcesPath;this.renderForms=t.renderForms;this.svgFactory=t.svgFactory;this.annotationStorage=t.annotationStorage;this.enableScripting=t.enableScripting;this.hasJSActions=t.hasJSActions;this._fieldObjects=t.fieldObjects;this.parent=t.parent;e&&(this.container=this._createContainer(i));s&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:i}){return!!(t?.str||e?.str||i?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return AnnotationElement._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#Hs||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#js(e);this.#zs?.popup.updateEdited(t)}resetEdited(){if(this.#Hs){this.#js(this.#Hs.rect);this.#zs?.popup.resetEdited();this.#Hs=null}}#js(t){const{container:{style:e},data:{rect:i,rotation:s},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:a,pageY:o}}}}=this;i?.splice(0,4,...t);const{width:l,height:h}=getRectDims(t);e.left=100*(t[0]-a)/n+"%";e.top=100*(r-t[3]+o)/r+"%";if(0===s){e.width=100*l/n+"%";e.height=100*h/r+"%"}else this.setRotation(s)}_createContainer(t){const{data:e,parent:{page:i,viewport:s}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id);this instanceof WidgetAnnotationElement||(n.tabIndex=Ut);const{style:r}=n;r.zIndex=this.parent.zIndex++;e.alternativeText&&(n.title=e.alternativeText);e.noRotate&&n.classList.add("norotate");if(!e.rect||this instanceof PopupAnnotationElement){const{rotation:t}=e;e.hasOwnCanvas||0===t||this.setRotation(t,n);return n}const{width:a,height:o}=getRectDims(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,i=e.borderStyle.verticalCornerRadius;if(t>0||i>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${i}px * var(--scale-factor))`;r.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${a}px * var(--scale-factor)) / calc(${o}px * var(--scale-factor))`;r.borderRadius=t}switch(e.borderStyle.style){case V:r.borderStyle="solid";break;case $:r.borderStyle="dashed";break;case W:warn("Unimplemented border style: beveled");break;case q:warn("Unimplemented border style: inset");break;case X:r.borderBottomStyle="solid"}const s=e.borderColor||null;if(s){this.#Us=!0;r.borderColor=Util.makeHexColor(0|s[0],0|s[1],0|s[2])}else r.borderWidth=0}const l=Util.normalizeRect([e.rect[0],i.view[3]-e.rect[1]+i.view[1],e.rect[2],i.view[3]-e.rect[3]+i.view[1]]),{pageWidth:h,pageHeight:c,pageX:d,pageY:u}=s.rawDims;r.left=100*(l[0]-d)/h+"%";r.top=100*(l[1]-u)/c+"%";const{rotation:p}=e;if(e.hasOwnCanvas||0===p){r.width=100*a/h+"%";r.height=100*o/c+"%"}else this.setRotation(p,n);return n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:i,pageHeight:s}=this.parent.viewport.rawDims,{width:n,height:r}=getRectDims(this.data.rect);let a,o;if(t%180==0){a=100*n/i;o=100*r/s}else{a=100*r/i;o=100*n/s}e.style.width=`${a}%`;e.style.height=`${o}%`;e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,i)=>{const s=i.detail[t],n=s[0],r=s.slice(1);i.target.style[e]=ColorConverters[`${n}_HTML`](r);this.annotationStorage.setValue(this.data.id,{[e]:ColorConverters[`${n}_rgb`](r)})};return shadow(this,"_commonActions",{display:t=>{const{display:e}=t.detail,i=e%2==1;this.container.style.visibility=i?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:1===e||2===e})},print:t=>{this.annotationStorage.setValue(this.data.id,{noPrint:!t.detail.print})},hidden:t=>{const{hidden:e}=t.detail;this.container.style.visibility=e?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{noPrint:e,noView:e})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.target.disabled=t.detail.readonly},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e);this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const i=this._commonActions;for(const s of Object.keys(e.detail)){const n=t[s]||i[s];n?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const i=this._commonActions;for(const[s,n]of Object.entries(e)){const r=i[s];if(r){r({detail:{[s]:n},target:t});delete e[s]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,i,s,n]=this.data.rect.map((t=>Math.fround(t)));if(8===t.length){const[r,a,o,l]=t.subarray(2,6);if(s===r&&n===a&&e===o&&i===l)return}const{style:r}=this.container;let a;if(this.#Us){const{borderColor:t,borderWidth:e}=r;r.borderWidth=0;a=["url('data:image/svg+xml;utf8,",'',``];this.container.classList.add("hasBorder")}const o=s-e,l=n-i,{svgFactory:h}=this,c=h.createElement("svg");c.classList.add("quadrilateralsContainer");c.setAttribute("width",0);c.setAttribute("height",0);const d=h.createElement("defs");c.append(d);const u=h.createElement("clipPath"),p=`clippath_${this.data.id}`;u.setAttribute("id",p);u.setAttribute("clipPathUnits","objectBoundingBox");d.append(u);for(let i=2,s=t.length;i`)}if(this.#Us){a.push("')");r.backgroundImage=a.join("")}this.container.append(c);this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=this.#zs=new PopupAnnotationElement({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){unreachable("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const i=[];if(this._fieldObjects){const s=this._fieldObjects[t];if(s)for(const{page:t,id:n,exportValues:r}of s){if(-1===t)continue;if(n===e)continue;const s="string"==typeof r?r:null,a=document.querySelector(`[data-element-id="${n}"]`);!a||zt.has(a)?i.push({id:n,exportValue:s,domElement:a}):warn(`_getElementsByName - element not allowed: ${n}`)}return i}for(const s of document.getElementsByName(t)){const{exportValue:t}=s,n=s.getAttribute("data-element-id");n!==e&&(zt.has(s)&&i.push({id:n,exportValue:t,domElement:s}))}return i}show(){this.container&&(this.container.hidden=!1);this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0);this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})}))}}class LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0});this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,i=document.createElement("a");i.setAttribute("data-element-id",t.id);let s=!1;if(t.url){e.addLinkAttributes(i,t.url,t.newWindow);s=!0}else if(t.action){this._bindNamedAction(i,t.action);s=!0}else if(t.attachment){this.#Gs(i,t.attachment,t.attachmentDest);s=!0}else if(t.setOCGState){this.#Vs(i,t.setOCGState);s=!0}else if(t.dest){this._bindLink(i,t.dest);s=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(i,t);s=!0}if(t.resetForm){this._bindResetFormAction(i,t.resetForm);s=!0}else if(this.isTooltipOnly&&!s){this._bindLink(i,"");s=!0}}this.container.classList.add("linkAnnotation");s&&this.container.append(i);return this.container}#$s(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#$s()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};this.#$s()}#Gs(t,e,i=null){t.href=this.linkService.getAnchorUrl("");e.description&&(t.title=e.description);t.onclick=()=>{this.downloadManager?.openOrDownloadData(e.content,e.filename,i);return!1};this.#$s()}#Vs(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};this.#$s()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const s of Object.keys(e.actions)){const n=i.get(s);n&&(t[n]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:s}});return!1})}t.onclick||(t.onclick=()=>!1);this.#$s()}_bindResetFormAction(t,e){const i=t.onclick;i||(t.href=this.linkService.getAnchorUrl(""));this.#$s();if(this._fieldObjects)t.onclick=()=>{i?.();const{fields:t,refs:s,include:n}=e,r=[];if(0!==t.length||0!==s.length){const e=new Set(s);for(const i of t){const t=this._fieldObjects[i]||[];for(const{id:i}of t)e.add(i)}for(const t of Object.values(this._fieldObjects))for(const i of t)e.has(i.id)===n&&r.push(i)}else for(const t of Object.values(this._fieldObjects))r.push(...t);const a=this.annotationStorage,o=[];for(const t of r){const{id:e}=t;o.push(e);switch(t.type){case"text":{const i=t.defaultValue||"";a.setValue(e,{value:i});break}case"checkbox":case"radiobutton":{const i=t.defaultValue===t.exportValues;a.setValue(e,{value:i});break}case"combobox":case"listbox":{const i=t.defaultValue||"";a.setValue(e,{value:i});break}default:continue}const i=document.querySelector(`[data-element-id="${e}"]`);i&&(zt.has(i)?i.dispatchEvent(new Event("resetform")):warn(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:o,name:"ResetForm"}});return!1};else{warn('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');i||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.setAttribute("data-l10n-id","pdfjs-text-annotation-type");t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name}));!this.data.popupRef&&this.hasPopupData&&this._createPopup();this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){return this.container}showElementAndHideCanvas(t){if(this.data.hasOwnCanvas){"CANVAS"===t.previousSibling?.nodeName&&(t.previousSibling.hidden=!0);t.hidden=!1}}_getKeyModifier(t){return util_FeatureTest.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,i,s,n){i.includes("mouse")?t.addEventListener(i,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(i,(t=>{if("blur"===i){if(!e.focused||!t.relatedTarget)return;e.focused=!1}else if("focus"===i){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,i,s){for(const[n,r]of i)if("Action"===r||this.data.actions?.[r]){"Focus"!==r&&"Blur"!==r||(e||={focused:!1});this._setEventListener(t,e,n,r,s);"Focus"!==r||this.data.actions?.Blur?"Blur"!==r||this.data.actions?.Focus||this._setEventListener(t,e,"focus","Focus",null):this._setEventListener(t,e,"blur","Blur",null)}}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:i}=this.data.defaultAppearanceData,s=this.data.defaultAppearanceData.fontSize||9,n=t.style;let a;const roundToOneDecimal=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(r*s))||1);a=Math.min(s,roundToOneDecimal(e/r))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(s,roundToOneDecimal(t/r))}n.fontSize=`calc(${a}px * var(--scale-factor))`;n.color=Util.makeHexColor(i[0],i[1],i[2]);null!==this.data.textAlignment&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,i,s){const n=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id)){r.domElement&&(r.domElement[e]=i);n.setValue(r.id,{[s]:i})}}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let i=null;if(this.renderForms){const s=t.getValue(e,{value:this.data.fieldValue});let n=s.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&n.length>r&&(n=n.slice(0,r));let a=s.formattedValue||this.data.textContent?.join("\n")||null;a&&this.data.comb&&(a=a.replaceAll(/\s+/g,""));const o={userValue:n,formattedValue:a,lastCommittedValue:null,commitKey:1,focused:!1};if(this.data.multiLine){i=document.createElement("textarea");i.textContent=a??n;this.data.doNotScroll&&(i.style.overflowY="hidden")}else{i=document.createElement("input");i.type="text";i.setAttribute("value",a??n);this.data.doNotScroll&&(i.style.overflowX="hidden")}this.data.hasOwnCanvas&&(i.hidden=!0);zt.add(i);i.setAttribute("data-element-id",e);i.disabled=this.data.readOnly;i.name=this.data.fieldName;i.tabIndex=Ut;this._setRequired(i,this.data.required);r&&(i.maxLength=r);i.addEventListener("input",(s=>{t.setValue(e,{value:s.target.value});this.setPropertyOnSiblings(i,"value",s.target.value,"value");o.formattedValue=null}));i.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";i.value=o.userValue=e;o.formattedValue=null}));let blurListener=t=>{const{formattedValue:e}=o;null!=e&&(t.target.value=e);t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){i.addEventListener("focus",(t=>{if(o.focused)return;const{target:e}=t;o.userValue&&(e.value=o.userValue);o.lastCommittedValue=e.value;o.commitKey=1;this.data.actions?.Focus||(o.focused=!0)}));i.addEventListener("updatefromsandbox",(i=>{this.showElementAndHideCanvas(i.target);const s={value(i){o.userValue=i.detail.value??"";t.setValue(e,{value:o.userValue.toString()});i.target.value=o.userValue},formattedValue(i){const{formattedValue:s}=i.detail;o.formattedValue=s;null!=s&&i.target!==document.activeElement&&(i.target.value=s);t.setValue(e,{formattedValue:s})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:i=>{const{charLimit:s}=i.detail,{target:n}=i;if(0===s){n.removeAttribute("maxLength");return}n.setAttribute("maxLength",s);let r=o.userValue;if(r&&!(r.length<=s)){r=r.slice(0,s);n.value=o.userValue=r;t.setValue(e,{value:r});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,willCommit:!0,commitKey:1,selStart:n.selectionStart,selEnd:n.selectionEnd}})}}};this._dispatchEventFromSandbox(s,i)}));i.addEventListener("keydown",(t=>{o.commitKey=1;let i=-1;"Escape"===t.key?i=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(o.commitKey=3):i=2;if(-1===i)return;const{value:s}=t.target;if(o.lastCommittedValue!==s){o.lastCommittedValue=s;o.userValue=s;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:i,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}}));const s=blurListener;blurListener=null;i.addEventListener("blur",(t=>{if(!o.focused||!t.relatedTarget)return;this.data.actions?.Blur||(o.focused=!1);const{value:i}=t.target;o.userValue=i;o.lastCommittedValue!==i&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,willCommit:!0,commitKey:o.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});s(t)}));this.data.actions?.Keystroke&&i.addEventListener("beforeinput",(t=>{o.lastCommittedValue=null;const{data:i,target:s}=t,{value:n,selectionStart:r,selectionEnd:a}=s;let l=r,h=a;switch(t.inputType){case"deleteWordBackward":{const t=n.substring(0,r).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=n.substring(r).match(/^[^\w]*\w*/);t&&(h+=t[0].length);break}case"deleteContentBackward":r===a&&(l-=1);break;case"deleteContentForward":r===a&&(h+=1)}t.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,change:i||"",willCommit:!1,selStart:l,selEnd:h}})}));this._setEventListeners(i,o,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}blurListener&&i.addEventListener("blur",blurListener);if(this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/r;i.classList.add("comb");i.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else{i=document.createElement("div");i.textContent=this.data.fieldValue;i.style.verticalAlign="middle";i.style.display="table-cell";this.data.hasOwnCanvas&&(i.hidden=!0)}this._setTextStyle(i);this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class SignatureWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.exportValue===e.fieldValue}).value;if("string"==typeof s){s="Off"!==s;t.setValue(i,{value:s})}this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");zt.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="checkbox";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.setAttribute("exportValue",e.exportValue);n.tabIndex=Ut;n.addEventListener("change",(s=>{const{name:n,checked:r}=s.target;for(const s of this._getElementsByName(n,i)){const i=r&&s.exportValue===e.exportValue;s.domElement&&(s.domElement.checked=i);t.setValue(s.id,{value:i})}t.setValue(i,{value:r})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue||"Off";t.target.checked=i===e.exportValue}));if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",(e=>{const s={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(i,{value:e.target.checked})}};this._dispatchEventFromSandbox(s,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,i=e.id;let s=t.getValue(i,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof s){s=s!==e.buttonValue;t.setValue(i,{value:s})}if(s)for(const s of this._getElementsByName(e.fieldName,i))t.setValue(s.id,{value:!1});const n=document.createElement("input");zt.add(n);n.setAttribute("data-element-id",i);n.disabled=e.readOnly;this._setRequired(n,this.data.required);n.type="radio";n.name=e.fieldName;s&&n.setAttribute("checked",!0);n.tabIndex=Ut;n.addEventListener("change",(e=>{const{name:s,checked:n}=e.target;for(const e of this._getElementsByName(s,i))t.setValue(e.id,{value:!1});t.setValue(i,{value:n})}));n.addEventListener("resetform",(t=>{const i=e.defaultFieldValue;t.target.checked=null!=i&&i===e.buttonValue}));if(this.enableScripting&&this.hasJSActions){const s=e.buttonValue;n.addEventListener("updatefromsandbox",(e=>{const n={value:e=>{const n=s===e.detail.value;for(const s of this._getElementsByName(e.target.name)){const e=n&&s.id===i;s.domElement&&(s.domElement.checked=e);t.setValue(s.id,{value:e})}}};this._dispatchEventFromSandbox(n,e)}));this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,i=t.getValue(e,{value:this.data.fieldValue}),s=document.createElement("select");zt.add(s);s.setAttribute("data-element-id",e);s.disabled=this.data.readOnly;this._setRequired(s,this.data.required);s.name=this.data.fieldName;s.tabIndex=Ut;let n=this.data.combo&&this.data.options.length>0;if(!this.data.combo){s.size=this.data.options.length;this.data.multiSelect&&(s.multiple=!0)}s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of s.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue;e.value=t.exportValue;if(i.value.includes(t.exportValue)){e.setAttribute("selected",!0);n=!1}s.append(e)}let r=null;if(n){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",!0);t.setAttribute("selected",!0);s.prepend(t);r=()=>{t.remove();s.removeEventListener("input",r);r=null};s.addEventListener("input",r)}const getValue=t=>{const e=t?"value":"textContent",{options:i,multiple:n}=s;return n?Array.prototype.filter.call(i,(t=>t.selected)).map((t=>t[e])):-1===i.selectedIndex?null:i[i.selectedIndex][e]};let a=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};if(this.enableScripting&&this.hasJSActions){s.addEventListener("updatefromsandbox",(i=>{const n={value(i){r?.();const n=i.detail.value,o=new Set(Array.isArray(n)?n:[n]);for(const t of s.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});a=getValue(!1)},multipleSelection(t){s.multiple=!0},remove(i){const n=s.options,r=i.detail.remove;n[r].selected=!1;s.remove(r);if(n.length>0){-1===Array.prototype.findIndex.call(n,(t=>t.selected))&&(n[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},clear(i){for(;0!==s.length;)s.remove(0);t.setValue(e,{value:null,items:[]});a=getValue(!1)},insert(i){const{index:n,displayValue:r,exportValue:o}=i.detail.insert,l=s.children[n],h=document.createElement("option");h.textContent=r;h.value=o;l?l.before(h):s.append(h);t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},items(i){const{items:n}=i.detail;for(;0!==s.length;)s.remove(0);for(const t of n){const{displayValue:e,exportValue:i}=t,n=document.createElement("option");n.textContent=e;n.value=i;s.append(n)}s.options.length>0&&(s.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(i)});a=getValue(!1)},indices(i){const s=new Set(i.detail.indices);for(const t of i.target.options)t.selected=s.has(t.index);t.setValue(e,{value:getValue(!0)});a=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(n,i)}));s.addEventListener("input",(i=>{const s=getValue(!0),n=getValue(!1);t.setValue(e,{value:s});i.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,change:n,changeEx:s,willCommit:!1,commitKey:1,keyDown:!1}})}));this._setEventListeners(s,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],(t=>t.target.value))}else s.addEventListener("input",(function(i){t.setValue(e,{value:getValue(!0)})}));this.data.combo&&this._setTextStyle(s);this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class PopupAnnotationElement extends AnnotationElement{constructor(t){const{data:e,elements:i}=t;super(t,{isRenderable:AnnotationElement._hasPopupData(e)});this.elements=i;this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new PopupElement({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const i of this.elements){i.popup=t;i.container.ariaHasPopup="dialog";e.push(i.data.id);i.addHighlightArea()}this.container.setAttribute("aria-controls",e.map((t=>`${st}${t}`)).join(","));return this.container}}class PopupElement{#Ws=this.#qs.bind(this);#Xs=this.#Ys.bind(this);#Ks=this.#Qs.bind(this);#Js=this.#Zs.bind(this);#tn=null;#pt=null;#en=null;#in=null;#sn=null;#nn=null;#rn=null;#an=!1;#on=null;#C=null;#ln=null;#hn=null;#cn=null;#Hs=null;#dn=!1;constructor({container:t,color:e,elements:i,titleObj:s,modificationDate:n,contentsObj:r,richText:a,parent:o,rect:l,parentRect:h,open:c}){this.#pt=t;this.#cn=s;this.#en=r;this.#hn=a;this.#nn=o;this.#tn=e;this.#ln=l;this.#rn=h;this.#sn=i;this.#in=PDFDateString.toDateObject(n);this.trigger=i.flatMap((t=>t.getElementsToTriggerPopup()));for(const t of this.trigger){t.addEventListener("click",this.#Js);t.addEventListener("mouseenter",this.#Ks);t.addEventListener("mouseleave",this.#Xs);t.classList.add("popupTriggerArea")}for(const t of i)t.container?.addEventListener("keydown",this.#Ws);this.#pt.hidden=!0;c&&this.#Zs()}render(){if(this.#on)return;const t=this.#on=document.createElement("div");t.className="popup";if(this.#tn){const e=t.style.outlineColor=Util.makeHexColor(...this.#tn);if(CSS.supports("background-color","color-mix(in srgb, red 30%, white)"))t.style.backgroundColor=`color-mix(in srgb, ${e} 30%, white)`;else{const e=.7;t.style.backgroundColor=Util.makeHexColor(...this.#tn.map((t=>Math.floor(e*(255-t)+t))))}}const e=document.createElement("span");e.className="header";const i=document.createElement("h1");e.append(i);({dir:i.dir,str:i.textContent}=this.#cn);t.append(e);if(this.#in){const t=document.createElement("span");t.classList.add("popupDate");t.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string");t.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#in.valueOf()}));e.append(t)}const s=this.#un;if(s){XfaLayer.render({xfaHtml:s,intent:"richText",div:t});t.lastChild.classList.add("richText","popupContent")}else{const e=this._formatContents(this.#en);t.append(e)}this.#pt.append(t)}get#un(){const t=this.#hn,e=this.#en;return!t?.str||e?.str&&e.str!==t.str?null:this.#hn.html||null}get#pn(){return this.#un?.attributes?.style?.fontSize||0}get#gn(){return this.#un?.attributes?.style?.color||null}#fn(t){const e=[],i={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},s={style:{color:this.#gn,fontSize:this.#pn?`calc(${this.#pn}px * var(--scale-factor))`:""}};for(const i of t.split("\n"))e.push({name:"span",value:i,attributes:s});return i}_formatContents({str:t,dir:e}){const i=document.createElement("p");i.classList.add("popupContent");i.dir=e;const s=t.split(/(?:\r\n?|\n)/);for(let t=0,e=s.length;t=0&&n.setAttribute("stroke-width",e||1);if(i)for(let t=0,e=this.#xn.length;t{"Enter"===t.key&&(s?t.metaKey:t.ctrlKey)&&this.#Sn()}));!e.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea");t.append(i);return t}getElementsToTriggerPopup(){return this.#En}addHighlightArea(){this.container.classList.add("highlightArea")}#Sn(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class AnnotationLayer{#Cn=null;#Tn=null;#Mn=new Map;#Pn=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:i,annotationEditorUIManager:s,page:n,viewport:r,structTreeLayer:a}){this.div=t;this.#Cn=e;this.#Tn=i;this.#Pn=a||null;this.page=n;this.viewport=r;this.zIndex=0;this._annotationEditorUIManager=s}hasEditableAnnotations(){return this.#Mn.size>0}async#Dn(t,e){const i=t.firstChild||t,s=i.id=`${st}${e}`,n=await(this.#Pn?.getAriaAttributes(s));if(n)for(const[t,e]of n)i.setAttribute(t,e);this.div.append(t);this.#Cn?.moveElementInDOM(this.div,t,i,!1)}async render(t){const{annotations:e}=t,i=this.div;setLayerDimensions(i,this.viewport);const s=new Map,n={data:null,layer:i,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:!1!==t.renderForms,svgFactory:new DOMSVGFactory,annotationStorage:t.annotationStorage||new AnnotationStorage,enableScripting:!0===t.enableScripting,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const t of e){if(t.noHTML)continue;const e=t.annotationType===z;if(e){const e=s.get(t.id);if(!e)continue;n.elements=e}else{const{width:e,height:i}=getRectDims(t.rect);if(e<=0||i<=0)continue}n.data=t;const i=AnnotationElementFactory.create(n);if(!i.isRenderable)continue;if(!e&&t.popupRef){const e=s.get(t.popupRef);e?e.push(i):s.set(t.popupRef,[i])}const r=i.render();t.hidden&&(r.style.visibility="hidden");await this.#Dn(r,t.id);if(i._isEditable){this.#Mn.set(i.data.id,i);this._annotationEditorUIManager?.renderAnnotationElement(i)}}this.#kn()}update({viewport:t}){const e=this.div;this.viewport=t;setLayerDimensions(e,{rotation:t.rotation});this.#kn();e.hidden=!1}#kn(){if(!this.#Tn)return;const t=this.div;for(const[e,i]of this.#Tn){const s=t.querySelector(`[data-annotation-id="${e}"]`);if(!s)continue;i.className="annotationContent";const{firstChild:n}=s;n?"CANVAS"===n.nodeName?n.replaceWith(i):n.classList.contains("annotationContent")?n.after(i):n.before(i):s.append(i)}this.#Tn.clear()}getEditableAnnotations(){return Array.from(this.#Mn.values())}getEditableAnnotation(t){return this.#Mn.get(t)}}const jt=/\r\n?|\n/g;class FreeTextEditor extends AnnotationEditor{#tn;#Rn="";#In=`${this.id}-editor`;#Fn=null;#pn;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=FreeTextEditor.prototype,arrowChecker=t=>t.isEmpty(),e=AnnotationEditorUIManager.TRANSLATE_SMALL,i=AnnotationEditorUIManager.TRANSLATE_BIG;return shadow(this,"_keyboardManager",new KeyboardManager([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-e,0],checker:arrowChecker}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:arrowChecker}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[e,0],checker:arrowChecker}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:arrowChecker}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-e],checker:arrowChecker}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:arrowChecker}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,e],checker:arrowChecker}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:arrowChecker}]]))}static _type="freetext";static _editorType=f.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"});this.#tn=t.color||FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor;this.#pn=t.fontSize||FreeTextEditor._defaultFontSize}static initialize(t,e){AnnotationEditor.initialize(t,e);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case m.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case m.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case m.FREETEXT_SIZE:this.#Ln(e);break;case m.FREETEXT_COLOR:this.#On(e)}}static get defaultPropertiesToUpdate(){return[[m.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[m.FREETEXT_COLOR,FreeTextEditor._defaultColor||AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[m.FREETEXT_SIZE,this.#pn],[m.FREETEXT_COLOR,this.#tn]]}#Ln(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`;this.translate(0,-(t-this.#pn)*this.parentScale);this.#pn=t;this.#Nn()},e=this.#pn;this.addCommands({cmd:setFontsize.bind(this,t),undo:setFontsize.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#On(t){const setColor=t=>{this.#tn=this.editorDiv.style.color=t},e=this.#tn;this.addCommands({cmd:setColor.bind(this,t),undo:setColor.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#pn)*t]}rebuild(){if(this.parent){super.rebuild();null!==this.div&&(this.isAttachedToDOM||this.parent.add(this))}}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1);this.parent.updateToolbar(f.FREETEXT);super.enableEditMode();this.overlayDiv.classList.remove("enabled");this.editorDiv.contentEditable=!0;this._isDraggable=!1;this.div.removeAttribute("aria-activedescendant");this.#Fn=new AbortController;const t=this._uiManager.combinedSignal(this.#Fn);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t});this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t});this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t});this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t});this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){if(this.isInEditMode()){this.parent.setEditingState(!0);super.disableEditMode();this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#In);this._isDraggable=!0;this.#Fn?.abort();this.#Fn=null;this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freetextEditing")}}focusin(t){if(this._focusEventsAllowed){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}}onceAdded(t){if(!this.width){this.enableEditMode();t&&this.editorDiv.focus();this._initialOptions?.isCentered&&this.center();this._initialOptions=null}}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1;if(this.parent){this.parent.setEditingState(!0);this.parent.div.classList.add("freetextEditing")}super.remove()}#Bn(){const t=[];this.editorDiv.normalize();let e=null;for(const i of this.editorDiv.childNodes)if(e?.nodeType!==Node.TEXT_NODE||"BR"!==i.nodeName){t.push(FreeTextEditor.#Hn(i));e=i}return t.join("\n")}#Nn(){const[t,e]=this.parentDimensions;let i;if(this.isAttachedToDOM)i=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,s=e.style.display,n=e.classList.contains("hidden");e.classList.remove("hidden");e.style.display="hidden";t.div.append(this.div);i=e.getBoundingClientRect();e.remove();e.style.display=s;e.classList.toggle("hidden",n)}if(this.rotation%180==this.parentRotation%180){this.width=i.width/t;this.height=i.height/e}else{this.width=i.height/t;this.height=i.width/e}this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit();this.disableEditMode();const t=this.#Rn,e=this.#Rn=this.#Bn().trimEnd();if(t===e)return;const setText=t=>{this.#Rn=t;if(t){this.#Un();this._uiManager.rebuild(this);this.#Nn()}else this.remove()};this.addCommands({cmd:()=>{setText(e)},undo:()=>{setText(t)},mustExec:!1});this.#Nn()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode();this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enterInEditMode();t.preventDefault()}}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment");this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox");this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#In);this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2");this.editorDiv.setAttribute("data-l10n-attrs","default-content");this.enableEditing();this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);bindEvents(this,this.div,["dblclick","keydown"]);if(this.width){const[i,s]=this.parentDimensions;if(this.annotationElementId){const{position:n}=this._initialData;let[r,a]=this.getInitialTranslation();[r,a]=this.pageTranslationToScreen(r,a);const[o,l]=this.pageDimensions,[h,c]=this.pageTranslation;let d,u;switch(this.rotation){case 0:d=t+(n[0]-h)/o;u=e+this.height-(n[1]-c)/l;break;case 90:d=t+(n[0]-h)/o;u=e-(n[1]-c)/l;[r,a]=[a,-r];break;case 180:d=t-this.width+(n[0]-h)/o;u=e-(n[1]-c)/l;[r,a]=[-r,-a];break;case 270:d=t+(n[0]-h-this.height*l)/o;u=e+(n[1]-c-this.width*o)/l;[r,a]=[-a,r]}this.setAt(d*i,u*s,r,a)}else this.setAt(t*i,e*s,this.width*i,this.height*s);this.#Un();this._isDraggable=!0;this.editorDiv.contentEditable=!1}else{this._isDraggable=!1;this.editorDiv.contentEditable=!0}return this.div}static#Hn(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(jt,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:i}=e;if(1===i.length&&"text/plain"===i[0])return;t.preventDefault();const s=FreeTextEditor.#zn(e.getData("text")||"").replaceAll(jt,"\n");if(!s)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize();n.deleteFromDocument();const r=n.getRangeAt(0);if(!s.includes("\n")){r.insertNode(document.createTextNode(s));this.editorDiv.normalize();n.collapseToStart();return}const{startContainer:a,startOffset:o}=r,l=[],h=[];if(a.nodeType===Node.TEXT_NODE){const t=a.parentElement;h.push(a.nodeValue.slice(o).replaceAll(jt,""));if(t!==this.editorDiv){let e=l;for(const i of this.editorDiv.childNodes)i!==t?e.push(FreeTextEditor.#Hn(i)):e=h}l.push(a.nodeValue.slice(0,o).replaceAll(jt,""))}else if(a===this.editorDiv){let t=l,e=0;for(const i of this.editorDiv.childNodes){e++===o&&(t=h);t.push(FreeTextEditor.#Hn(i))}}this.#Rn=`${l.join("\n")}${s}${h.join("\n")}`;this.#Un();const c=new Range;let d=l.reduce(((t,e)=>t+e.length),0);for(const{firstChild:t}of this.editorDiv.childNodes)if(t.nodeType===Node.TEXT_NODE){const e=t.nodeValue.length;if(d<=e){c.setStart(t,d);c.setEnd(t,d);break}d-=e}n.removeAllRanges();n.addRange(c)}#Un(){this.editorDiv.replaceChildren();if(this.#Rn)for(const t of this.#Rn.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}}#jn(){return this.#Rn.replaceAll(" "," ")}static#zn(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,i){let s=null;if(t instanceof FreeTextAnnotationElement){const{data:{defaultAppearanceData:{fontSize:e,fontColor:i},rect:n,rotation:r,id:a,popupRef:o},textContent:l,textPosition:h,parent:{page:{pageNumber:c}}}=t;if(!l||0===l.length)return null;s=t={annotationType:f.FREETEXT,color:Array.from(i),fontSize:e,value:l.join("\n"),position:h,pageIndex:c-1,rect:n.slice(0),rotation:r,id:a,deleted:!1,popupRef:o}}const n=await super.deserialize(t,e,i);n.#pn=t.fontSize;n.#tn=Util.makeHexColor(...t.color);n.#Rn=FreeTextEditor.#zn(t.value);n.annotationElementId=t.id||null;n._initialData=s;return n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=FreeTextEditor._internalPadding*this.parentScale,i=this.getRect(e,e),s=AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#tn),n={annotationType:f.FREETEXT,color:s,fontSize:this.#pn,value:this.#jn(),pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};if(t)return n;if(this.annotationElementId&&!this.#Gn(n))return null;n.id=this.annotationElementId;return n}#Gn(t){const{value:e,fontSize:i,color:s,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==i||t.color.some(((t,e)=>t!==s[e]))||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:i}=e;i.fontSize=`calc(${this.#pn}px * var(--scale-factor))`;i.color=this.#tn;e.replaceChildren();for(const t of this.#Rn.split("\n")){const i=document.createElement("div");i.append(t?document.createTextNode(t):document.createElement("br"));e.append(i)}const s=FreeTextEditor._internalPadding*this.parentScale;t.updateEdited({rect:this.getRect(s,s),popupContent:this.#Rn});return e}resetAnnotationElement(t){super.resetAnnotationElement(t);t.resetEdited()}}class Outline{static PRECISION=1e-4;toSVGPath(){unreachable("Abstract method `toSVGPath` must be implemented.")}get box(){unreachable("Abstract getter `box` must be implemented.")}serialize(t,e){unreachable("Abstract method `serialize` must be implemented.")}static _rescale(t,e,i,s,n,r){r||=new Float32Array(t.length);for(let a=0,o=t.length;a=6;t-=6)isNaN(e[t])?i.push(`L${e[t+4]} ${e[t+5]}`):i.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#hr(i);return i.join(" ")}#or(){const[t,e,i,s]=this.#Vn,[n,r,a,o]=this.#ar();return`M${(this.#Yn[2]-t)/i} ${(this.#Yn[3]-e)/s} L${(this.#Yn[4]-t)/i} ${(this.#Yn[5]-e)/s} L${n} ${r} L${a} ${o} L${(this.#Yn[16]-t)/i} ${(this.#Yn[17]-e)/s} L${(this.#Yn[14]-t)/i} ${(this.#Yn[15]-e)/s} Z`}#hr(t){const e=this.#$n;t.push(`L${e[4]} ${e[5]} Z`)}#lr(t){const[e,i,s,n]=this.#Vn,r=this.#Yn.subarray(4,6),a=this.#Yn.subarray(16,18),[o,l,h,c]=this.#ar();t.push(`L${(r[0]-e)/s} ${(r[1]-i)/n} L${o} ${l} L${h} ${c} L${(a[0]-e)/s} ${(a[1]-i)/n}`)}newFreeDrawOutline(t,e,i,s,n,r){return new FreeDrawOutline(t,e,i,s,n,r)}getOutlines(){const t=this.#Xn,e=this.#$n,i=this.#Yn,[s,n,r,a]=this.#Vn,o=new Float32Array((this.#ir?.length??0)+2);for(let t=0,e=o.length-2;t=6;t-=6)for(let i=0;i<6;i+=2)if(isNaN(e[t+i])){l[h]=l[h+1]=NaN;h+=2}else{l[h]=e[t+i];l[h+1]=e[t+i+1];h+=2}this.#ur(l,h);return this.newFreeDrawOutline(l,o,this.#Vn,this.#tr,this.#Wn,this.#qn)}#cr(t){const e=this.#Yn,[i,s,n,r]=this.#Vn,[a,o,l,h]=this.#ar(),c=new Float32Array(36);c.set([NaN,NaN,NaN,NaN,(e[2]-i)/n,(e[3]-s)/r,NaN,NaN,NaN,NaN,(e[4]-i)/n,(e[5]-s)/r,NaN,NaN,NaN,NaN,a,o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,(e[16]-i)/n,(e[17]-s)/r,NaN,NaN,NaN,NaN,(e[14]-i)/n,(e[15]-s)/r],0);return this.newFreeDrawOutline(c,t,this.#Vn,this.#tr,this.#Wn,this.#qn)}#ur(t,e){const i=this.#$n;t.set([NaN,NaN,NaN,NaN,i[4],i[5]],e);return e+6}#dr(t,e){const i=this.#Yn.subarray(4,6),s=this.#Yn.subarray(16,18),[n,r,a,o]=this.#Vn,[l,h,c,d]=this.#ar();t.set([NaN,NaN,NaN,NaN,(i[0]-n)/a,(i[1]-r)/o,NaN,NaN,NaN,NaN,l,h,NaN,NaN,NaN,NaN,c,d,NaN,NaN,NaN,NaN,(s[0]-n)/a,(s[1]-r)/o],e);return e+24}}class FreeDrawOutline extends Outline{#Vn;#pr=new Float32Array(4);#Wn;#qn;#ir;#tr;#gr;constructor(t,e,i,s,n,r){super();this.#gr=t;this.#ir=e;this.#Vn=i;this.#tr=s;this.#Wn=n;this.#qn=r;this.lastPoint=[NaN,NaN];this.#fr(r);const[a,o,l,h]=this.#pr;for(let e=0,i=t.length;et[0]-e[0]||t[1]-e[1]||t[2]-e[2]));const t=[];for(const e of this.#br)if(e[3]){t.push(...this.#yr(e));this.#wr(e)}else{this.#Ar(e);t.push(...this.#yr(e))}return this.#xr(t)}#xr(t){const e=[],i=new Set;for(const i of t){const[t,s,n]=i;e.push([t,s,i],[t,n,i])}e.sort(((t,e)=>t[1]-e[1]||t[0]-e[0]));for(let t=0,s=e.length;t0;){const t=i.values().next().value;let[e,r,a,o,l]=t;i.delete(t);let h=e,c=r;n=[e,a];s.push(n);for(;;){let t;if(i.has(o))t=o;else{if(!i.has(l))break;t=l}i.delete(t);[e,r,a,o,l]=t;if(h!==e){n.push(h,c,e,c===r?r:a);h=e}c=c===r?a:r}n.push(h,c)}return new HighlightOutline(s,this.#Vn,this.#mr)}#_r(t){const e=this.#vr;let i=0,s=e.length-1;for(;i<=s;){const n=i+s>>1,r=e[n][0];if(r===t)return n;r=0;s--){const[i,n]=this.#vr[s];if(i!==t)break;if(i===t&&n===e){this.#vr.splice(s,1);return}}}#yr(t){const[e,i,s]=t,n=[[e,i,s]],r=this.#_r(s);for(let t=0;t=i)if(o>s)n[t][1]=s;else{if(1===r)return[];n.splice(t,1);t--;r--}else{n[t][2]=i;o>s&&n.push([e,s,o])}}}return n}}class HighlightOutline extends Outline{#Vn;#Er;constructor(t,e,i){super();this.#Er=t;this.#Vn=e;this.lastPoint=i}toSVGPath(){const t=[];for(const e of this.#Er){let[i,s]=e;t.push(`M${i} ${s}`);for(let n=2;n-1){this.#Xr=!0;this.#Zr(t);this.#ta()}else if(this.#zr){this.#Hr=t.anchorNode;this.#Ur=t.anchorOffset;this.#Vr=t.focusNode;this.#$r=t.focusOffset;this.#ea();this.#ta();this.rotate(this.rotation)}}get telemetryInitialData(){return{action:"added",type:this.#Xr?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#er,methodOfCreation:this.#Jr}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#ea(){const t=new HighlightOutliner(this.#zr,.001);this.#qr=t.getOutlines();[this.x,this.y,this.width,this.height]=this.#qr.box;const e=new HighlightOutliner(this.#zr,.0025,.001,"ltr"===this._uiManager.direction);this.#Gr=e.getOutlines();const{lastPoint:i}=this.#Gr;this.#mr=[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]}#Zr({highlightOutlines:t,highlightId:e,clipPathId:i}){this.#qr=t;this.#Gr=t.getNewOutline(this.#er/2+1.5,.0025);if(e>=0){this.#y=e;this.#jr=i;this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}});this.#Kr=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#Gr.box,path:{d:this.#Gr.toSVGPath()}},!0)}else if(this.parent){const e=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#y,{bbox:HighlightEditor.#ia(this.#qr.box,(e-this.rotation+360)%360),path:{d:t.toSVGPath()}});this.parent.drawLayer.updateProperties(this.#Kr,{bbox:HighlightEditor.#ia(this.#Gr.box,e),path:{d:this.#Gr.toSVGPath()}})}const[s,n,r,a]=t.box;switch(this.rotation){case 0:this.x=s;this.y=n;this.width=r;this.height=a;break;case 90:{const[t,e]=this.parentDimensions;this.x=n;this.y=1-s;this.width=r*e/t;this.height=a*t/e;break}case 180:this.x=1-s;this.y=1-n;this.width=r;this.height=a;break;case 270:{const[t,e]=this.parentDimensions;this.x=1-n;this.y=s;this.width=r*e/t;this.height=a*t/e;break}}const{lastPoint:o}=this.#Gr;this.#mr=[(o[0]-s)/r,(o[1]-n)/a]}static initialize(t,e){AnnotationEditor.initialize(t,e);HighlightEditor._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case m.HIGHLIGHT_DEFAULT_COLOR:HighlightEditor._defaultColor=e;break;case m.HIGHLIGHT_THICKNESS:HighlightEditor._defaultThickness=e}}translateInPage(t,e){}get toolbarPosition(){return this.#mr}updateParams(t,e){switch(t){case m.HIGHLIGHT_COLOR:this.#On(e);break;case m.HIGHLIGHT_THICKNESS:this.#sa(e)}}static get defaultPropertiesToUpdate(){return[[m.HIGHLIGHT_DEFAULT_COLOR,HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,HighlightEditor._defaultThickness]]}get propertiesToUpdate(){return[[m.HIGHLIGHT_COLOR,this.color||HighlightEditor._defaultColor],[m.HIGHLIGHT_THICKNESS,this.#er||HighlightEditor._defaultThickness],[m.HIGHLIGHT_FREE,this.#Xr]]}#On(t){const setColorAndOpacity=(t,e)=>{this.color=t;this.#Yr=e;this.parent?.drawLayer.updateProperties(this.#y,{root:{fill:t,"fill-opacity":e}});this.#n?.updateColor(t)},e=this.color,i=this.#Yr;this.addCommands({cmd:setColorAndOpacity.bind(this,t,HighlightEditor._defaultOpacity),undo:setColorAndOpacity.bind(this,e,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#sa(t){const e=this.#er,setThickness=t=>{this.#er=t;this.#na(t)};this.addCommands({cmd:setThickness.bind(this,t),undo:setThickness.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:m.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0});this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();if(!t)return null;if(this._uiManager.highlightColors){this.#n=new ColorPicker({editor:this});t.addColorPicker(this.#n)}return t}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#ra())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#ra())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);t&&this.div.focus()}remove(){this.#aa();this._reportTelemetry({action:"deleted"});super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#ta();this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t)this.#aa();else if(t){this.#ta(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);this.show(this._isVisible);e&&this.select()}#na(t){if(!this.#Xr)return;this.#Zr({highlightOutlines:this.#qr.getNewOutline(t/2)});this.fixAndSetPosition();const[e,i]=this.parentDimensions;this.setDims(this.width*e,this.height*i)}#aa(){if(null!==this.#y&&this.parent){this.parent.drawLayer.remove(this.#y);this.#y=null;this.parent.drawLayer.remove(this.#Kr);this.#Kr=null}}#ta(t=this.parent){if(null===this.#y){({id:this.#y,clipPathId:this.#jr}=t.drawLayer.draw({bbox:this.#qr.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#Yr},rootClass:{highlight:!0,free:this.#Xr},path:{d:this.#qr.toSVGPath()}},!1,!0));this.#Kr=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#Xr},bbox:this.#Gr.box,path:{d:this.#Gr.toSVGPath()}},this.#Xr);this.#Wr&&(this.#Wr.style.clipPath=this.#jr)}}static#ia([t,e,i,s],n){switch(n){case 90:return[1-e-s,t,s,i];case 180:return[1-t-i,1-e-s,i,s];case 270:return[e,1-t-i,s,i]}return[t,e,i,s]}rotate(t){const{drawLayer:e}=this.parent;let i;if(this.#Xr){t=(t-this.rotation+360)%360;i=HighlightEditor.#ia(this.#qr.box,t)}else i=HighlightEditor.#ia([this.x,this.y,this.width,this.height],t);e.updateProperties(this.#y,{bbox:i,root:{"data-main-rotation":t}});e.updateProperties(this.#Kr,{bbox:HighlightEditor.#ia(this.#Gr.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();if(this.#Qr){t.setAttribute("aria-label",this.#Qr);t.setAttribute("role","mark")}this.#Xr?t.classList.add("free"):this.div.addEventListener("keydown",this.#oa.bind(this),{signal:this._uiManager._signal});const e=this.#Wr=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";e.style.clipPath=this.#jr;const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);bindEvents(this,this.#Wr,["pointerover","pointerleave"]);this.enableEditing();return t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Kr,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#Kr,{rootClass:{hovered:!1}})}#oa(t){HighlightEditor._keyboardManager.exec(this,t)}_moveCaret(t){this.parent.unselect(this);switch(t){case 0:case 2:this.#la(!0);break;case 1:case 3:this.#la(!1)}}#la(t){if(!this.#Hr)return;const e=window.getSelection();t?e.setPosition(this.#Hr,this.#Ur):e.setPosition(this.#Vr,this.#$r)}select(){super.select();this.#Kr&&this.parent?.drawLayer.updateProperties(this.#Kr,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect();if(this.#Kr){this.parent?.drawLayer.updateProperties(this.#Kr,{rootClass:{selected:!1}});this.#Xr||this.#la(!1)}}get _mustFixPosition(){return!this.#Xr}show(t=this._isVisible){super.show(t);if(this.parent){this.parent.drawLayer.updateProperties(this.#y,{rootClass:{hidden:!t}});this.parent.drawLayer.updateProperties(this.#Kr,{rootClass:{hidden:!t}})}}#ra(){return this.#Xr?this.rotation:0}#ha(){if(this.#Xr)return null;const[t,e]=this.pageDimensions,[i,s]=this.pageTranslation,n=this.#zr,r=new Float32Array(8*n.length);let a=0;for(const{x:o,y:l,width:h,height:c}of n){const n=o*t+i,d=(1-l)*e+s;r[a]=r[a+4]=n;r[a+1]=r[a+3]=d;r[a+2]=r[a+6]=n+h*t;r[a+5]=r[a+7]=d-c*e;a+=8}return r}#ca(t){return this.#qr.serialize(t,this.#ra())}static startHighlighting(t,e,{target:i,x:s,y:n}){const{x:r,y:a,width:o,height:l}=i.getBoundingClientRect(),h=new AbortController,c=t.combinedSignal(h),pointerUpCallback=e=>{h.abort();this.#da(t,e)};window.addEventListener("blur",pointerUpCallback,{signal:c});window.addEventListener("pointerup",pointerUpCallback,{signal:c});window.addEventListener("pointerdown",stopEvent,{capture:!0,passive:!1,signal:c});window.addEventListener("contextmenu",noContextMenu,{signal:c});i.addEventListener("pointermove",this.#ua.bind(this,t),{signal:c});this._freeHighlight=new FreeHighlightOutliner({x:s,y:n},[r,a,o,l],t.scale,this._defaultThickness/2,e,.001);({id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0))}static#ua(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#da(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"});this._freeHighlightId=-1;this._freeHighlight=null;this._freeHighlightClipId=""}static async deserialize(t,e,i){let s=null;if(t instanceof HighlightAnnotationElement){const{data:{quadPoints:e,rect:i,rotation:n,id:r,color:a,opacity:o,popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:f.HIGHLIGHT,color:Array.from(a),opacity:o,quadPoints:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:r,deleted:!1,popupRef:l}}else if(t instanceof InkAnnotationElement){const{data:{inkLists:e,rect:i,rotation:n,id:r,color:a,borderStyle:{rawWidth:o},popupRef:l},parent:{page:{pageNumber:h}}}=t;s=t={annotationType:f.HIGHLIGHT,color:Array.from(a),thickness:o,inkLists:e,boxes:null,pageIndex:h-1,rect:i.slice(0),rotation:n,id:r,deleted:!1,popupRef:l}}const{color:n,quadPoints:r,inkLists:a,opacity:o}=t,l=await super.deserialize(t,e,i);l.color=Util.makeHexColor(...n);l.#Yr=o||1;a&&(l.#er=t.thickness);l.annotationElementId=t.id||null;l._initialData=s;const[h,c]=l.pageDimensions,[d,u]=l.pageTranslation;if(r){const t=l.#zr=[];for(let e=0;et!==e[i]))}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class DrawingOptions{#pa=Object.create(null);updateProperty(t,e){this[t]=e;this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,i]of Object.entries(t))this.updateProperty(e,i)}updateSVGProperty(t,e){this.#pa[t]=e}toSVGProperties(){const t=this.#pa;this.#pa=Object.create(null);return{root:t}}reset(){this.#pa=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){unreachable("Not implemented")}}class DrawingEditor extends AnnotationEditor{#ga=null;#fa;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#ma=null;static#ba=null;static#va=null;static#ya=NaN;static#wa=null;static#Aa=null;static#xa=NaN;static _INNER_MARGIN=3;constructor(t){super(t);this.#fa=t.mustBeCommitted||!1;if(t.drawOutlines){this.#_a(t);this.#ta()}}#_a({drawOutlines:t,drawId:e,drawingOptions:i}){this.#ga=t;this._drawingOptions||=i;if(e>=0){this._drawId=e;this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)}else this._drawId=this.#Ea(t,this.parent);this.#Sa(t.box)}#Ea(t,e){const{id:i}=e.drawLayer.draw(DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i}static _mergeSVGProperties(t,e){const i=new Set(Object.keys(t));for(const[s,n]of Object.entries(e))i.has(s)?Object.assign(t[s],n):t[s]=n;return t}static getDefaultDrawingOptions(t){unreachable("Not implemented")}static get typesMap(){unreachable("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const i=this.typesMap.get(t);i&&this._defaultDrawingOptions.updateProperty(i,e);if(this._currentParent){DrawingEditor.#ma.updateProperty(i,e);this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties())}}updateParams(t,e){const i=this.constructor.typesMap.get(t);i&&this._updateProperty(t,i,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[i,s]of this.typesMap)t.push([i,e[s]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[i,s]of this.constructor.typesMap)t.push([i,e[s]]);return t}_updateProperty(t,e,i){const s=this._drawingOptions,n=s[e],setter=t=>{s.updateProperty(e,t);const i=this.#ga.updateProperty(e,t);i&&this.#Sa(i);this.parent?.drawLayer.updateProperties(this._drawId,s.toSVGProperties())};this.addCommands({cmd:setter.bind(this,i),undo:setter.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ga.getPathResizingSVGProperties(this.#Ca()),{bbox:this.#Ta()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ga.getPathResizedSVGProperties(this.#Ca()),{bbox:this.#Ta()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#Ta(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties(this.#ga.getPathTranslatedSVGProperties(this.#Ca(),this.parentDimensions),{bbox:this.#Ta()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit();this.disableEditMode();this.disableEditing()}disableEditing(){super.disableEditing();this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing();this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this);this._isDraggable=!0;if(this.#fa){this.#fa=!1;this.commit();this.parent.setSelected(this);t&&this.isOnScreen&&this.div.focus()}}remove(){this.#aa();super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#ta();this.#Sa(this.#ga.box);this.isAttachedToDOM||this.parent.add(this)}}}setParent(t){let e=!1;if(this.parent&&!t){this._uiManager.removeShouldRescale(this);this.#aa()}else if(t){this._uiManager.addShouldRescale(this);this.#ta(t);e=!this.parent&&this.div?.classList.contains("selectedEditor")}super.setParent(t);e&&this.select()}#aa(){if(null!==this._drawId&&this.parent){this.parent.drawLayer.remove(this._drawId);this._drawId=null;this._drawingOptions.reset()}}#ta(t=this.parent){if(null===this._drawId||this.parent!==t)if(null===this._drawId){this._drawingOptions.updateAll();this._drawId=this.#Ea(this.#ga,t)}else this.parent.drawLayer.updateParent(this._drawId,t.drawLayer)}#Ma([t,e,i,s]){const{parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[e,1-t,i*(r/n),s*(n/r)];case 180:return[1-t,1-e,i,s];case 270:return[1-e,t,i*(r/n),s*(n/r)];default:return[t,e,i,s]}}#Ca(){const{x:t,y:e,width:i,height:s,parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[1-e,t,i*(n/r),s*(r/n)];case 180:return[1-t,1-e,i,s];case 270:return[e,1-t,i*(n/r),s*(r/n)];default:return[t,e,i,s]}}#Sa(t){[this.x,this.y,this.width,this.height]=this.#Ma(t);if(this.div){this.fixAndSetPosition();const[t,e]=this.parentDimensions;this.setDims(this.width*t,this.height*e)}this._onResized()}#Ta(){const{x:t,y:e,width:i,height:s,rotation:n,parentRotation:r,parentDimensions:[a,o]}=this;switch((4*n+r)/90){case 1:return[1-e-s,t,s,i];case 2:return[1-t-i,1-e-s,i,s];case 3:return[e,1-t-i,s,i];case 4:return[t,e-i*(a/o),s*(o/a),i*(a/o)];case 5:return[1-e,t,i*(a/o),s*(o/a)];case 6:return[1-t-s*(o/a),1-e,s*(o/a),i*(a/o)];case 7:return[e-i*(a/o),1-t-s*(o/a),i*(a/o),s*(o/a)];case 8:return[t-i,e-s,i,s];case 9:return[1-e,t-i,s,i];case 10:return[1-t,1-e,i,s];case 11:return[e-s,1-t,s,i];case 12:return[t-s*(o/a),e,s*(o/a),i*(a/o)];case 13:return[1-e-i*(a/o),t-s*(o/a),i*(a/o),s*(o/a)];case 14:return[1-t,1-e-i*(a/o),s*(o/a),i*(a/o)];case 15:return[e,1-t,i*(a/o),s*(o/a)];default:return[t,e,i,s]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,DrawingEditor._mergeSVGProperties({bbox:this.#Ta()},this.#ga.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#Sa(this.#ga.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e);e.setAttribute("aria-hidden","true");e.className="internal";const[i,s]=this.parentDimensions;this.setDims(this.width*i,this.height*s);this._uiManager.addShouldRescale(this);this.disableEditing();return t}static createDrawerInstance(t,e,i,s,n){unreachable("Not implemented")}static startDrawing(t,e,i,s){const{target:n,offsetX:r,offsetY:a,pointerId:o,pointerType:l}=s;if(DrawingEditor.#wa&&DrawingEditor.#wa!==l)return;const{viewport:{rotation:h}}=t,{width:c,height:d}=n.getBoundingClientRect(),u=DrawingEditor.#ba=new AbortController,p=t.combinedSignal(u);DrawingEditor.#ya||=o;DrawingEditor.#wa??=l;window.addEventListener("pointerup",(t=>{DrawingEditor.#ya===t.pointerId?this._endDraw(t):DrawingEditor.#Aa?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointercancel",(t=>{DrawingEditor.#ya===t.pointerId?this._currentParent.endDrawingSession():DrawingEditor.#Aa?.delete(t.pointerId)}),{signal:p});window.addEventListener("pointerdown",(t=>{if(DrawingEditor.#wa===t.pointerType){(DrawingEditor.#Aa||=new Set).add(t.pointerId);if(DrawingEditor.#ma.isCancellable()){DrawingEditor.#ma.removeLastElement();DrawingEditor.#ma.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)}}}),{capture:!0,passive:!1,signal:p});window.addEventListener("contextmenu",noContextMenu,{signal:p});n.addEventListener("pointermove",this._drawMove.bind(this),{signal:p});n.addEventListener("touchmove",(t=>{t.timeStamp===DrawingEditor.#xa&&stopEvent(t)}),{signal:p});t.toggleDrawing();e._editorUndoBar?.hide();if(DrawingEditor.#ma)t.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#ma.startNew(r,a,c,d,h));else{e.updateUIForDefaultProperties(this);DrawingEditor.#ma=this.createDrawerInstance(r,a,c,d,h);DrawingEditor.#va=this.getDefaultDrawingOptions();this._currentParent=t;({id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(DrawingEditor.#va.toSVGProperties(),DrawingEditor.#ma.defaultSVGProperties),!0,!1))}}static _drawMove(t){DrawingEditor.#xa=-1;if(!DrawingEditor.#ma)return;const{offsetX:e,offsetY:i,pointerId:s}=t;if(DrawingEditor.#ya===s)if(DrawingEditor.#Aa?.size>=1)this._endDraw(t);else{this._currentParent.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#ma.add(e,i));DrawingEditor.#xa=t.timeStamp;stopEvent(t)}}static _cleanup(t){if(t){this._currentDrawId=-1;this._currentParent=null;DrawingEditor.#ma=null;DrawingEditor.#va=null;DrawingEditor.#wa=null;DrawingEditor.#xa=NaN}if(DrawingEditor.#ba){DrawingEditor.#ba.abort();DrawingEditor.#ba=null;DrawingEditor.#ya=NaN;DrawingEditor.#Aa=null}}static _endDraw(t){const e=this._currentParent;if(e){e.toggleDrawing(!0);this._cleanup(!1);t&&e.drawLayer.updateProperties(this._currentDrawId,DrawingEditor.#ma.end(t.offsetX,t.offsetY));if(this.supportMultipleDrawings){const t=DrawingEditor.#ma,i=this._currentDrawId,s=t.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,t.setLastElement(s))},undo:()=>{e.drawLayer.updateProperties(i,t.removeLastElement())},mustExec:!1,type:m.DRAW_STEP})}else this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;e.toggleDrawing(!0);e.cleanUndoStack(m.DRAW_STEP);if(!DrawingEditor.#ma.isEmpty()){const{pageDimensions:[i,s],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:DrawingEditor.#ma.getOutlines(i*n,s*n,n,this._INNER_MARGIN),drawingOptions:DrawingEditor.#va,mustBeCommitted:!t});this._cleanup(!0);return r}e.drawLayer.remove(this._currentDrawId);this._cleanup(!0);return null}createDrawingOptions(t){}static deserializeDraw(t,e,i,s,n,r){unreachable("Not implemented")}static async deserialize(t,e,i){const{rawDims:{pageWidth:s,pageHeight:n,pageX:r,pageY:a}}=e.viewport,o=this.deserializeDraw(r,a,s,n,this._INNER_MARGIN,t),l=await super.deserialize(t,e,i);l.createDrawingOptions(t);l.#_a({drawOutlines:o});l.#ta();l.onScaleChanging();l.rotate();return l}serializeDraw(t){const[e,i]=this.pageTranslation,[s,n]=this.pageDimensions;return this.#ga.serialize([e,i,s,n],t)}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}static canCreateNewEmptyEditor(){return!1}}class InkDrawOutliner{#Yn=new Float64Array(6);#bn;#Pa;#Fi;#er;#ir;#Da="";#ka=0;#Er=new InkDrawOutline;#Ra;#Ia;constructor(t,e,i,s,n,r){this.#Ra=i;this.#Ia=s;this.#Fi=n;this.#er=r;[t,e]=this.#Fa(t,e);const a=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ir=[t,e];this.#Pa=[{line:a,points:this.#ir}];this.#Yn.set(a,0)}updateProperty(t,e){"stroke-width"===t&&(this.#er=e)}#Fa(t,e){return Outline._normalizePoint(t,e,this.#Ra,this.#Ia,this.#Fi)}isEmpty(){return!this.#Pa||0===this.#Pa.length}isCancellable(){return this.#ir.length<=10}add(t,e){[t,e]=this.#Fa(t,e);const[i,s,n,r]=this.#Yn.subarray(2,6),a=t-n,o=e-r;if(Math.hypot(this.#Ra*a,this.#Ia*o)<=2)return null;this.#ir.push(t,e);if(isNaN(i)){this.#Yn.set([n,r,t,e],2);this.#bn.push(NaN,NaN,NaN,NaN,t,e);return{path:{d:this.toSVGPath()}}}isNaN(this.#Yn[0])&&this.#bn.splice(6,6);this.#Yn.set([i,s,n,r,t,e],0);this.#bn.push(...Outline.createBezierPoints(i,s,n,r,t,e));return{path:{d:this.toSVGPath()}}}end(t,e){const i=this.add(t,e);return i||(2===this.#ir.length?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,i,s,n){this.#Ra=i;this.#Ia=s;this.#Fi=n;[t,e]=this.#Fa(t,e);const r=this.#bn=[NaN,NaN,NaN,NaN,t,e];this.#ir=[t,e];const a=this.#Pa.at(-1);if(a){a.line=new Float32Array(a.line);a.points=new Float32Array(a.points)}this.#Pa.push({line:r,points:this.#ir});this.#Yn.set(r,0);this.#ka=0;this.toSVGPath();return null}getLastElement(){return this.#Pa.at(-1)}setLastElement(t){if(!this.#Pa)return this.#Er.setLastElement(t);this.#Pa.push(t);this.#bn=t.line;this.#ir=t.points;this.#ka=0;return{path:{d:this.toSVGPath()}}}removeLastElement(){if(!this.#Pa)return this.#Er.removeLastElement();this.#Pa.pop();this.#Da="";for(let t=0,e=this.#Pa.length;tt??NaN)),c,d,u,p),points:g(a[t].map((t=>t??NaN)),c,d,u,p)});const f=new InkDrawOutline;f.build(h,i,s,1,o,l,n);return f}#Ha(t=this.#er){const e=this.#Wn+t/2*this.#Oa;return this.#Fi%180==0?[e/this.#Ra,e/this.#Ia]:[e/this.#Ia,e/this.#Ra]}#Ba(){const[t,e,i,s]=this.#pr,[n,r]=this.#Ha(0);return[t+n,e+r,i-2*n,s-2*r]}#Na(){const t=this.#pr=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:e}of this.#Pa){if(e.length<=12){for(let i=4,s=e.length;it!==e[i]))||t.thickness!==i||t.opacity!==s||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:i}=this.serializeDraw(!1);t.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:e});return null}}class StampEditor extends AnnotationEditor{#za=null;#ja=null;#Ga=null;#Va=null;#$a=null;#Wa="";#qa=null;#Xa=null;#Ya=!1;#Ka=!1;static _type="stamp";static _editorType=f.STAMP;constructor(t){super({...t,name:"stampEditor"});this.#Va=t.bitmapUrl;this.#$a=t.bitmapFile}static initialize(t,e){AnnotationEditor.initialize(t,e)}static get supportedTypes(){return shadow(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map((t=>`image/${t}`)))}static get supportedTypesStr(){return shadow(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(f.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1);super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#Qa(t,e=!1){if(t){this.#za=t.bitmap;if(!e){this.#ja=t.id;this.#Ya=t.isSvg}t.file&&(this.#Wa=t.file.name);this.#Ja()}else this.remove()}#Za(){this.#Ga=null;this._uiManager.enableWaiting(!1);if(this.#qa)if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#za){this._editToolbar.hide();this._uiManager.editAltText(this,!0)}else{if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#za){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:s,width:n,height:r}=t||this.copyCanvas(null,null,!0).imageData,a=await i.guess({name:"altText",request:{data:s,width:n,height:r,channels:s.length/(n*r)}});if(!a)throw new Error("No response from the AI service.");if(a.error)throw new Error("Error from the AI service.");if(a.cancel)return null;if(!a.output)throw new Error("No valid response from the AI service.");const o=a.output;await this.setGuessedAltText(o);e&&!this.hasAltTextData()&&(this.altTextData={alt:o,decorative:!1});return o}#to(){if(this.#ja){this._uiManager.enableWaiting(!0);this._uiManager.imageManager.getFromId(this.#ja).then((t=>this.#Qa(t,!0))).finally((()=>this.#Za()));return}if(this.#Va){const t=this.#Va;this.#Va=null;this._uiManager.enableWaiting(!0);this.#Ga=this._uiManager.imageManager.getFromUrl(t).then((t=>this.#Qa(t))).finally((()=>this.#Za()));return}if(this.#$a){const t=this.#$a;this.#$a=null;this._uiManager.enableWaiting(!0);this.#Ga=this._uiManager.imageManager.getFromFile(t).then((t=>this.#Qa(t))).finally((()=>this.#Za()));return}const t=document.createElement("input");t.type="file";t.accept=StampEditor.supportedTypesStr;const e=this._uiManager._signal;this.#Ga=new Promise((i=>{t.addEventListener("change",(async()=>{if(t.files&&0!==t.files.length){this._uiManager.enableWaiting(!0);const e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}});this.#Qa(e)}else this.remove();i()}),{signal:e});t.addEventListener("cancel",(()=>{this.remove();i()}),{signal:e})})).finally((()=>this.#Za()));t.click()}remove(){if(this.#ja){this.#za=null;this._uiManager.imageManager.deleteId(this.#ja);this.#qa?.remove();this.#qa=null;if(this.#Xa){clearTimeout(this.#Xa);this.#Xa=null}}super.remove()}rebuild(){if(this.parent){super.rebuild();if(null!==this.div){this.#ja&&null===this.#qa&&this.#to();this.isAttachedToDOM||this.parent.add(this)}}else this.#ja&&this.#to()}onceAdded(t){this._isDraggable=!0;t&&this.div.focus()}isEmpty(){return!(this.#Ga||this.#za||this.#Va||this.#$a||this.#ja)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.div.hidden=!0;this.div.setAttribute("role","figure");this.addAltTextButton();this.#za?this.#Ja():this.#to();if(this.width&&!this.annotationElementId){const[i,s]=this.parentDimensions;this.setAt(t*i,e*s,this.width*i,this.height*s)}this._uiManager.addShouldRescale(this);return this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;null!==this.#Xa&&clearTimeout(this.#Xa);this.#Xa=setTimeout((()=>{this.#Xa=null;this.#eo()}),200)}#Ja(){const{div:t}=this;let{width:e,height:i}=this.#za;const[s,n]=this.pageDimensions,r=.75;if(this.width){e=this.width*s;i=this.height*n}else if(e>r*s||i>r*n){const t=Math.min(r*s/e,r*n/i);e*=t;i*=t}const[a,o]=this.parentDimensions;this.setDims(e*a/s,i*o/n);this._uiManager.enableWaiting(!1);const l=this.#qa=document.createElement("canvas");l.setAttribute("role","img");this.addContainer(l);this.width=e/s;this.height=i/n;this._initialOptions?.isCentered?this.center():this.fixAndSetPosition();this._initialOptions=null;this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&!this.annotationElementId||(t.hidden=!1);this.#eo();if(!this.#Ka){this.parent.addUndoableEditor(this);this.#Ka=!0}this._reportTelemetry({action:"inserted_image"});this.#Wa&&l.setAttribute("aria-label",this.#Wa)}copyCanvas(t,e,i=!1){t||(t=224);const{width:s,height:n}=this.#za,r=new OutputScale;let a=this.#za,o=s,l=n,h=null;if(e){if(s>e||n>e){const t=Math.min(e/s,e/n);o=Math.floor(s*t);l=Math.floor(n*t)}h=document.createElement("canvas");const t=h.width=Math.ceil(o*r.sx),i=h.height=Math.ceil(l*r.sy);this.#Ya||(a=this.#io(t,i));const c=h.getContext("2d");c.filter=this._uiManager.hcmFilter;let d="white",u="#cfcfd8";if("none"!==this._uiManager.hcmFilter)u="black";else if(window.matchMedia?.("(prefers-color-scheme: dark)").matches){d="#8f8f9d";u="#42414d"}const p=15,g=p*r.sx,f=p*r.sy,m=new OffscreenCanvas(2*g,2*f),b=m.getContext("2d");b.fillStyle=d;b.fillRect(0,0,2*g,2*f);b.fillStyle=u;b.fillRect(0,0,g,f);b.fillRect(g,f,g,f);c.fillStyle=c.createPattern(m,"repeat");c.fillRect(0,0,t,i);c.drawImage(a,0,0,a.width,a.height,0,0,t,i)}let c=null;if(i){let e,i;if(r.symmetric&&a.widtht||n>t){const r=Math.min(t/s,t/n);e=Math.floor(s*r);i=Math.floor(n*r);this.#Ya||(a=this.#io(e,i))}}const o=new OffscreenCanvas(e,i).getContext("2d",{willReadFrequently:!0});o.drawImage(a,0,0,a.width,a.height,0,0,e,i);c={width:e,height:i,data:o.getImageData(0,0,e,i).data}}return{canvas:h,width:o,height:l,imageData:c}}#io(t,e){const{width:i,height:s}=this.#za;let n=i,r=s,a=this.#za;for(;n>2*t||r>2*e;){const i=n,s=r;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2));r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2));const o=new OffscreenCanvas(n,r);o.getContext("2d").drawImage(a,0,0,i,s,0,0,n,r);a=o.transferToImageBitmap()}return a}#eo(){const[t,e]=this.parentDimensions,{width:i,height:s}=this,n=new OutputScale,r=Math.ceil(i*t*n.sx),a=Math.ceil(s*e*n.sy),o=this.#qa;if(!o||o.width===r&&o.height===a)return;o.width=r;o.height=a;const l=this.#Ya?this.#za:this.#io(r,a),h=o.getContext("2d");h.filter=this._uiManager.hcmFilter;h.drawImage(l,0,0,l.width,l.height,0,0,r,a)}getImageForAltText(){return this.#qa}#so(t){if(t){if(this.#Ya){const t=this._uiManager.imageManager.getSvgUrl(this.#ja);if(t)return t}const t=document.createElement("canvas");({width:t.width,height:t.height}=this.#za);t.getContext("2d").drawImage(this.#za,0,0);return t.toDataURL()}if(this.#Ya){const[t,e]=this.pageDimensions,i=Math.round(this.width*t*PixelsPerInch.PDF_TO_CSS_UNITS),s=Math.round(this.height*e*PixelsPerInch.PDF_TO_CSS_UNITS),n=new OffscreenCanvas(i,s);n.getContext("2d").drawImage(this.#za,0,0,this.#za.width,this.#za.height,0,0,i,s);return n.transferToImageBitmap()}return structuredClone(this.#za)}static async deserialize(t,e,i){let s=null;if(t instanceof StampAnnotationElement){const{data:{rect:n,rotation:r,id:a,structParent:o,popupRef:l},container:h,parent:{page:{pageNumber:c}}}=t,d=h.querySelector("canvas"),u=i.imageManager.getFromCanvas(h.id,d);d.remove();const p=(await e._structTree.getAriaAttributes(`${st}${a}`))?.get("aria-label")||"";s=t={annotationType:f.STAMP,bitmapId:u.id,bitmap:u.bitmap,pageIndex:c-1,rect:n.slice(0),rotation:r,id:a,deleted:!1,accessibilityData:{decorative:!1,altText:p},isSvg:!1,structParent:o,popupRef:l}}const n=await super.deserialize(t,e,i),{rect:r,bitmap:a,bitmapUrl:o,bitmapId:l,isSvg:h,accessibilityData:c}=t;if(l&&i.imageManager.isValidId(l)){n.#ja=l;a&&(n.#za=a)}else n.#Va=o;n.#Ya=h;const[d,u]=n.pageDimensions;n.width=(r[2]-r[0])/d;n.height=(r[3]-r[1])/u;n.annotationElementId=t.id||null;c&&(n.altTextData=c);n._initialData=s;n.#Ka=!!s;return n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:f.STAMP,bitmapId:this.#ja,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#Ya,structTreeParentId:this._structTreeParentId};if(t){i.bitmapUrl=this.#so(!0);i.accessibilityData=this.serializeAltText(!0);return i}const{decorative:s,altText:n}=this.serializeAltText(!1);!s&&n&&(i.accessibilityData={type:"Figure",alt:n});if(this.annotationElementId){const t=this.#Gn(i);if(t.isSame)return null;t.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}i.id=this.annotationElementId;if(null===e)return i;e.stamps||=new Map;const r=this.#Ya?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(e.stamps.has(this.#ja)){if(this.#Ya){const t=e.stamps.get(this.#ja);if(r>t.area){t.area=r;t.serialized.bitmap.close();t.serialized.bitmap=this.#so(!1)}}}else{e.stamps.set(this.#ja,{area:r,serialized:i});i.bitmap=this.#so(!1)}return i}#Gn(t){const{pageIndex:e,accessibilityData:{altText:i}}=this._initialData,s=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===i;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&s&&n,isSameAltText:n}}renderAnnotationElement(t){t.updateEdited({rect:this.getRect(0,0)});return null}}class AnnotationEditorLayer{#Cn;#no=!1;#ro=null;#ao=null;#oo=null;#lo=new Map;#ho=!1;#co=!1;#do=!1;#uo=null;#po=null;#go=null;#fo=null;#f;static _initialized=!1;static#z=new Map([FreeTextEditor,InkEditor,StampEditor,HighlightEditor].map((t=>[t._editorType,t])));constructor({uiManager:t,pageIndex:e,div:i,structTreeLayer:s,accessibilityManager:n,annotationLayer:r,drawLayer:a,textLayer:o,viewport:l,l10n:h}){const c=[...AnnotationEditorLayer.#z.values()];if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;for(const e of c)e.initialize(h,t)}t.registerEditorTypes(c);this.#f=t;this.pageIndex=e;this.div=i;this.#Cn=n;this.#ro=r;this.viewport=l;this.#go=o;this.drawLayer=a;this._structTree=s;this.#f.addLayer(this)}get isEmpty(){return 0===this.#lo.size}get isInvisible(){return this.isEmpty&&this.#f.getMode()===f.NONE}updateToolbar(t){this.#f.updateToolbar(t)}updateMode(t=this.#f.getMode()){this.#mo();switch(t){case f.NONE:this.disableTextSelection();this.togglePointerEvents(!1);this.toggleAnnotationLayerPointerEvents(!0);this.disableClick();return;case f.INK:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick();break;case f.HIGHLIGHT:this.enableTextSelection();this.togglePointerEvents(!1);this.disableClick();break;default:this.disableTextSelection();this.togglePointerEvents(!0);this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const i of AnnotationEditorLayer.#z.values())e.toggle(`${i._type}Editing`,t===i._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#go?.div}setEditingState(t){this.#f.setEditingState(t)}addCommands(t){this.#f.addCommands(t)}cleanUndoStack(t){this.#f.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#ro?.div.classList.toggle("disabled",!t)}async enable(){this.#do=!0;this.div.tabIndex=0;this.togglePointerEvents(!0);const t=new Set;for(const e of this.#lo.values()){e.enableEditing();e.show(!0);if(e.annotationElementId){this.#f.removeChangedExistingAnnotation(e);t.add(e.annotationElementId)}}if(!this.#ro){this.#do=!1;return}const e=this.#ro.getEditableAnnotations();for(const i of e){i.hide();if(this.#f.isDeletedAnnotationElement(i.data.id))continue;if(t.has(i.data.id))continue;const e=await this.deserialize(i);if(e){this.addOrRebuild(e);e.enableEditing()}}this.#do=!1}disable(){this.#co=!0;this.div.tabIndex=-1;this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#lo.values()){i.disableEditing();if(i.annotationElementId)if(null===i.serialize()){e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show();i.remove()}else t.set(i.annotationElementId,i)}if(this.#ro){const i=this.#ro.getEditableAnnotations();for(const s of i){const{id:i}=s.data;if(this.#f.isDeletedAnnotationElement(i))continue;let n=e.get(i);if(n){n.resetAnnotationElement(s);n.show(!1);s.show()}else{n=t.get(i);if(n){this.#f.addChangedExistingAnnotation(n);n.renderAnnotationElement(s)&&n.show(!1)}s.show()}}}this.#mo();this.isEmpty&&(this.div.hidden=!0);const{classList:i}=this.div;for(const t of AnnotationEditorLayer.#z.values())i.remove(`${t._type}Editing`);this.disableTextSelection();this.toggleAnnotationLayerPointerEvents(!0);this.#co=!1}getEditableAnnotation(t){return this.#ro?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#f.getActive()!==t&&this.#f.setActiveEditor(t)}enableTextSelection(){this.div.tabIndex=-1;if(this.#go?.div&&!this.#fo){this.#fo=new AbortController;const t=this.#f.combinedSignal(this.#fo);this.#go.div.addEventListener("pointerdown",this.#bo.bind(this),{signal:t});this.#go.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0;if(this.#go?.div&&this.#fo){this.#fo.abort();this.#fo=null;this.#go.div.classList.remove("highlighting")}}#bo(t){this.#f.unselectAll();const{target:e}=t;if(e===this.#go.div||("img"===e.getAttribute("role")||e.classList.contains("endOfContent"))&&this.#go.div.contains(e)){const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;this.#f.showAllEditors("highlight",!0,!0);this.#go.div.classList.add("free");this.toggleDrawing();HighlightEditor.startHighlighting(this,"ltr"===this.#f.direction,{target:this.#go.div,x:t.x,y:t.y});this.#go.div.addEventListener("pointerup",(()=>{this.#go.div.classList.remove("free");this.toggleDrawing(!0)}),{once:!0,signal:this.#f._signal});t.preventDefault()}}enableClick(){if(this.#ao)return;this.#ao=new AbortController;const t=this.#f.combinedSignal(this.#ao);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t});this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#ao?.abort();this.#ao=null}attach(t){this.#lo.set(t.id,t);const{annotationElementId:e}=t;e&&this.#f.isDeletedAnnotationElement(e)&&this.#f.removeDeletedAnnotationElement(t)}detach(t){this.#lo.delete(t.id);this.#Cn?.removePointerInTextLayer(t.contentDiv);!this.#co&&t.annotationElementId&&this.#f.addDeletedAnnotationElement(t)}remove(t){this.detach(t);this.#f.removeEditor(t);t.div.remove();t.isAttachedToDOM=!1}changeParent(t){if(t.parent!==this){if(t.parent&&t.annotationElementId){this.#f.addDeletedAnnotationElement(t.annotationElementId);AnnotationEditor.deleteAnnotationElement(t);t.annotationElementId=null}this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){if(t.parent!==this||!t.isAttachedToDOM){this.changeParent(t);this.#f.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}t.fixAndSetPosition();t.onceAdded(!this.#do);this.#f.addToAnnotationStorage(t);t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;if(t.div.contains(e)&&!this.#oo){t._focusEventsAllowed=!1;this.#oo=setTimeout((()=>{this.#oo=null;if(t.div.contains(document.activeElement))t._focusEventsAllowed=!0;else{t.div.addEventListener("focusin",(()=>{t._focusEventsAllowed=!0}),{once:!0,signal:this.#f._signal});e.focus()}}),0)}t._structTreeParentId=this.#Cn?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){if(t.needsToBeRebuilt()){t.parent||=this;t.rebuild();t.show()}else this.add(t)}addUndoableEditor(t){this.addCommands({cmd:()=>t._uiManager.rebuild(t),undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#f.getId()}get#vo(){return AnnotationEditorLayer.#z.get(this.#f.getMode())}combinedSignal(t){return this.#f.combinedSignal(t)}#yo(t){const e=this.#vo;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#vo?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#f.updateToolbar(t);this.#f.updateMode(t);const{offsetX:i,offsetY:s}=this.#wo(),n=this.getNextId(),r=this.#yo({parent:this,id:n,x:i,y:s,uiManager:this.#f,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await(AnnotationEditorLayer.#z.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#f))||null}createAndAddNewEditor(t,e,i={}){const s=this.getNextId(),n=this.#yo({parent:this,id:s,x:t.offsetX,y:t.offsetY,uiManager:this.#f,isCentered:e,...i});n&&this.add(n);return n}#wo(){const{x:t,y:e,width:i,height:s}=this.div.getBoundingClientRect(),n=Math.max(0,t),r=Math.max(0,e),a=(n+Math.min(window.innerWidth,t+i))/2-t,o=(r+Math.min(window.innerHeight,e+s))/2-e,[l,h]=this.viewport.rotation%180==0?[a,o]:[o,a];return{offsetX:l,offsetY:h}}addNewEditor(){this.createAndAddNewEditor(this.#wo(),!0)}setSelected(t){this.#f.setSelected(t)}toggleSelected(t){this.#f.toggleSelected(t)}unselect(t){this.#f.unselect(t)}pointerup(t){const{isMac:e}=util_FeatureTest.platform;if(!(0!==t.button||t.ctrlKey&&e)&&t.target===this.div&&this.#ho){this.#ho=!1;this.#vo?.isDrawer&&this.#vo.supportMultipleDrawings||(this.#no?this.#f.getMode()!==f.STAMP?this.createAndAddNewEditor(t,!1):this.#f.unselectAll():this.#no=!0)}}pointerdown(t){this.#f.getMode()===f.HIGHLIGHT&&this.enableTextSelection();if(this.#ho){this.#ho=!1;return}const{isMac:e}=util_FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#ho=!0;if(this.#vo?.isDrawer){this.startDrawingSession(t);return}const i=this.#f.getActive();this.#no=!i||i.isEmpty()}startDrawingSession(t){this.div.focus();if(this.#uo){this.#vo.startDrawing(this,this.#f,!1,t);return}this.#f.setCurrentDrawingSession(this);this.#uo=new AbortController;const e=this.#f.combinedSignal(this.#uo);this.div.addEventListener("blur",(({relatedTarget:t})=>{if(t&&!this.div.contains(t)){this.#po=null;this.commitOrRemove()}}),{signal:e});this.#vo.startDrawing(this,this.#f,!1,t)}pause(t){if(t){const{activeElement:t}=document;this.div.contains(t)&&(this.#po=t)}else this.#po&&setTimeout((()=>{this.#po?.focus();this.#po=null}),0)}endDrawingSession(t=!1){if(!this.#uo)return null;this.#f.setCurrentDrawingSession(null);this.#uo.abort();this.#uo=null;this.#po=null;return this.#vo.endDrawing(t)}findNewParent(t,e,i){const s=this.#f.findParent(e,i);if(null===s||s===this)return!1;s.changeParent(t);return!0}commitOrRemove(){if(this.#uo){this.endDrawingSession();return!0}return!1}onScaleChanging(){this.#uo&&this.#vo.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove();if(this.#f.getActive()?.parent===this){this.#f.commitOrRemove();this.#f.setActiveEditor(null)}if(this.#oo){clearTimeout(this.#oo);this.#oo=null}for(const t of this.#lo.values()){this.#Cn?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#lo.clear();this.#f.removeLayer(this)}#mo(){for(const t of this.#lo.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t;setLayerDimensions(this.div,t);for(const t of this.#f.getEditors(this.pageIndex)){this.add(t);t.rebuild()}this.updateMode()}update({viewport:t}){this.#f.commitOrRemove();this.#mo();const e=this.viewport.rotation,i=t.rotation;this.viewport=t;setLayerDimensions(this.div,{rotation:i});if(e!==i)for(const t of this.#lo.values())t.rotate(i)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#f.viewParameters.realScale}}class DrawLayer{#nn=null;#y=0;#Ao=new Map;#xo=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(this.#nn){if(this.#nn!==t){if(this.#Ao.size>0)for(const e of this.#Ao.values()){e.remove();t.append(e)}this.#nn=t}}else this.#nn=t}static get _svgFactory(){return shadow(this,"_svgFactory",new DOMSVGFactory)}static#_o(t,[e,i,s,n]){const{style:r}=t;r.top=100*i+"%";r.left=100*e+"%";r.width=100*s+"%";r.height=100*n+"%"}#Eo(){const t=DrawLayer._svgFactory.create(1,1,!0);this.#nn.append(t);t.setAttribute("aria-hidden",!0);return t}#So(t,e){const i=DrawLayer._svgFactory.createElement("clipPath");t.append(i);const s=`clip_${e}`;i.setAttribute("id",s);i.setAttribute("clipPathUnits","objectBoundingBox");const n=DrawLayer._svgFactory.createElement("use");i.append(n);n.setAttribute("href",`#${e}`);n.classList.add("clip");return s}#Co(t,e){for(const[i,s]of Object.entries(e))null===s?t.removeAttribute(i):t.setAttribute(i,s)}draw(t,e=!1,i=!1){const s=this.#y++,n=this.#Eo(),r=DrawLayer._svgFactory.createElement("defs");n.append(r);const a=DrawLayer._svgFactory.createElement("path");r.append(a);const o=`path_p${this.pageIndex}_${s}`;a.setAttribute("id",o);a.setAttribute("vector-effect","non-scaling-stroke");e&&this.#xo.set(s,a);const l=i?this.#So(r,o):null,h=DrawLayer._svgFactory.createElement("use");n.append(h);h.setAttribute("href",`#${o}`);this.updateProperties(n,t);this.#Ao.set(s,n);return{id:s,clipPathId:`url(#${l})`}}drawOutline(t,e){const i=this.#y++,s=this.#Eo(),n=DrawLayer._svgFactory.createElement("defs");s.append(n);const r=DrawLayer._svgFactory.createElement("path");n.append(r);const a=`path_p${this.pageIndex}_${i}`;r.setAttribute("id",a);r.setAttribute("vector-effect","non-scaling-stroke");let o;if(e){const t=DrawLayer._svgFactory.createElement("mask");n.append(t);o=`mask_p${this.pageIndex}_${i}`;t.setAttribute("id",o);t.setAttribute("maskUnits","objectBoundingBox");const e=DrawLayer._svgFactory.createElement("rect");t.append(e);e.setAttribute("width","1");e.setAttribute("height","1");e.setAttribute("fill","white");const s=DrawLayer._svgFactory.createElement("use");t.append(s);s.setAttribute("href",`#${a}`);s.setAttribute("stroke","none");s.setAttribute("fill","black");s.setAttribute("fill-rule","nonzero");s.classList.add("mask")}const l=DrawLayer._svgFactory.createElement("use");s.append(l);l.setAttribute("href",`#${a}`);o&&l.setAttribute("mask",`url(#${o})`);const h=l.cloneNode();s.append(h);l.classList.add("mainOutline");h.classList.add("secondaryOutline");this.updateProperties(s,t);this.#Ao.set(i,s);return i}finalizeDraw(t,e){this.#xo.delete(t);this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:i,bbox:s,rootClass:n,path:r}=e,a="number"==typeof t?this.#Ao.get(t):t;if(a){i&&this.#Co(a,i);s&&DrawLayer.#_o(a,s);if(n){const{classList:t}=a;for(const[e,i]of Object.entries(n))t.toggle(e,i)}if(r){const t=a.firstChild.firstChild;this.#Co(t,r)}}}updateParent(t,e){if(e===this)return;const i=this.#Ao.get(t);if(i){e.#nn.append(i);this.#Ao.delete(t);e.#Ao.set(t,i)}}remove(t){this.#xo.delete(t);if(null!==this.#nn){this.#Ao.get(t).remove();this.#Ao.delete(t)}}destroy(){this.#nn=null;for(const t of this.#Ao.values())t.remove();this.#Ao.clear();this.#xo.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner};var Gt=__webpack_exports__.AbortException,Vt=__webpack_exports__.AnnotationEditorLayer,$t=__webpack_exports__.AnnotationEditorParamsType,Wt=__webpack_exports__.AnnotationEditorType,qt=__webpack_exports__.AnnotationEditorUIManager,Xt=__webpack_exports__.AnnotationLayer,Yt=__webpack_exports__.AnnotationMode,Kt=__webpack_exports__.ColorPicker,Qt=__webpack_exports__.DOMSVGFactory,Jt=__webpack_exports__.DrawLayer,Zt=__webpack_exports__.FeatureTest,te=__webpack_exports__.GlobalWorkerOptions,ee=__webpack_exports__.ImageKind,ie=__webpack_exports__.InvalidPDFException,se=__webpack_exports__.MissingPDFException,ne=__webpack_exports__.OPS,re=__webpack_exports__.OutputScale,ae=__webpack_exports__.PDFDataRangeTransport,oe=__webpack_exports__.PDFDateString,le=__webpack_exports__.PDFWorker,he=__webpack_exports__.PasswordResponses,ce=__webpack_exports__.PermissionFlag,de=__webpack_exports__.PixelsPerInch,ue=__webpack_exports__.RenderingCancelledException,pe=__webpack_exports__.TextLayer,ge=__webpack_exports__.TouchManager,fe=__webpack_exports__.UnexpectedResponseException,me=__webpack_exports__.Util,be=__webpack_exports__.VerbosityLevel,ve=__webpack_exports__.XfaLayer,ye=__webpack_exports__.build,we=__webpack_exports__.createValidAbsoluteUrl,Ae=__webpack_exports__.fetchData,xe=__webpack_exports__.getDocument,_e=__webpack_exports__.getFilenameFromUrl,Ee=__webpack_exports__.getPdfFilenameFromUrl,Se=__webpack_exports__.getXfaPageViewport,Ce=__webpack_exports__.isDataScheme,Te=__webpack_exports__.isPdfFile,Me=__webpack_exports__.noContextMenu,Pe=__webpack_exports__.normalizeUnicode,De=__webpack_exports__.setLayerDimensions,ke=__webpack_exports__.shadow,Re=__webpack_exports__.stopEvent,Ie=__webpack_exports__.version;export{Gt as AbortException,Vt as AnnotationEditorLayer,$t as AnnotationEditorParamsType,Wt as AnnotationEditorType,qt as AnnotationEditorUIManager,Xt as AnnotationLayer,Yt as AnnotationMode,Kt as ColorPicker,Qt as DOMSVGFactory,Jt as DrawLayer,Zt as FeatureTest,te as GlobalWorkerOptions,ee as ImageKind,ie as InvalidPDFException,se as MissingPDFException,ne as OPS,re as OutputScale,ae as PDFDataRangeTransport,oe as PDFDateString,le as PDFWorker,he as PasswordResponses,ce as PermissionFlag,de as PixelsPerInch,ue as RenderingCancelledException,pe as TextLayer,ge as TouchManager,fe as UnexpectedResponseException,me as Util,be as VerbosityLevel,ve as XfaLayer,ye as build,we as createValidAbsoluteUrl,Ae as fetchData,xe as getDocument,_e as getFilenameFromUrl,Ee as getPdfFilenameFromUrl,Se as getXfaPageViewport,Ce as isDataScheme,Te as isPdfFile,Me as noContextMenu,Pe as normalizeUnicode,De as setLayerDimensions,ke as shadow,Re as stopEvent,Ie as version}; \ No newline at end of file diff --git a/apps/gui/ui/vendor/pdf.worker.min.mjs b/apps/gui/ui/vendor/pdf.worker.min.mjs new file mode 100644 index 0000000..c347e56 --- /dev/null +++ b/apps/gui/ui/vendor/pdf.worker.min.mjs @@ -0,0 +1,21 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * Copyright 2024 Mozilla Foundation + * + * 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. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */var e={9306:(e,t,i)=>{var a=i(4901),r=i(6823),s=TypeError;e.exports=function(e){if(a(e))return e;throw new s(r(e)+" is not a function")}},3506:(e,t,i)=>{var a=i(3925),r=String,s=TypeError;e.exports=function(e){if(a(e))return e;throw new s("Can't set "+r(e)+" as a prototype")}},7080:(e,t,i)=>{var a=i(4402).has;e.exports=function(e){a(e);return e}},679:(e,t,i)=>{var a=i(1625),r=TypeError;e.exports=function(e,t){if(a(t,e))return e;throw new r("Incorrect invocation")}},8551:(e,t,i)=>{var a=i(34),r=String,s=TypeError;e.exports=function(e){if(a(e))return e;throw new s(r(e)+" is not an object")}},7811:e=>{e.exports="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView},7394:(e,t,i)=>{var a=i(4576),r=i(6706),s=i(2195),n=a.ArrayBuffer,o=a.TypeError;e.exports=n&&r(n.prototype,"byteLength","get")||function(e){if("ArrayBuffer"!==s(e))throw new o("ArrayBuffer expected");return e.byteLength}},3238:(e,t,i)=>{var a=i(4576),r=i(7476),s=i(7394),n=a.ArrayBuffer,o=n&&n.prototype,g=o&&r(o.slice);e.exports=function(e){if(0!==s(e))return!1;if(!g)return!1;try{g(e,0,0);return!1}catch(e){return!0}}},5169:(e,t,i)=>{var a=i(3238),r=TypeError;e.exports=function(e){if(a(e))throw new r("ArrayBuffer is detached");return e}},5636:(e,t,i)=>{var a=i(4576),r=i(9504),s=i(6706),n=i(7696),o=i(5169),g=i(7394),c=i(4483),l=i(1548),h=a.structuredClone,C=a.ArrayBuffer,Q=a.DataView,E=Math.min,u=C.prototype,d=Q.prototype,f=r(u.slice),p=s(u,"resizable","get"),m=s(u,"maxByteLength","get"),y=r(d.getInt8),w=r(d.setInt8);e.exports=(l||c)&&function(e,t,i){var a,r=g(e),s=void 0===t?r:n(t),u=!p||!p(e);o(e);if(l){e=h(e,{transfer:[e]});if(r===s&&(i||u))return e}if(r>=s&&(!i||u))a=f(e,0,s);else{var d=i&&!u&&m?{maxByteLength:m(e)}:void 0;a=new C(s,d);for(var b=new Q(e),D=new Q(a),S=E(s,r),k=0;k{var a,r,s,n=i(7811),o=i(3724),g=i(4576),c=i(4901),l=i(34),h=i(9297),C=i(6955),Q=i(6823),E=i(6699),u=i(6840),d=i(2106),f=i(1625),p=i(2787),m=i(2967),y=i(8227),w=i(3392),b=i(1181),D=b.enforce,S=b.get,k=g.Int8Array,R=k&&k.prototype,N=g.Uint8ClampedArray,G=N&&N.prototype,M=k&&p(k),U=R&&p(R),x=Object.prototype,L=g.TypeError,H=y("toStringTag"),J=w("TYPED_ARRAY_TAG"),v="TypedArrayConstructor",Y=n&&!!m&&"Opera"!==C(g.opera),K=!1,T={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},q={BigInt64Array:8,BigUint64Array:8},getTypedArrayConstructor=function(e){var t=p(e);if(l(t)){var i=S(t);return i&&h(i,v)?i[v]:getTypedArrayConstructor(t)}},isTypedArray=function(e){if(!l(e))return!1;var t=C(e);return h(T,t)||h(q,t)};for(a in T)(s=(r=g[a])&&r.prototype)?D(s)[v]=r:Y=!1;for(a in q)(s=(r=g[a])&&r.prototype)&&(D(s)[v]=r);if(!Y||!c(M)||M===Function.prototype){M=function TypedArray(){throw new L("Incorrect invocation")};if(Y)for(a in T)g[a]&&m(g[a],M)}if(!Y||!U||U===x){U=M.prototype;if(Y)for(a in T)g[a]&&m(g[a].prototype,U)}Y&&p(G)!==U&&m(G,U);if(o&&!h(U,H)){K=!0;d(U,H,{configurable:!0,get:function(){return l(this)?this[J]:void 0}});for(a in T)g[a]&&E(g[a],J,a)}e.exports={NATIVE_ARRAY_BUFFER_VIEWS:Y,TYPED_ARRAY_TAG:K&&J,aTypedArray:function(e){if(isTypedArray(e))return e;throw new L("Target is not a typed array")},aTypedArrayConstructor:function(e){if(c(e)&&(!m||f(M,e)))return e;throw new L(Q(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,a){if(o){if(i)for(var r in T){var s=g[r];if(s&&h(s.prototype,e))try{delete s.prototype[e]}catch(i){try{s.prototype[e]=t}catch(e){}}}U[e]&&!i||u(U,e,i?t:Y&&R[e]||t,a)}},exportTypedArrayStaticMethod:function(e,t,i){var a,r;if(o){if(m){if(i)for(a in T)if((r=g[a])&&h(r,e))try{delete r[e]}catch(e){}if(M[e]&&!i)return;try{return u(M,e,i?t:Y&&M[e]||t)}catch(e){}}for(a in T)!(r=g[a])||r[e]&&!i||u(r,e,t)}},getTypedArrayConstructor,isView:function isView(e){if(!l(e))return!1;var t=C(e);return"DataView"===t||h(T,t)||h(q,t)},isTypedArray,TypedArray:M,TypedArrayPrototype:U}},5370:(e,t,i)=>{var a=i(6198);e.exports=function(e,t,i){for(var r=0,s=arguments.length>2?i:a(t),n=new e(s);s>r;)n[r]=t[r++];return n}},9617:(e,t,i)=>{var a=i(5397),r=i(5610),s=i(6198),createMethod=function(e){return function(t,i,n){var o=a(t),g=s(o);if(0===g)return!e&&-1;var c,l=r(n,g);if(e&&i!=i){for(;g>l;)if((c=o[l++])!=c)return!0}else for(;g>l;l++)if((e||l in o)&&o[l]===i)return e||l||0;return!e&&-1}};e.exports={includes:createMethod(!0),indexOf:createMethod(!1)}},4527:(e,t,i)=>{var a=i(3724),r=i(4376),s=TypeError,n=Object.getOwnPropertyDescriptor,o=a&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(e){return e instanceof TypeError}}();e.exports=o?function(e,t){if(r(e)&&!n(e,"length").writable)throw new s("Cannot set read only .length");return e.length=t}:function(e,t){return e.length=t}},7680:(e,t,i)=>{var a=i(9504);e.exports=a([].slice)},7628:(e,t,i)=>{var a=i(6198);e.exports=function(e,t){for(var i=a(e),r=new t(i),s=0;s{var a=i(6198),r=i(1291),s=RangeError;e.exports=function(e,t,i,n){var o=a(e),g=r(i),c=g<0?o+g:g;if(c>=o||c<0)throw new s("Incorrect index");for(var l=new t(o),h=0;h{var a=i(8551),r=i(9539);e.exports=function(e,t,i,s){try{return s?t(a(i)[0],i[1]):t(i)}catch(t){r(e,"throw",t)}}},2195:(e,t,i)=>{var a=i(9504),r=a({}.toString),s=a("".slice);e.exports=function(e){return s(r(e),8,-1)}},6955:(e,t,i)=>{var a=i(2140),r=i(4901),s=i(2195),n=i(8227)("toStringTag"),o=Object,g="Arguments"===s(function(){return arguments}());e.exports=a?s:function(e){var t,i,a;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(e){}}(t=o(e),n))?i:g?s(t):"Object"===(a=s(t))&&r(t.callee)?"Arguments":a}},7740:(e,t,i)=>{var a=i(9297),r=i(5031),s=i(7347),n=i(4913);e.exports=function(e,t,i){for(var o=r(t),g=n.f,c=s.f,l=0;l{var a=i(9039);e.exports=!a((function(){function F(){}F.prototype.constructor=null;return Object.getPrototypeOf(new F)!==F.prototype}))},2529:e=>{e.exports=function(e,t){return{value:e,done:t}}},6699:(e,t,i)=>{var a=i(3724),r=i(4913),s=i(6980);e.exports=a?function(e,t,i){return r.f(e,t,s(1,i))}:function(e,t,i){e[t]=i;return e}},6980:e=>{e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},4659:(e,t,i)=>{var a=i(3724),r=i(4913),s=i(6980);e.exports=function(e,t,i){a?r.f(e,t,s(0,i)):e[t]=i}},2106:(e,t,i)=>{var a=i(283),r=i(4913);e.exports=function(e,t,i){i.get&&a(i.get,t,{getter:!0});i.set&&a(i.set,t,{setter:!0});return r.f(e,t,i)}},6840:(e,t,i)=>{var a=i(4901),r=i(4913),s=i(283),n=i(9433);e.exports=function(e,t,i,o){o||(o={});var g=o.enumerable,c=void 0!==o.name?o.name:t;a(i)&&s(i,c,o);if(o.global)g?e[t]=i:n(t,i);else{try{o.unsafe?e[t]&&(g=!0):delete e[t]}catch(e){}g?e[t]=i:r.f(e,t,{value:i,enumerable:!1,configurable:!o.nonConfigurable,writable:!o.nonWritable})}return e}},6279:(e,t,i)=>{var a=i(6840);e.exports=function(e,t,i){for(var r in t)a(e,r,t[r],i);return e}},9433:(e,t,i)=>{var a=i(4576),r=Object.defineProperty;e.exports=function(e,t){try{r(a,e,{value:t,configurable:!0,writable:!0})}catch(i){a[e]=t}return t}},3724:(e,t,i)=>{var a=i(9039);e.exports=!a((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]}))},4483:(e,t,i)=>{var a,r,s,n,o=i(4576),g=i(9429),c=i(1548),l=o.structuredClone,h=o.ArrayBuffer,C=o.MessageChannel,Q=!1;if(c)Q=function(e){l(e,{transfer:[e]})};else if(h)try{C||(a=g("worker_threads"))&&(C=a.MessageChannel);if(C){r=new C;s=new h(2);n=function(e){r.port1.postMessage(null,[e])};if(2===s.byteLength){n(s);0===s.byteLength&&(Q=n)}}}catch(e){}e.exports=Q},4055:(e,t,i)=>{var a=i(4576),r=i(34),s=a.document,n=r(s)&&r(s.createElement);e.exports=function(e){return n?s.createElement(e):{}}},6837:e=>{var t=TypeError;e.exports=function(e){if(e>9007199254740991)throw t("Maximum allowed index exceeded");return e}},5002:e=>{e.exports={IndexSizeError:{s:"INDEX_SIZE_ERR",c:1,m:1},DOMStringSizeError:{s:"DOMSTRING_SIZE_ERR",c:2,m:0},HierarchyRequestError:{s:"HIERARCHY_REQUEST_ERR",c:3,m:1},WrongDocumentError:{s:"WRONG_DOCUMENT_ERR",c:4,m:1},InvalidCharacterError:{s:"INVALID_CHARACTER_ERR",c:5,m:1},NoDataAllowedError:{s:"NO_DATA_ALLOWED_ERR",c:6,m:0},NoModificationAllowedError:{s:"NO_MODIFICATION_ALLOWED_ERR",c:7,m:1},NotFoundError:{s:"NOT_FOUND_ERR",c:8,m:1},NotSupportedError:{s:"NOT_SUPPORTED_ERR",c:9,m:1},InUseAttributeError:{s:"INUSE_ATTRIBUTE_ERR",c:10,m:1},InvalidStateError:{s:"INVALID_STATE_ERR",c:11,m:1},SyntaxError:{s:"SYNTAX_ERR",c:12,m:1},InvalidModificationError:{s:"INVALID_MODIFICATION_ERR",c:13,m:1},NamespaceError:{s:"NAMESPACE_ERR",c:14,m:1},InvalidAccessError:{s:"INVALID_ACCESS_ERR",c:15,m:1},ValidationError:{s:"VALIDATION_ERR",c:16,m:0},TypeMismatchError:{s:"TYPE_MISMATCH_ERR",c:17,m:1},SecurityError:{s:"SECURITY_ERR",c:18,m:1},NetworkError:{s:"NETWORK_ERR",c:19,m:1},AbortError:{s:"ABORT_ERR",c:20,m:1},URLMismatchError:{s:"URL_MISMATCH_ERR",c:21,m:1},QuotaExceededError:{s:"QUOTA_EXCEEDED_ERR",c:22,m:1},TimeoutError:{s:"TIMEOUT_ERR",c:23,m:1},InvalidNodeTypeError:{s:"INVALID_NODE_TYPE_ERR",c:24,m:1},DataCloneError:{s:"DATA_CLONE_ERR",c:25,m:1}}},8727:e=>{e.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},6193:(e,t,i)=>{var a=i(4215);e.exports="NODE"===a},2839:(e,t,i)=>{var a=i(4576).navigator,r=a&&a.userAgent;e.exports=r?String(r):""},9519:(e,t,i)=>{var a,r,s=i(4576),n=i(2839),o=s.process,g=s.Deno,c=o&&o.versions||g&&g.version,l=c&&c.v8;l&&(r=(a=l.split("."))[0]>0&&a[0]<4?1:+(a[0]+a[1]));!r&&n&&(!(a=n.match(/Edge\/(\d+)/))||a[1]>=74)&&(a=n.match(/Chrome\/(\d+)/))&&(r=+a[1]);e.exports=r},4215:(e,t,i)=>{var a=i(4576),r=i(2839),s=i(2195),userAgentStartsWith=function(e){return r.slice(0,e.length)===e};e.exports=userAgentStartsWith("Bun/")?"BUN":userAgentStartsWith("Cloudflare-Workers")?"CLOUDFLARE":userAgentStartsWith("Deno/")?"DENO":userAgentStartsWith("Node.js/")?"NODE":a.Bun&&"string"==typeof Bun.version?"BUN":a.Deno&&"object"==typeof Deno.version?"DENO":"process"===s(a.process)?"NODE":a.window&&a.document?"BROWSER":"REST"},8574:(e,t,i)=>{var a=i(9504),r=Error,s=a("".replace),n=String(new r("zxcasd").stack),o=/\n\s*at [^:]*:[^\n]*/,g=o.test(n);e.exports=function(e,t){if(g&&"string"==typeof e&&!r.prepareStackTrace)for(;t--;)e=s(e,o,"");return e}},6518:(e,t,i)=>{var a=i(4576),r=i(7347).f,s=i(6699),n=i(6840),o=i(9433),g=i(7740),c=i(2796);e.exports=function(e,t){var i,l,h,C,Q,E=e.target,u=e.global,d=e.stat;if(i=u?a:d?a[E]||o(E,{}):a[E]&&a[E].prototype)for(l in t){C=t[l];h=e.dontCallGetSet?(Q=r(i,l))&&Q.value:i[l];if(!c(u?l:E+(d?".":"#")+l,e.forced)&&void 0!==h){if(typeof C==typeof h)continue;g(C,h)}(e.sham||h&&h.sham)&&s(C,"sham",!0);n(i,l,C,e)}}},9039:e=>{e.exports=function(e){try{return!!e()}catch(e){return!0}}},8745:(e,t,i)=>{var a=i(616),r=Function.prototype,s=r.apply,n=r.call;e.exports="object"==typeof Reflect&&Reflect.apply||(a?n.bind(s):function(){return n.apply(s,arguments)})},6080:(e,t,i)=>{var a=i(7476),r=i(9306),s=i(616),n=a(a.bind);e.exports=function(e,t){r(e);return void 0===t?e:s?n(e,t):function(){return e.apply(t,arguments)}}},616:(e,t,i)=>{var a=i(9039);e.exports=!a((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")}))},9565:(e,t,i)=>{var a=i(616),r=Function.prototype.call;e.exports=a?r.bind(r):function(){return r.apply(r,arguments)}},350:(e,t,i)=>{var a=i(3724),r=i(9297),s=Function.prototype,n=a&&Object.getOwnPropertyDescriptor,o=r(s,"name"),g=o&&"something"===function something(){}.name,c=o&&(!a||a&&n(s,"name").configurable);e.exports={EXISTS:o,PROPER:g,CONFIGURABLE:c}},6706:(e,t,i)=>{var a=i(9504),r=i(9306);e.exports=function(e,t,i){try{return a(r(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(e){}}},7476:(e,t,i)=>{var a=i(2195),r=i(9504);e.exports=function(e){if("Function"===a(e))return r(e)}},9504:(e,t,i)=>{var a=i(616),r=Function.prototype,s=r.call,n=a&&r.bind.bind(s,s);e.exports=a?n:function(e){return function(){return s.apply(e,arguments)}}},9429:(e,t,i)=>{var a=i(4576),r=i(6193);e.exports=function(e){if(r){try{return a.process.getBuiltinModule(e)}catch(e){}try{return Function('return require("'+e+'")')()}catch(e){}}}},7751:(e,t,i)=>{var a=i(4576),r=i(4901);e.exports=function(e,t){return arguments.length<2?(i=a[e],r(i)?i:void 0):a[e]&&a[e][t];var i}},1767:e=>{e.exports=function(e){return{iterator:e,next:e.next,done:!1}}},851:(e,t,i)=>{var a=i(6955),r=i(5966),s=i(4117),n=i(6269),o=i(8227)("iterator");e.exports=function(e){if(!s(e))return r(e,o)||r(e,"@@iterator")||n[a(e)]}},81:(e,t,i)=>{var a=i(9565),r=i(9306),s=i(8551),n=i(6823),o=i(851),g=TypeError;e.exports=function(e,t){var i=arguments.length<2?o(e):t;if(r(i))return s(a(i,e));throw new g(n(e)+" is not iterable")}},5966:(e,t,i)=>{var a=i(9306),r=i(4117);e.exports=function(e,t){var i=e[t];return r(i)?void 0:a(i)}},3789:(e,t,i)=>{var a=i(9306),r=i(8551),s=i(9565),n=i(1291),o=i(1767),g="Invalid size",c=RangeError,l=TypeError,h=Math.max,SetRecord=function(e,t){this.set=e;this.size=h(t,0);this.has=a(e.has);this.keys=a(e.keys)};SetRecord.prototype={getIterator:function(){return o(r(s(this.keys,this.set)))},includes:function(e){return s(this.has,this.set,e)}};e.exports=function(e){r(e);var t=+e.size;if(t!=t)throw new l(g);var i=n(t);if(i<0)throw new c(g);return new SetRecord(e,i)}},4576:function(e){var check=function(e){return e&&e.Math===Math&&e};e.exports=check("object"==typeof globalThis&&globalThis)||check("object"==typeof window&&window)||check("object"==typeof self&&self)||check("object"==typeof global&&global)||check("object"==typeof this&&this)||function(){return this}()||Function("return this")()},9297:(e,t,i)=>{var a=i(9504),r=i(8981),s=a({}.hasOwnProperty);e.exports=Object.hasOwn||function hasOwn(e,t){return s(r(e),t)}},421:e=>{e.exports={}},397:(e,t,i)=>{var a=i(7751);e.exports=a("document","documentElement")},5917:(e,t,i)=>{var a=i(3724),r=i(9039),s=i(4055);e.exports=!a&&!r((function(){return 7!==Object.defineProperty(s("div"),"a",{get:function(){return 7}}).a}))},7055:(e,t,i)=>{var a=i(9504),r=i(9039),s=i(2195),n=Object,o=a("".split);e.exports=r((function(){return!n("z").propertyIsEnumerable(0)}))?function(e){return"String"===s(e)?o(e,""):n(e)}:n},3167:(e,t,i)=>{var a=i(4901),r=i(34),s=i(2967);e.exports=function(e,t,i){var n,o;s&&a(n=t.constructor)&&n!==i&&r(o=n.prototype)&&o!==i.prototype&&s(e,o);return e}},3706:(e,t,i)=>{var a=i(9504),r=i(4901),s=i(7629),n=a(Function.toString);r(s.inspectSource)||(s.inspectSource=function(e){return n(e)});e.exports=s.inspectSource},1181:(e,t,i)=>{var a,r,s,n=i(8622),o=i(4576),g=i(34),c=i(6699),l=i(9297),h=i(7629),C=i(6119),Q=i(421),E="Object already initialized",u=o.TypeError,d=o.WeakMap;if(n||h.state){var f=h.state||(h.state=new d);f.get=f.get;f.has=f.has;f.set=f.set;a=function(e,t){if(f.has(e))throw new u(E);t.facade=e;f.set(e,t);return t};r=function(e){return f.get(e)||{}};s=function(e){return f.has(e)}}else{var p=C("state");Q[p]=!0;a=function(e,t){if(l(e,p))throw new u(E);t.facade=e;c(e,p,t);return t};r=function(e){return l(e,p)?e[p]:{}};s=function(e){return l(e,p)}}e.exports={set:a,get:r,has:s,enforce:function(e){return s(e)?r(e):a(e,{})},getterFor:function(e){return function(t){var i;if(!g(t)||(i=r(t)).type!==e)throw new u("Incompatible receiver, "+e+" required");return i}}}},4209:(e,t,i)=>{var a=i(8227),r=i(6269),s=a("iterator"),n=Array.prototype;e.exports=function(e){return void 0!==e&&(r.Array===e||n[s]===e)}},4376:(e,t,i)=>{var a=i(2195);e.exports=Array.isArray||function isArray(e){return"Array"===a(e)}},1108:(e,t,i)=>{var a=i(6955);e.exports=function(e){var t=a(e);return"BigInt64Array"===t||"BigUint64Array"===t}},4901:e=>{var t="object"==typeof document&&document.all;e.exports=void 0===t&&void 0!==t?function(e){return"function"==typeof e||e===t}:function(e){return"function"==typeof e}},2796:(e,t,i)=>{var a=i(9039),r=i(4901),s=/#|\.prototype\./,isForced=function(e,t){var i=o[n(e)];return i===c||i!==g&&(r(t)?a(t):!!t)},n=isForced.normalize=function(e){return String(e).replace(s,".").toLowerCase()},o=isForced.data={},g=isForced.NATIVE="N",c=isForced.POLYFILL="P";e.exports=isForced},4117:e=>{e.exports=function(e){return null==e}},34:(e,t,i)=>{var a=i(4901);e.exports=function(e){return"object"==typeof e?null!==e:a(e)}},3925:(e,t,i)=>{var a=i(34);e.exports=function(e){return a(e)||null===e}},6395:e=>{e.exports=!1},757:(e,t,i)=>{var a=i(7751),r=i(4901),s=i(1625),n=i(7040),o=Object;e.exports=n?function(e){return"symbol"==typeof e}:function(e){var t=a("Symbol");return r(t)&&s(t.prototype,o(e))}},507:(e,t,i)=>{var a=i(9565);e.exports=function(e,t,i){for(var r,s,n=i?e:e.iterator,o=e.next;!(r=a(o,n)).done;)if(void 0!==(s=t(r.value)))return s}},2652:(e,t,i)=>{var a=i(6080),r=i(9565),s=i(8551),n=i(6823),o=i(4209),g=i(6198),c=i(1625),l=i(81),h=i(851),C=i(9539),Q=TypeError,Result=function(e,t){this.stopped=e;this.result=t},E=Result.prototype;e.exports=function(e,t,i){var u,d,f,p,m,y,w,b=i&&i.that,D=!(!i||!i.AS_ENTRIES),S=!(!i||!i.IS_RECORD),k=!(!i||!i.IS_ITERATOR),R=!(!i||!i.INTERRUPTED),N=a(t,b),stop=function(e){u&&C(u,"normal",e);return new Result(!0,e)},callFn=function(e){if(D){s(e);return R?N(e[0],e[1],stop):N(e[0],e[1])}return R?N(e,stop):N(e)};if(S)u=e.iterator;else if(k)u=e;else{if(!(d=h(e)))throw new Q(n(e)+" is not iterable");if(o(d)){for(f=0,p=g(e);p>f;f++)if((m=callFn(e[f]))&&c(E,m))return m;return new Result(!1)}u=l(e,d)}y=S?e.next:u.next;for(;!(w=r(y,u)).done;){try{m=callFn(w.value)}catch(e){C(u,"throw",e)}if("object"==typeof m&&m&&c(E,m))return m}return new Result(!1)}},9539:(e,t,i)=>{var a=i(9565),r=i(8551),s=i(5966);e.exports=function(e,t,i){var n,o;r(e);try{if(!(n=s(e,"return"))){if("throw"===t)throw i;return i}n=a(n,e)}catch(e){o=!0;n=e}if("throw"===t)throw i;if(o)throw n;r(n);return i}},9462:(e,t,i)=>{var a=i(9565),r=i(2360),s=i(6699),n=i(6279),o=i(8227),g=i(1181),c=i(5966),l=i(7657).IteratorPrototype,h=i(2529),C=i(9539),Q=o("toStringTag"),E="IteratorHelper",u="WrapForValidIterator",d=g.set,createIteratorProxyPrototype=function(e){var t=g.getterFor(e?u:E);return n(r(l),{next:function next(){var i=t(this);if(e)return i.nextHandler();try{var a=i.done?void 0:i.nextHandler();return h(a,i.done)}catch(e){i.done=!0;throw e}},return:function(){var i=t(this),r=i.iterator;i.done=!0;if(e){var s=c(r,"return");return s?a(s,r):h(void 0,!0)}if(i.inner)try{C(i.inner.iterator,"normal")}catch(e){return C(r,"throw",e)}r&&C(r,"normal");return h(void 0,!0)}})},f=createIteratorProxyPrototype(!0),p=createIteratorProxyPrototype(!1);s(p,Q,"Iterator Helper");e.exports=function(e,t){var i=function Iterator(i,a){if(a){a.iterator=i.iterator;a.next=i.next}else a=i;a.type=t?u:E;a.nextHandler=e;a.counter=0;a.done=!1;d(this,a)};i.prototype=t?f:p;return i}},713:(e,t,i)=>{var a=i(9565),r=i(9306),s=i(8551),n=i(1767),o=i(9462),g=i(6319),c=o((function(){var e=this.iterator,t=s(a(this.next,e));if(!(this.done=!!t.done))return g(e,this.mapper,[t.value,this.counter++],!0)}));e.exports=function map(e){s(this);r(e);return new c(n(this),{mapper:e})}},7657:(e,t,i)=>{var a,r,s,n=i(9039),o=i(4901),g=i(34),c=i(2360),l=i(2787),h=i(6840),C=i(8227),Q=i(6395),E=C("iterator"),u=!1;[].keys&&("next"in(s=[].keys())?(r=l(l(s)))!==Object.prototype&&(a=r):u=!0);!g(a)||n((function(){var e={};return a[E].call(e)!==e}))?a={}:Q&&(a=c(a));o(a[E])||h(a,E,(function(){return this}));e.exports={IteratorPrototype:a,BUGGY_SAFARI_ITERATORS:u}},6269:e=>{e.exports={}},6198:(e,t,i)=>{var a=i(8014);e.exports=function(e){return a(e.length)}},283:(e,t,i)=>{var a=i(9504),r=i(9039),s=i(4901),n=i(9297),o=i(3724),g=i(350).CONFIGURABLE,c=i(3706),l=i(1181),h=l.enforce,C=l.get,Q=String,E=Object.defineProperty,u=a("".slice),d=a("".replace),f=a([].join),p=o&&!r((function(){return 8!==E((function(){}),"length",{value:8}).length})),m=String(String).split("String"),y=e.exports=function(e,t,i){"Symbol("===u(Q(t),0,7)&&(t="["+d(Q(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]");i&&i.getter&&(t="get "+t);i&&i.setter&&(t="set "+t);(!n(e,"name")||g&&e.name!==t)&&(o?E(e,"name",{value:t,configurable:!0}):e.name=t);p&&i&&n(i,"arity")&&e.length!==i.arity&&E(e,"length",{value:i.arity});try{i&&n(i,"constructor")&&i.constructor?o&&E(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(e){}var a=h(e);n(a,"source")||(a.source=f(m,"string"==typeof t?t:""));return e};Function.prototype.toString=y((function toString(){return s(this)&&C(this).source||c(this)}),"toString")},741:e=>{var t=Math.ceil,i=Math.floor;e.exports=Math.trunc||function trunc(e){var a=+e;return(a>0?i:t)(a)}},6043:(e,t,i)=>{var a=i(9306),r=TypeError,PromiseCapability=function(e){var t,i;this.promise=new e((function(e,a){if(void 0!==t||void 0!==i)throw new r("Bad Promise constructor");t=e;i=a}));this.resolve=a(t);this.reject=a(i)};e.exports.f=function(e){return new PromiseCapability(e)}},2603:(e,t,i)=>{var a=i(655);e.exports=function(e,t){return void 0===e?arguments.length<2?"":t:a(e)}},2360:(e,t,i)=>{var a,r=i(8551),s=i(6801),n=i(8727),o=i(421),g=i(397),c=i(4055),l=i(6119),h="prototype",C="script",Q=l("IE_PROTO"),EmptyConstructor=function(){},scriptTag=function(e){return"<"+C+">"+e+""},NullProtoObjectViaActiveX=function(e){e.write(scriptTag(""));e.close();var t=e.parentWindow.Object;e=null;return t},NullProtoObject=function(){try{a=new ActiveXObject("htmlfile")}catch(e){}NullProtoObject="undefined"!=typeof document?document.domain&&a?NullProtoObjectViaActiveX(a):function(){var e,t=c("iframe"),i="java"+C+":";t.style.display="none";g.appendChild(t);t.src=String(i);(e=t.contentWindow.document).open();e.write(scriptTag("document.F=Object"));e.close();return e.F}():NullProtoObjectViaActiveX(a);for(var e=n.length;e--;)delete NullProtoObject[h][n[e]];return NullProtoObject()};o[Q]=!0;e.exports=Object.create||function create(e,t){var i;if(null!==e){EmptyConstructor[h]=r(e);i=new EmptyConstructor;EmptyConstructor[h]=null;i[Q]=e}else i=NullProtoObject();return void 0===t?i:s.f(i,t)}},6801:(e,t,i)=>{var a=i(3724),r=i(8686),s=i(4913),n=i(8551),o=i(5397),g=i(1072);t.f=a&&!r?Object.defineProperties:function defineProperties(e,t){n(e);for(var i,a=o(t),r=g(t),c=r.length,l=0;c>l;)s.f(e,i=r[l++],a[i]);return e}},4913:(e,t,i)=>{var a=i(3724),r=i(5917),s=i(8686),n=i(8551),o=i(6969),g=TypeError,c=Object.defineProperty,l=Object.getOwnPropertyDescriptor,h="enumerable",C="configurable",Q="writable";t.f=a?s?function defineProperty(e,t,i){n(e);t=o(t);n(i);if("function"==typeof e&&"prototype"===t&&"value"in i&&Q in i&&!i[Q]){var a=l(e,t);if(a&&a[Q]){e[t]=i.value;i={configurable:C in i?i[C]:a[C],enumerable:h in i?i[h]:a[h],writable:!1}}}return c(e,t,i)}:c:function defineProperty(e,t,i){n(e);t=o(t);n(i);if(r)try{return c(e,t,i)}catch(e){}if("get"in i||"set"in i)throw new g("Accessors not supported");"value"in i&&(e[t]=i.value);return e}},7347:(e,t,i)=>{var a=i(3724),r=i(9565),s=i(8773),n=i(6980),o=i(5397),g=i(6969),c=i(9297),l=i(5917),h=Object.getOwnPropertyDescriptor;t.f=a?h:function getOwnPropertyDescriptor(e,t){e=o(e);t=g(t);if(l)try{return h(e,t)}catch(e){}if(c(e,t))return n(!r(s.f,e,t),e[t])}},8480:(e,t,i)=>{var a=i(1828),r=i(8727).concat("length","prototype");t.f=Object.getOwnPropertyNames||function getOwnPropertyNames(e){return a(e,r)}},3717:(e,t)=>{t.f=Object.getOwnPropertySymbols},2787:(e,t,i)=>{var a=i(9297),r=i(4901),s=i(8981),n=i(6119),o=i(2211),g=n("IE_PROTO"),c=Object,l=c.prototype;e.exports=o?c.getPrototypeOf:function(e){var t=s(e);if(a(t,g))return t[g];var i=t.constructor;return r(i)&&t instanceof i?i.prototype:t instanceof c?l:null}},1625:(e,t,i)=>{var a=i(9504);e.exports=a({}.isPrototypeOf)},1828:(e,t,i)=>{var a=i(9504),r=i(9297),s=i(5397),n=i(9617).indexOf,o=i(421),g=a([].push);e.exports=function(e,t){var i,a=s(e),c=0,l=[];for(i in a)!r(o,i)&&r(a,i)&&g(l,i);for(;t.length>c;)r(a,i=t[c++])&&(~n(l,i)||g(l,i));return l}},1072:(e,t,i)=>{var a=i(1828),r=i(8727);e.exports=Object.keys||function keys(e){return a(e,r)}},8773:(e,t)=>{var i={}.propertyIsEnumerable,a=Object.getOwnPropertyDescriptor,r=a&&!i.call({1:2},1);t.f=r?function propertyIsEnumerable(e){var t=a(this,e);return!!t&&t.enumerable}:i},2967:(e,t,i)=>{var a=i(6706),r=i(34),s=i(7750),n=i(3506);e.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=a(Object.prototype,"__proto__","set"))(i,[]);t=i instanceof Array}catch(e){}return function setPrototypeOf(i,a){s(i);n(a);if(!r(i))return i;t?e(i,a):i.__proto__=a;return i}}():void 0)},4270:(e,t,i)=>{var a=i(9565),r=i(4901),s=i(34),n=TypeError;e.exports=function(e,t){var i,o;if("string"===t&&r(i=e.toString)&&!s(o=a(i,e)))return o;if(r(i=e.valueOf)&&!s(o=a(i,e)))return o;if("string"!==t&&r(i=e.toString)&&!s(o=a(i,e)))return o;throw new n("Can't convert object to primitive value")}},5031:(e,t,i)=>{var a=i(7751),r=i(9504),s=i(8480),n=i(3717),o=i(8551),g=r([].concat);e.exports=a("Reflect","ownKeys")||function ownKeys(e){var t=s.f(o(e)),i=n.f;return i?g(t,i(e)):t}},1103:e=>{e.exports=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}}},7979:(e,t,i)=>{var a=i(8551);e.exports=function(){var e=a(this),t="";e.hasIndices&&(t+="d");e.global&&(t+="g");e.ignoreCase&&(t+="i");e.multiline&&(t+="m");e.dotAll&&(t+="s");e.unicode&&(t+="u");e.unicodeSets&&(t+="v");e.sticky&&(t+="y");return t}},7750:(e,t,i)=>{var a=i(4117),r=TypeError;e.exports=function(e){if(a(e))throw new r("Can't call method on "+e);return e}},9286:(e,t,i)=>{var a=i(4402),r=i(8469),s=a.Set,n=a.add;e.exports=function(e){var t=new s;r(e,(function(e){n(t,e)}));return t}},3440:(e,t,i)=>{var a=i(7080),r=i(4402),s=i(9286),n=i(5170),o=i(3789),g=i(8469),c=i(507),l=r.has,h=r.remove;e.exports=function difference(e){var t=a(this),i=o(e),r=s(t);n(t)<=i.size?g(t,(function(e){i.includes(e)&&h(r,e)})):c(i.getIterator(),(function(e){l(t,e)&&h(r,e)}));return r}},4402:(e,t,i)=>{var a=i(9504),r=Set.prototype;e.exports={Set,add:a(r.add),has:a(r.has),remove:a(r.delete),proto:r}},8750:(e,t,i)=>{var a=i(7080),r=i(4402),s=i(5170),n=i(3789),o=i(8469),g=i(507),c=r.Set,l=r.add,h=r.has;e.exports=function intersection(e){var t=a(this),i=n(e),r=new c;s(t)>i.size?g(i.getIterator(),(function(e){h(t,e)&&l(r,e)})):o(t,(function(e){i.includes(e)&&l(r,e)}));return r}},4449:(e,t,i)=>{var a=i(7080),r=i(4402).has,s=i(5170),n=i(3789),o=i(8469),g=i(507),c=i(9539);e.exports=function isDisjointFrom(e){var t=a(this),i=n(e);if(s(t)<=i.size)return!1!==o(t,(function(e){if(i.includes(e))return!1}),!0);var l=i.getIterator();return!1!==g(l,(function(e){if(r(t,e))return c(l,"normal",!1)}))}},3838:(e,t,i)=>{var a=i(7080),r=i(5170),s=i(8469),n=i(3789);e.exports=function isSubsetOf(e){var t=a(this),i=n(e);return!(r(t)>i.size)&&!1!==s(t,(function(e){if(!i.includes(e))return!1}),!0)}},8527:(e,t,i)=>{var a=i(7080),r=i(4402).has,s=i(5170),n=i(3789),o=i(507),g=i(9539);e.exports=function isSupersetOf(e){var t=a(this),i=n(e);if(s(t){var a=i(9504),r=i(507),s=i(4402),n=s.Set,o=s.proto,g=a(o.forEach),c=a(o.keys),l=c(new n).next;e.exports=function(e,t,i){return i?r({iterator:c(e),next:l},t):g(e,t)}},4916:(e,t,i)=>{var a=i(7751),createSetLike=function(e){return{size:e,has:function(){return!1},keys:function(){return{next:function(){return{done:!0}}}}}};e.exports=function(e){var t=a("Set");try{(new t)[e](createSetLike(0));try{(new t)[e](createSetLike(-1));return!1}catch(e){return!0}}catch(e){return!1}}},5170:(e,t,i)=>{var a=i(6706),r=i(4402);e.exports=a(r.proto,"size","get")||function(e){return e.size}},3650:(e,t,i)=>{var a=i(7080),r=i(4402),s=i(9286),n=i(3789),o=i(507),g=r.add,c=r.has,l=r.remove;e.exports=function symmetricDifference(e){var t=a(this),i=n(e).getIterator(),r=s(t);o(i,(function(e){c(t,e)?l(r,e):g(r,e)}));return r}},4204:(e,t,i)=>{var a=i(7080),r=i(4402).add,s=i(9286),n=i(3789),o=i(507);e.exports=function union(e){var t=a(this),i=n(e).getIterator(),g=s(t);o(i,(function(e){r(g,e)}));return g}},6119:(e,t,i)=>{var a=i(5745),r=i(3392),s=a("keys");e.exports=function(e){return s[e]||(s[e]=r(e))}},7629:(e,t,i)=>{var a=i(6395),r=i(4576),s=i(9433),n="__core-js_shared__",o=e.exports=r[n]||s(n,{});(o.versions||(o.versions=[])).push({version:"3.39.0",mode:a?"pure":"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.39.0/LICENSE",source:"https://github.com/zloirock/core-js"})},5745:(e,t,i)=>{var a=i(7629);e.exports=function(e,t){return a[e]||(a[e]=t||{})}},1548:(e,t,i)=>{var a=i(4576),r=i(9039),s=i(9519),n=i(4215),o=a.structuredClone;e.exports=!!o&&!r((function(){if("DENO"===n&&s>92||"NODE"===n&&s>94||"BROWSER"===n&&s>97)return!1;var e=new ArrayBuffer(8),t=o(e,{transfer:[e]});return 0!==e.byteLength||8!==t.byteLength}))},4495:(e,t,i)=>{var a=i(9519),r=i(9039),s=i(4576).String;e.exports=!!Object.getOwnPropertySymbols&&!r((function(){var e=Symbol("symbol detection");return!s(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&a&&a<41}))},5610:(e,t,i)=>{var a=i(1291),r=Math.max,s=Math.min;e.exports=function(e,t){var i=a(e);return i<0?r(i+t,0):s(i,t)}},5854:(e,t,i)=>{var a=i(2777),r=TypeError;e.exports=function(e){var t=a(e,"number");if("number"==typeof t)throw new r("Can't convert number to bigint");return BigInt(t)}},7696:(e,t,i)=>{var a=i(1291),r=i(8014),s=RangeError;e.exports=function(e){if(void 0===e)return 0;var t=a(e),i=r(t);if(t!==i)throw new s("Wrong length or index");return i}},5397:(e,t,i)=>{var a=i(7055),r=i(7750);e.exports=function(e){return a(r(e))}},1291:(e,t,i)=>{var a=i(741);e.exports=function(e){var t=+e;return t!=t||0===t?0:a(t)}},8014:(e,t,i)=>{var a=i(1291),r=Math.min;e.exports=function(e){var t=a(e);return t>0?r(t,9007199254740991):0}},8981:(e,t,i)=>{var a=i(7750),r=Object;e.exports=function(e){return r(a(e))}},2777:(e,t,i)=>{var a=i(9565),r=i(34),s=i(757),n=i(5966),o=i(4270),g=i(8227),c=TypeError,l=g("toPrimitive");e.exports=function(e,t){if(!r(e)||s(e))return e;var i,g=n(e,l);if(g){void 0===t&&(t="default");i=a(g,e,t);if(!r(i)||s(i))return i;throw new c("Can't convert object to primitive value")}void 0===t&&(t="number");return o(e,t)}},6969:(e,t,i)=>{var a=i(2777),r=i(757);e.exports=function(e){var t=a(e,"string");return r(t)?t:t+""}},2140:(e,t,i)=>{var a={};a[i(8227)("toStringTag")]="z";e.exports="[object z]"===String(a)},655:(e,t,i)=>{var a=i(6955),r=String;e.exports=function(e){if("Symbol"===a(e))throw new TypeError("Cannot convert a Symbol value to a string");return r(e)}},6823:e=>{var t=String;e.exports=function(e){try{return t(e)}catch(e){return"Object"}}},3392:(e,t,i)=>{var a=i(9504),r=0,s=Math.random(),n=a(1..toString);e.exports=function(e){return"Symbol("+(void 0===e?"":e)+")_"+n(++r+s,36)}},7040:(e,t,i)=>{var a=i(4495);e.exports=a&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},8686:(e,t,i)=>{var a=i(3724),r=i(9039);e.exports=a&&r((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype}))},2812:e=>{var t=TypeError;e.exports=function(e,i){if(e{var a=i(4576),r=i(4901),s=a.WeakMap;e.exports=r(s)&&/native code/.test(String(s))},8227:(e,t,i)=>{var a=i(4576),r=i(5745),s=i(9297),n=i(3392),o=i(4495),g=i(7040),c=a.Symbol,l=r("wks"),h=g?c.for||c:c&&c.withoutSetter||n;e.exports=function(e){s(l,e)||(l[e]=o&&s(c,e)?c[e]:h("Symbol."+e));return l[e]}},6573:(e,t,i)=>{var a=i(3724),r=i(2106),s=i(3238),n=ArrayBuffer.prototype;a&&!("detached"in n)&&r(n,"detached",{configurable:!0,get:function detached(){return s(this)}})},7936:(e,t,i)=>{var a=i(6518),r=i(5636);r&&a({target:"ArrayBuffer",proto:!0},{transferToFixedLength:function transferToFixedLength(){return r(this,arguments.length?arguments[0]:void 0,!1)}})},8100:(e,t,i)=>{var a=i(6518),r=i(5636);r&&a({target:"ArrayBuffer",proto:!0},{transfer:function transfer(){return r(this,arguments.length?arguments[0]:void 0,!0)}})},4114:(e,t,i)=>{var a=i(6518),r=i(8981),s=i(6198),n=i(4527),o=i(6837);a({target:"Array",proto:!0,arity:1,forced:i(9039)((function(){return 4294967297!==[].push.call({length:4294967296},1)}))||!function(){try{Object.defineProperty([],"length",{writable:!1}).push()}catch(e){return e instanceof TypeError}}()},{push:function push(e){var t=r(this),i=s(t),a=arguments.length;o(i+a);for(var g=0;g{var a=i(6518),r=i(4576),s=i(679),n=i(8551),o=i(4901),g=i(2787),c=i(2106),l=i(4659),h=i(9039),C=i(9297),Q=i(8227),E=i(7657).IteratorPrototype,u=i(3724),d=i(6395),f="constructor",p="Iterator",m=Q("toStringTag"),y=TypeError,w=r[p],b=d||!o(w)||w.prototype!==E||!h((function(){w({})})),D=function Iterator(){s(this,E);if(g(this)===E)throw new y("Abstract class Iterator not directly constructable")},defineIteratorPrototypeAccessor=function(e,t){u?c(E,e,{configurable:!0,get:function(){return t},set:function(t){n(this);if(this===E)throw new y("You can't redefine this property");C(this,e)?this[e]=t:l(this,e,t)}}):E[e]=t};C(E,m)||defineIteratorPrototypeAccessor(m,p);!b&&C(E,f)&&E[f]!==Object||defineIteratorPrototypeAccessor(f,D);D.prototype=E;a({global:!0,constructor:!0,forced:b},{Iterator:D})},1148:(e,t,i)=>{var a=i(6518),r=i(2652),s=i(9306),n=i(8551),o=i(1767);a({target:"Iterator",proto:!0,real:!0},{every:function every(e){n(this);s(e);var t=o(this),i=0;return!r(t,(function(t,a){if(!e(t,i++))return a()}),{IS_RECORD:!0,INTERRUPTED:!0}).stopped}})},2489:(e,t,i)=>{var a=i(6518),r=i(9565),s=i(9306),n=i(8551),o=i(1767),g=i(9462),c=i(6319),l=i(6395),h=g((function(){for(var e,t,i=this.iterator,a=this.predicate,s=this.next;;){e=n(r(s,i));if(this.done=!!e.done)return;t=e.value;if(c(i,a,[t,this.counter++],!0))return t}}));a({target:"Iterator",proto:!0,real:!0,forced:l},{filter:function filter(e){n(this);s(e);return new h(o(this),{predicate:e})}})},116:(e,t,i)=>{var a=i(6518),r=i(2652),s=i(9306),n=i(8551),o=i(1767);a({target:"Iterator",proto:!0,real:!0},{find:function find(e){n(this);s(e);var t=o(this),i=0;return r(t,(function(t,a){if(e(t,i++))return a(t)}),{IS_RECORD:!0,INTERRUPTED:!0}).result}})},7588:(e,t,i)=>{var a=i(6518),r=i(2652),s=i(9306),n=i(8551),o=i(1767);a({target:"Iterator",proto:!0,real:!0},{forEach:function forEach(e){n(this);s(e);var t=o(this),i=0;r(t,(function(t){e(t,i++)}),{IS_RECORD:!0})}})},1701:(e,t,i)=>{var a=i(6518),r=i(713);a({target:"Iterator",proto:!0,real:!0,forced:i(6395)},{map:r})},8237:(e,t,i)=>{var a=i(6518),r=i(2652),s=i(9306),n=i(8551),o=i(1767),g=TypeError;a({target:"Iterator",proto:!0,real:!0},{reduce:function reduce(e){n(this);s(e);var t=o(this),i=arguments.length<2,a=i?void 0:arguments[1],c=0;r(t,(function(t){if(i){i=!1;a=t}else a=e(a,t,c);c++}),{IS_RECORD:!0});if(i)throw new g("Reduce of empty iterator with no initial value");return a}})},3579:(e,t,i)=>{var a=i(6518),r=i(2652),s=i(9306),n=i(8551),o=i(1767);a({target:"Iterator",proto:!0,real:!0},{some:function some(e){n(this);s(e);var t=o(this),i=0;return r(t,(function(t,a){if(e(t,i++))return a()}),{IS_RECORD:!0,INTERRUPTED:!0}).stopped}})},1806:(e,t,i)=>{var a=i(6518),r=i(8551),s=i(2652),n=i(1767),o=[].push;a({target:"Iterator",proto:!0,real:!0},{toArray:function toArray(){var e=[];s(n(r(this)),o,{that:e,IS_RECORD:!0});return e}})},1689:(e,t,i)=>{var a=i(6518),r=i(4576),s=i(8745),n=i(7680),o=i(6043),g=i(9306),c=i(1103),l=r.Promise,h=!1;a({target:"Promise",stat:!0,forced:!l||!l.try||c((function(){l.try((function(e){h=8===e}),8)})).error||!h},{try:function(e){var t=arguments.length>1?n(arguments,1):[],i=o.f(this),a=c((function(){return s(g(e),void 0,t)}));(a.error?i.reject:i.resolve)(a.value);return i.promise}})},4628:(e,t,i)=>{var a=i(6518),r=i(6043);a({target:"Promise",stat:!0},{withResolvers:function withResolvers(){var e=r.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}})},9479:(e,t,i)=>{var a=i(4576),r=i(3724),s=i(2106),n=i(7979),o=i(9039),g=a.RegExp,c=g.prototype;r&&o((function(){var e=!0;try{g(".","d")}catch(t){e=!1}var t={},i="",a=e?"dgimsy":"gimsy",addGetter=function(e,a){Object.defineProperty(t,e,{get:function(){i+=a;return!0}})},r={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};e&&(r.hasIndices="d");for(var s in r)addGetter(s,r[s]);return Object.getOwnPropertyDescriptor(c,"flags").get.call(t)!==a||i!==a}))&&s(c,"flags",{configurable:!0,get:n})},7642:(e,t,i)=>{var a=i(6518),r=i(3440);a({target:"Set",proto:!0,real:!0,forced:!i(4916)("difference")},{difference:r})},8004:(e,t,i)=>{var a=i(6518),r=i(9039),s=i(8750);a({target:"Set",proto:!0,real:!0,forced:!i(4916)("intersection")||r((function(){return"3,2"!==String(Array.from(new Set([1,2,3]).intersection(new Set([3,2]))))}))},{intersection:s})},3853:(e,t,i)=>{var a=i(6518),r=i(4449);a({target:"Set",proto:!0,real:!0,forced:!i(4916)("isDisjointFrom")},{isDisjointFrom:r})},5876:(e,t,i)=>{var a=i(6518),r=i(3838);a({target:"Set",proto:!0,real:!0,forced:!i(4916)("isSubsetOf")},{isSubsetOf:r})},2475:(e,t,i)=>{var a=i(6518),r=i(8527);a({target:"Set",proto:!0,real:!0,forced:!i(4916)("isSupersetOf")},{isSupersetOf:r})},5024:(e,t,i)=>{var a=i(6518),r=i(3650);a({target:"Set",proto:!0,real:!0,forced:!i(4916)("symmetricDifference")},{symmetricDifference:r})},1698:(e,t,i)=>{var a=i(6518),r=i(4204);a({target:"Set",proto:!0,real:!0,forced:!i(4916)("union")},{union:r})},7467:(e,t,i)=>{var a=i(7628),r=i(4644),s=r.aTypedArray,n=r.exportTypedArrayMethod,o=r.getTypedArrayConstructor;n("toReversed",(function toReversed(){return a(s(this),o(this))}))},4732:(e,t,i)=>{var a=i(4644),r=i(9504),s=i(9306),n=i(5370),o=a.aTypedArray,g=a.getTypedArrayConstructor,c=a.exportTypedArrayMethod,l=r(a.TypedArrayPrototype.sort);c("toSorted",(function toSorted(e){void 0!==e&&s(e);var t=o(this),i=n(g(t),t);return l(i,e)}))},9577:(e,t,i)=>{var a=i(9928),r=i(4644),s=i(1108),n=i(1291),o=i(5854),g=r.aTypedArray,c=r.getTypedArrayConstructor,l=r.exportTypedArrayMethod,h=!!function(){try{new Int8Array(1).with(2,{valueOf:function(){throw 8}})}catch(e){return 8===e}}();l("with",{with:function(e,t){var i=g(this),r=n(e),l=s(i)?o(t):+t;return a(i,c(i),r,l)}}.with,!h)},8992:(e,t,i)=>{i(8111)},3215:(e,t,i)=>{i(1148)},4520:(e,t,i)=>{i(2489)},2577:(e,t,i)=>{i(116)},3949:(e,t,i)=>{i(7588)},1454:(e,t,i)=>{i(1701)},8872:(e,t,i)=>{i(8237)},7550:(e,t,i)=>{i(3579)},1795:(e,t,i)=>{i(1806)},5247:(e,t,i)=>{i(1689)},4979:(e,t,i)=>{var a=i(6518),r=i(4576),s=i(7751),n=i(6980),o=i(4913).f,g=i(9297),c=i(679),l=i(3167),h=i(2603),C=i(5002),Q=i(8574),E=i(3724),u=i(6395),d="DOMException",f=s("Error"),p=s(d),m=function DOMException(){c(this,y);var e=arguments.length,t=h(e<1?void 0:arguments[0]),i=h(e<2?void 0:arguments[1],"Error"),a=new p(t,i),r=new f(t);r.name=d;o(a,"stack",n(1,Q(r.stack,1)));l(a,this,m);return a},y=m.prototype=p.prototype,w="stack"in new f(d),b="stack"in new p(1,2),D=p&&E&&Object.getOwnPropertyDescriptor(r,d),S=!(!D||D.writable&&D.configurable),k=w&&!S&&!b;a({global:!0,constructor:!0,forced:u||k},{DOMException:k?m:p});var R=s(d),N=R.prototype;if(N.constructor!==R){u||o(N,"constructor",n(1,R));for(var G in C)if(g(C,G)){var M=C[G],U=M.s;g(R,U)||o(R,U,n(6,M.c))}}},3611:(e,t,i)=>{var a=i(6518),r=i(4576),s=i(2106),n=i(3724),o=TypeError,g=Object.defineProperty,c=r.self!==r;try{if(n){var l=Object.getOwnPropertyDescriptor(r,"self");!c&&l&&l.get&&l.enumerable||s(r,"self",{get:function self(){return r},set:function self(e){if(this!==r)throw new o("Illegal invocation");g(r,"self",{value:e,writable:!0,configurable:!0,enumerable:!0})},configurable:!0,enumerable:!0})}else a({global:!0,simple:!0,forced:c},{self:r})}catch(e){}},4603:(e,t,i)=>{var a=i(6840),r=i(9504),s=i(655),n=i(2812),o=URLSearchParams,g=o.prototype,c=r(g.append),l=r(g.delete),h=r(g.forEach),C=r([].push),Q=new o("a=1&a=2&b=3");Q.delete("a",1);Q.delete("b",void 0);Q+""!="a=2"&&a(g,"delete",(function(e){var t=arguments.length,i=t<2?void 0:arguments[1];if(t&&void 0===i)return l(this,e);var a=[];h(this,(function(e,t){C(a,{key:t,value:e})}));n(t,1);for(var r,o=s(e),g=s(i),Q=0,E=0,u=!1,d=a.length;Q{var a=i(6840),r=i(9504),s=i(655),n=i(2812),o=URLSearchParams,g=o.prototype,c=r(g.getAll),l=r(g.has),h=new o("a=1");!h.has("a",2)&&h.has("a",void 0)||a(g,"has",(function has(e){var t=arguments.length,i=t<2?void 0:arguments[1];if(t&&void 0===i)return l(this,e);var a=c(this,e);n(t,1);for(var r=s(i),o=0;o{var a=i(3724),r=i(9504),s=i(2106),n=URLSearchParams.prototype,o=r(n.forEach);a&&!("size"in n)&&s(n,"size",{get:function size(){var e=0;o(this,(function(){e++}));return e},configurable:!0,enumerable:!0})}},t={};function __webpack_require__(i){var a=t[i];if(void 0!==a)return a.exports;var r=t[i]={exports:{}};e[i].call(r.exports,r,r.exports,__webpack_require__);return r.exports}__webpack_require__.d=(e,t)=>{for(var i in t)__webpack_require__.o(t,i)&&!__webpack_require__.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})};__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var __webpack_exports__ = globalThis.pdfjsWorker = {};__webpack_require__.d(__webpack_exports__,{WorkerMessageHandler:()=>WorkerMessageHandler});__webpack_require__(4114),__webpack_require__(6573),__webpack_require__(8100),__webpack_require__(7936),__webpack_require__(4628),__webpack_require__(7642),__webpack_require__(8004),__webpack_require__(3853),__webpack_require__(5876),__webpack_require__(2475),__webpack_require__(5024),__webpack_require__(1698),__webpack_require__(7467),__webpack_require__(4732),__webpack_require__(9577),__webpack_require__(8992),__webpack_require__(1454),__webpack_require__(7550),__webpack_require__(3611),__webpack_require__(5247),__webpack_require__(4979),__webpack_require__(4603),__webpack_require__(7566),__webpack_require__(8721);const i=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),a=[1,0,0,1,0,0],r=[.001,0,0,.001,0,0],s=1.35,n=.35,o=.25925925925925924,g=1,c=2,l=4,h=8,C=16,Q=64,E=128,u=256,d="pdfjs_internal_editor_",f=3,p=9,m=13,y=15,w={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},b=0,D=4,S=1,k=2,R=3,N=1,G=2,M=3,U=4,x=5,L=6,H=7,J=8,v=9,Y=10,K=11,T=12,q=13,O=14,W=15,j=16,X=17,V=20,Z="Group",_="R",z=1,$=2,AA=4,eA=16,tA=32,iA=128,aA=512,rA=1,sA=2,nA=4096,oA=8192,gA=32768,IA=65536,cA=131072,lA=1048576,hA=2097152,CA=8388608,BA=16777216,QA=1,EA=2,uA=3,dA=4,fA=5,pA={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},mA={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},yA={O:"PageOpen",C:"PageClose"},wA=1,bA=5,DA=1,FA=2,SA=3,kA=4,RA=5,NA=6,GA=7,MA=8,UA=9,xA=10,LA=11,HA=12,JA=13,vA=14,YA=15,KA=16,TA=17,qA=18,OA=19,PA=20,WA=21,jA=22,XA=23,VA=24,ZA=25,_A=26,zA=27,$A=28,Ae=29,ee=30,te=31,ie=32,ae=33,re=34,se=35,ne=36,oe=37,ge=38,Ie=39,ce=40,le=41,he=42,Ce=43,Be=44,Qe=45,Ee=46,ue=47,de=48,fe=49,pe=50,me=51,ye=52,we=53,be=54,De=55,Fe=56,Se=57,ke=58,Re=59,Ne=60,Ge=61,Me=62,Ue=63,xe=64,Le=65,He=66,Je=67,ve=68,Ye=69,Ke=70,Te=71,qe=72,Oe=73,Pe=74,We=75,je=76,Xe=77,Ve=80,Ze=81,_e=83,ze=84,$e=85,At=86,et=87,tt=88,it=89,at=90,rt=91,st=92,nt=93,ot=1,gt=2;let It=wA;function getVerbosityLevel(){return It}function info(e){It>=bA&&console.log(`Info: ${e}`)}function warn(e){It>=wA&&console.log(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,i=null){if(!e)return null;try{if(i&&"string"==typeof e){if(i.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(i.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const a=t?new URL(e,t):new URL(e);if(function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(a))return a}catch{}return null}function shadow(e,t,i,a=!1){Object.defineProperty(e,t,{value:i,enumerable:!a,configurable:!0,writable:!1});return i}const ct=function BaseExceptionClosure(){function BaseException(e,t){this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends ct{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends ct{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends ct{constructor(e){super(e,"InvalidPDFException")}}class MissingPDFException extends ct{constructor(e){super(e,"MissingPDFException")}}class UnexpectedResponseException extends ct{constructor(e,t){super(e,"UnexpectedResponseException");this.status=t}}class FormatError extends ct{constructor(e){super(e,"FormatError")}}class AbortException extends ct{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,i=8192;if(t>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:"string"==typeof navigator?.userAgent&&navigator.userAgent.includes("Firefox")}):shadow(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const lt=Array.from(Array(256).keys(),(e=>e.toString(16).padStart(2,"0")));class Util{static makeHexColor(e,t,i){return`#${lt[e]}${lt[t]}${lt[i]}`}static scaleMinMax(e,t){let i;if(e[0]){if(e[0]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[3];t[3]*=e[3]}else{i=t[0];t[0]=t[1];t[1]=i;i=t[2];t[2]=t[3];t[3]=i;if(e[1]<0){i=t[1];t[1]=t[3];t[3]=i}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){i=t[0];t[0]=t[2];t[2]=i}t[0]*=e[2];t[2]*=e[2]}t[0]+=e[4];t[1]+=e[5];t[2]+=e[4];t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return[e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){const i=t[0]*t[3]-t[1]*t[2];return[(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/i,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/i]}static getAxialAlignedBoundingBox(e,t){const i=this.applyTransform(e,t),a=this.applyTransform(e.slice(2,4),t),r=this.applyTransform([e[0],e[3]],t),s=this.applyTransform([e[2],e[1]],t);return[Math.min(i[0],a[0],r[0],s[0]),Math.min(i[1],a[1],r[1],s[1]),Math.max(i[0],a[0],r[0],s[0]),Math.max(i[1],a[1],r[1],s[1])]}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){const t=[e[0],e[2],e[1],e[3]],i=e[0]*t[0]+e[1]*t[2],a=e[0]*t[1]+e[1]*t[3],r=e[2]*t[0]+e[3]*t[2],s=e[2]*t[1]+e[3]*t[3],n=(i+s)/2,o=Math.sqrt((i+s)**2-4*(i*s-r*a))/2,g=n+o||1,c=n-o||1;return[Math.sqrt(g),Math.sqrt(c)]}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0]}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1]}return t}static intersect(e,t){const i=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),a=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(i>a)return null;const r=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),s=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return r>s?null:[i,r,a,s]}static#A(e,t,i,a,r,s,n,o,g,c){if(g<=0||g>=1)return;const l=1-g,h=g*g,C=h*g,Q=l*(l*(l*e+3*g*t)+3*h*i)+C*a,E=l*(l*(l*r+3*g*s)+3*h*n)+C*o;c[0]=Math.min(c[0],Q);c[1]=Math.min(c[1],E);c[2]=Math.max(c[2],Q);c[3]=Math.max(c[3],E)}static#e(e,t,i,a,r,s,n,o,g,c,l,h){if(Math.abs(g)<1e-12){Math.abs(c)>=1e-12&&this.#A(e,t,i,a,r,s,n,o,-l/c,h);return}const C=c**2-4*l*g;if(C<0)return;const Q=Math.sqrt(C),E=2*g;this.#A(e,t,i,a,r,s,n,o,(-c+Q)/E,h);this.#A(e,t,i,a,r,s,n,o,(-c-Q)/E,h)}static bezierBoundingBox(e,t,i,a,r,s,n,o,g){if(g){g[0]=Math.min(g[0],e,n);g[1]=Math.min(g[1],t,o);g[2]=Math.max(g[2],e,n);g[3]=Math.max(g[3],t,o)}else g=[Math.min(e,n),Math.min(t,o),Math.max(e,n),Math.max(t,o)];this.#e(e,i,r,n,t,a,s,o,3*(3*(i-r)-e+n),6*(e-2*i+r),3*(i-e),g);this.#e(e,i,r,n,t,a,s,o,3*(3*(a-s)-t+o),6*(t-2*a+s),3*(a-t),g);return g}}const ht=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e){if(e[0]>="ï"){let t;if("þ"===e[0]&&"ÿ"===e[1]){t="utf-16be";e.length%2==1&&(e=e.slice(0,-1))}else if("ÿ"===e[0]&&"þ"===e[1]){t="utf-16le";e.length%2==1&&(e=e.slice(0,-1))}else"ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(t="utf-8");if(t)try{const i=new TextDecoder(t,{fatal:!0}),a=stringToBytes(e),r=i.decode(a);return r.includes("")?r.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,""):r}catch(e){warn(`stringToPDFString: "${e}".`)}}const t=[];for(let i=0,a=e.length;ilt[e])).join("")}__webpack_require__(3215);const Qt=Symbol("CIRCULAR_REF"),Et=Symbol("EOF");let ut=Object.create(null),dt=Object.create(null),ft=Object.create(null);class Name{constructor(e){this.name=e}static get(e){return dt[e]||=new Name(e)}}class Cmd{constructor(e){this.cmd=e}static get(e){return ut[e]||=new Cmd(e)}}const pt=function nonSerializableClosure(){return pt};class Dict{constructor(e=null){this._map=new Map;this.xref=e;this.objId=null;this.suppressEncryption=!1;this.__nonSerializable__=pt}assignXref(e){this.xref=e}get size(){return this._map.size}get(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetch(a,this.suppressEncryption):a}async getAsync(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}return a instanceof Ref&&this.xref?this.xref.fetchAsync(a,this.suppressEncryption):a}getArray(e,t,i){let a=this._map.get(e);if(void 0===a&&void 0!==t){a=this._map.get(t);void 0===a&&void 0!==i&&(a=this._map.get(i))}a instanceof Ref&&this.xref&&(a=this.xref.fetch(a,this.suppressEncryption));if(Array.isArray(a)){a=a.slice();for(let e=0,t=a.length;e{unreachable("Should not call `set` on the empty dictionary.")};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:i=!1}){const a=new Dict(e),r=new Map;for(const e of t)if(e instanceof Dict)for(const[t,a]of e._map){let e=r.get(t);if(void 0===e){e=[];r.set(t,e)}else if(!(i&&a instanceof Dict))continue;e.push(a)}for(const[t,i]of r){if(1===i.length||!(i[0]instanceof Dict)){a._map.set(t,i[0]);continue}const r=new Dict(e);for(const e of i)for(const[t,i]of e._map)r._map.has(t)||r._map.set(t,i);r.size>0&&a._map.set(t,r)}r.clear();return a.size>0?a:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}delete(e){delete this._map[e]}}class Ref{constructor(e,t){this.num=e;this.gen=t}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=ft[e];if(t)return t;const i=/^(\d+)R(\d*)$/.exec(e);return i&&"0"!==i[1]?ft[e]=new Ref(parseInt(i[1]),i[2]?parseInt(i[2]):0):null}static get(e,t){const i=0===t?`${e}R`:`${e}R${t}`;return ft[i]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set)}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString())}remove(e){this._set.delete(e.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class RefSetCache{constructor(){this._map=new Map}get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t)}putAlias(e,t){this._map.set(e.toString(),this.get(t))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}*values(){yield*this._map.values()}*items(){for(const[e,t]of this._map)yield[Ref.fromString(e),t]}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{get length(){unreachable("Abstract getter `length` accessed")}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called")}getBytes(e){unreachable("Abstract method `getBytes` called")}async getImageData(e,t){return this.getBytes(e,t)}async asyncGetBytes(){unreachable("Abstract method `asyncGetBytes` called")}get isAsync(){return!1}get canAsyncDecodeImageFromBuffer(){return!1}async getTransferableImage(){return null}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return-1===e||-1===t?-1:(e<<8)+t}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called")}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1}reset(){unreachable("Abstract method `reset` called")}moveStart(){unreachable("Abstract method `moveStart` called")}makeSubStream(e,t,i=null){unreachable("Abstract method `makeSubStream` called")}getBaseStreams(){return null}}const mt=/^[1-9]\.\d$/,yt=2**31-1;function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null}return t}}class MissingDataException extends ct{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t}}class ParserEOFException extends ct{constructor(e){super(e,"ParserEOFException")}}class XRefEntryException extends ct{constructor(e){super(e,"XRefEntryException")}}class XRefParseException extends ct{constructor(e){super(e,"XRefParseException")}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let i=0;for(let a=0;a0,"The number should be a positive integer.");const i="M".repeat(e/1e3|0)+wt[e%1e3/100|0]+wt[10+(e%100/10|0)]+wt[20+e%10];return t?i.toLowerCase():i}function log2(e){return e>0?Math.ceil(Math.log2(e)):0}function readInt8(e,t){return e[t]<<24>>24}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function isNumberArray(e,t){return Array.isArray(e)?(null===t||e.length===t)&&e.every((e=>"number"==typeof e)):ArrayBuffer.isView(e)&&(0===e.length||"number"==typeof e[0])&&(null===t||e.length===t)}function lookupMatrix(e,t){return isNumberArray(e,6)?e:t}function lookupRect(e,t){return isNumberArray(e,4)?e:t}function lookupNormalRect(e,t){return isNumberArray(e,4)?Util.normalizeRect(e):t}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map((e=>{const i=e.match(t);return i?{name:i[1],pos:parseInt(i[2],10)}:{name:e,pos:0}}))}function escapePDFName(e){const t=[];let i=0;for(let a=0,r=e.length;a126||35===r||40===r||41===r||60===r||62===r||91===r||93===r||123===r||125===r||47===r||37===r){i"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`))}function _collectJS(e,t,i,a){if(!e)return;let r=null;if(e instanceof Ref){if(a.has(e))return;r=e;a.put(r);e=t.fetch(e)}if(Array.isArray(e))for(const r of e)_collectJS(r,t,i,a);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let a;t instanceof BaseStream?a=t.getString():"string"==typeof t&&(a=t);a&&=stringToPDFString(a).replaceAll("\0","");a&&i.push(a)}_collectJS(e.getRaw("Next"),t,i,a)}r&&a.remove(r)}function collectActions(e,t,i){const a=Object.create(null),r=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(r)for(let t=r.length-1;t>=0;t--){const s=r[t];if(s instanceof Dict)for(const t of s.getKeys()){const r=i[t];if(!r)continue;const n=[];_collectJS(s.getRaw(t),e,n,new RefSet);n.length>0&&(a[r]=n)}}if(t.has("A")){const i=[];_collectJS(t.get("A"),e,i,new RefSet);i.length>0&&(a.Action=i)}return objectSize(a)>0?a:null}const bt={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,i=e.length;t55295&&(i<57344||i>65533)&&t++;yield i}}function encodeToXmlString(e){const t=[];let i=0;for(let a=0,r=e.length;a55295&&(r<57344||r>65533)&&a++;i=a+1}}if(0===t.length)return e;i: ${e}.`);return!1}return!0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:i,fontWeight:a,italicAngle:r}=e;if(!validateFontName(i,!0))return!1;const s=a?a.toString():"";e.fontWeight=t.has(s)?s:"400";const n=parseFloat(r);e.italicAngle=isNaN(n)||n<-90||n>90?"14":r.toString();return!0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);return t?.[2]?{url:t[2],newWindow:"app.launchURL"===t[1]&&"true"===t[3]}:null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[i,a]of e){if(!i.startsWith(d))continue;let e=t.get(a.pageIndex);if(!e){e=[];t.set(a.pageIndex,e)}e.push(a)}return t.size>0?t:null}function stringToAsciiOrUTF16BE(e){return function isAscii(e){return/^[\x00-\x7F]*$/.test(e)}(e)?e:stringToUTF16String(e,!0)}function stringToUTF16HexString(e){const t=[];for(let i=0,a=e.length;i>8&255],lt[255&a])}return t.join("")}function stringToUTF16String(e,t=!1){const i=[];t&&i.push("þÿ");for(let t=0,a=e.length;t>8&255),String.fromCharCode(255&a))}return i.join("")}function getRotationMatrix(e,t,i){switch(e){case 90:return[0,1,-1,0,t,0];case 180:return[-1,0,0,-1,t,i];case 270:return[0,-1,1,0,0,i];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class Stream extends BaseStream{constructor(e,t,i,a){super();this.bytes=e instanceof Uint8Array?e:new Uint8Array(e);this.start=t||0;this.pos=this.start;this.end=t+i||this.bytes.length;this.dict=a}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e)return t.subarray(i,a);let r=i+e;r>a&&(r=a);this.pos=r;return t.subarray(i,r)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(e,t,i=null){return new Stream(this.bytes.buffer,e,t,i)}}class StringStream extends Stream{constructor(e){super(stringToBytes(e))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{constructor(e,t,i){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this._loadedChunks=new Set;this.numChunks=Math.ceil(e/t);this.manager=i;this.progressiveDataLength=0;this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const e=[];for(let t=0,i=this.numChunks;t=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=i;ethis.numChunks)&&t!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this.lastSuccessfulEnsureByteChunk=t}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const i=Math.floor(e/this.chunkSize);if(i>this.numChunks)return;const a=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let r=i;r=this.end)return-1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,i=this.pos,a=this.end;if(!e){a>this.progressiveDataLength&&this.ensureRange(i,a);return t.subarray(i,a)}let r=i+e;r>a&&(r=a);r>this.progressiveDataLength&&this.ensureRange(i,r);this.pos=r;return t.subarray(i,r)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,i=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),i=Math.floor((this.end-1)/e)+1,a=[];for(let e=t;e{const readChunk=({value:s,done:n})=>{try{if(n){const t=arrayBuffersToBytes(a);a=null;e(t);return}r+=s.byteLength;i.isStreamingSupported&&this.onProgress({loaded:r});a.push(s);i.read().then(readChunk,t)}catch(e){t(e)}};i.read().then(readChunk,t)})).then((t=>{this.aborted||this.onReceiveData({chunk:t,begin:e})}))}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e)}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,i=new Set;this._chunksNeededByRequest.set(t,i);for(const t of e)this.stream.hasChunk(t)||i.add(t);if(0===i.size)return Promise.resolve();const a=Promise.withResolvers();this._promisesByRequest.set(t,a);const r=[];for(const e of i){let i=this._requestsByChunk.get(e);if(!i){i=[];this._requestsByChunk.set(e,i);r.push(e)}i.push(t)}if(r.length>0){const e=this.groupChunks(r);for(const t of e){const e=t.beginChunk*this.chunkSize,i=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,i).catch(a.reject)}}return a.promise.catch((e=>{if(!this.aborted)throw e}))}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const i=this.getBeginChunk(e),a=this.getEndChunk(t),r=[];for(let e=i;e=0&&a+1!==s){t.push({beginChunk:i,endChunk:a+1});i=s}r+1===e.length&&t.push({beginChunk:i,endChunk:s+1});a=s}return t}onProgress(e){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+e.loaded,total:this.length})}onReceiveData(e){const t=e.chunk,i=void 0===e.begin,a=i?this.progressiveDataLength:e.begin,r=a+t.byteLength,s=Math.floor(a/this.chunkSize),n=r0||o.push(i)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===this.stream.numChunksLoaded){const t=this.stream.numChunks-1;this.stream.hasChunk(t)||(e=t)}else e=this.stream.nextEmptyChunk(n);Number.isInteger(e)&&this._requestChunks([e])}for(const e of o){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(e){this._loadedStreamCapability.reject(e)}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfNetworkStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e)}}__webpack_require__(4520),__webpack_require__(9479),__webpack_require__(2577),__webpack_require__(8872);class ColorSpace{constructor(e,t){this.name=e;this.numComps=t}getRgb(e,t){const i=new Uint8ClampedArray(3);this.getRgbItem(e,t,i,0);return i}getRgbItem(e,t,i,a){unreachable("Should not call ColorSpace.getRgbItem")}getRgbBuffer(e,t,i,a,r,s,n){unreachable("Should not call ColorSpace.getRgbBuffer")}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength")}isPassthrough(e){return!1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,i,a,r,s,n,o,g){const c=t*i;let l=null;const h=1<h&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=n<=8?new Uint8Array(h):new Uint16Array(h);for(let e=0;e=.99554525?1:this.#B(0,1,1.055*e**(1/2.4)-.055)}#B(e,t,i){return Math.max(e,Math.min(t,i))}#Q(e){return e<0?-this.#Q(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#I}#E(e,t,i){if(0===e[0]&&0===e[1]&&0===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=this.#Q(0),r=(1-a)/(1-this.#Q(e[0])),s=1-r,n=(1-a)/(1-this.#Q(e[1])),o=1-n,g=(1-a)/(1-this.#Q(e[2])),c=1-g;i[0]=t[0]*r+s;i[1]=t[1]*n+o;i[2]=t[2]*g+c}#u(e,t,i){if(1===e[0]&&1===e[2]){i[0]=t[0];i[1]=t[1];i[2]=t[2];return}const a=i;this.#c(CalRGBCS.#i,t,a);const r=CalRGBCS.#n;this.#l(e,a,r);this.#c(CalRGBCS.#a,r,i)}#d(e,t,i){const a=i;this.#c(CalRGBCS.#i,t,a);const r=CalRGBCS.#n;this.#h(e,a,r);this.#c(CalRGBCS.#a,r,i)}#t(e,t,i,a,r){const s=this.#B(0,1,e[t]*r),n=this.#B(0,1,e[t+1]*r),o=this.#B(0,1,e[t+2]*r),g=1===s?1:s**this.GR,c=1===n?1:n**this.GG,l=1===o?1:o**this.GB,h=this.MXA*g+this.MXB*c+this.MXC*l,C=this.MYA*g+this.MYB*c+this.MYC*l,Q=this.MZA*g+this.MZB*c+this.MZC*l,E=CalRGBCS.#o;E[0]=h;E[1]=C;E[2]=Q;const u=CalRGBCS.#g;this.#u(this.whitePoint,E,u);const d=CalRGBCS.#o;this.#E(this.blackPoint,u,d);const f=CalRGBCS.#g;this.#d(CalRGBCS.#s,d,f);const p=CalRGBCS.#o;this.#c(CalRGBCS.#r,f,p);i[a]=255*this.#C(p[0]);i[a+1]=255*this.#C(p[1]);i[a+2]=255*this.#C(p[2])}getRgbItem(e,t,i,a){this.#t(e,t,i,a,1)}getRgbBuffer(e,t,i,a,r,s,n){const o=1/((1<this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100}}#f(e){return e>=6/29?e**3:108/841*(e-4/29)}#p(e,t,i,a){return i+e*(a-i)/t}#t(e,t,i,a,r){let s=e[t],n=e[t+1],o=e[t+2];if(!1!==i){s=this.#p(s,i,0,100);n=this.#p(n,i,this.amin,this.amax);o=this.#p(o,i,this.bmin,this.bmax)}n>this.amax?n=this.amax:nthis.bmax?o=this.bmax:o>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,i){let a=0;for(let r=i;r>=0;r--){a+=e[r]+t[r];e[r]=255&a;a>>=8}}function incHex(e,t){let i=1;for(let a=t;a>=0&&i>0;a--){i+=e[a];e[a]=255&i;i>>=8}}const Dt=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let e,t=0;do{const i=this.readByte();if(i<0)throw new FormatError("unexpected EOF in bcmap");e=!(128&i);t=t<<7|127&i}while(!e);return t}readSigned(){const e=this.readNumber();return 1&e?~(e>>>1):e>>>1}readHex(e,t){e.set(this.buffer.subarray(this.pos,this.pos+t+1));this.pos+=t+1}readHexNumber(e,t){let i;const a=this.tmpBuf;let r=0;do{const e=this.readByte();if(e<0)throw new FormatError("unexpected EOF in bcmap");i=!(128&e);a[r++]=127&e}while(!i);let s=t,n=0,o=0;for(;s>=0;){for(;o<8&&a.length>0;){n|=a[--r]<>=8;o-=8}}readHexSigned(e,t){this.readHexNumber(e,t);const i=1&e[t]?255:0;let a=0;for(let r=0;r<=t;r++){a=(1&a)<<8|e[r];e[r]=a>>1^i}}readString(){const e=this.readNumber(),t=new Array(e);for(let i=0;i=0;){const e=C>>5;if(7===e){switch(31&C){case 0:a.readString();break;case 1:s=a.readString()}continue}const i=!!(16&C),r=15&C;if(r+1>Dt)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const Q=1,E=a.readNumber();switch(e){case 0:a.readHex(n,r);a.readHexNumber(o,r);addHex(o,n,r);t.addCodespaceRange(r+1,hexToInt(n,r),hexToInt(o,r));for(let e=1;er&&(a=r)}else{for(;!this.eof;)this.readBlock(t);a=this.bufferLength}this.pos=a;return this.buffer.subarray(i,a)}async getImageData(e,t=null){if(!this.canAsyncDecodeImageFromBuffer)return this.getBytes(e,t);const i=await this.stream.asyncGetBytes();return this.decodeImage(i,t)}reset(){this.pos=0}makeSubStream(e,t,i=null){if(void 0===t)for(;!this.eof;)this.readBlock();else{const i=e+t;for(;this.bufferLength<=i&&!this.eof;)this.readBlock()}return new Stream(this.buffer,e,t,i)}getBaseStreams(){return this.str?this.str.getBaseStreams():null}}class StreamsSequenceStream extends DecodeStream{constructor(e,t=null){e=e.filter((e=>e instanceof BaseStream));let i=0;for(const t of e)i+=t instanceof DecodeStream?t._rawMinBufferLength:t.length;super(i);this.streams=e;this._onError=t}readBlock(){const e=this.streams;if(0===e.length){this.eof=!0;return}const t=e.shift();let i;try{i=t.getBytes()}catch(e){if(this._onError){this._onError(e,t.dict?.objId);return}throw e}const a=this.bufferLength,r=a+i.length;this.ensureBuffer(r).set(i,a);this.bufferLength=r}getBaseStreams(){const e=[];for(const t of this.streams){const i=t.getBaseStreams();i&&e.push(...i)}return e.length>0?e:null}}class Ascii85Stream extends DecodeStream{constructor(e,t){t&&(t*=.8);super(t);this.str=e;this.dict=e.dict;this.input=new Uint8Array(5)}readBlock(){const e=this.str;let t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();if(-1===t||126===t){this.eof=!0;return}const i=this.bufferLength;let a,r;if(122===t){a=this.ensureBuffer(i+4);for(r=0;r<4;++r)a[i+r]=0;this.bufferLength+=4}else{const s=this.input;s[0]=t;for(r=1;r<5;++r){t=e.getByte();for(;isWhiteSpace(t);)t=e.getByte();s[r]=t;if(-1===t||126===t)break}a=this.ensureBuffer(i+r-1);this.bufferLength+=r-1;if(r<5){for(;r<5;++r)s[r]=117;this.eof=!0}let n=0;for(r=0;r<5;++r)n=85*n+(s[r]-33);for(r=3;r>=0;--r){a[i+r]=255&n;n>>=8}}}}class AsciiHexStream extends DecodeStream{constructor(e,t){t&&(t*=.5);super(t);this.str=e;this.dict=e.dict;this.firstDigit=-1}readBlock(){const e=this.str.getBytes(8e3);if(!e.length){this.eof=!0;return}const t=e.length+1>>1,i=this.ensureBuffer(this.bufferLength+t);let a=this.bufferLength,r=this.firstDigit;for(const t of e){let e;if(t>=48&&t<=57)e=15&t;else{if(!(t>=65&&t<=70||t>=97&&t<=102)){if(62===t){this.eof=!0;break}continue}e=9+(15&t)}if(r<0)r=e;else{i[a++]=r<<4|e;r=-1}}if(r>=0&&this.eof){i[a++]=r<<4;r=-1}this.firstDigit=r;this.bufferLength=a}}const St=-1,kt=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],Rt=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],Nt=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Gt=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],Mt=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Ut=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(e,t={}){if("function"!=typeof e?.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e;this.eof=!1;this.encoding=t.K||0;this.eoline=t.EndOfLine||!1;this.byteAlign=t.EncodedByteAlign||!1;this.columns=t.Columns||1728;this.rows=t.Rows||0;this.eoblock=t.EndOfBlock??!0;this.black=t.BlackIs1||!1;this.codingLine=new Uint32Array(this.columns+1);this.refLine=new Uint32Array(this.columns+2);this.codingLine[0]=this.columns;this.codingPos=0;this.row=0;this.nextLine2D=this.encoding<0;this.inputBits=0;this.inputBuf=0;this.outputBits=0;this.rowsDone=!1;let i;for(;0===(i=this._lookBits(12));)this._eatBits(1);1===i&&this._eatBits(12);if(this.encoding>0){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}}readNextChar(){if(this.eof)return-1;const e=this.refLine,t=this.codingLine,i=this.columns;let a,r,s,n,o;if(0===this.outputBits){this.rowsDone&&(this.eof=!0);if(this.eof)return-1;this.err=!1;let s,o,g;if(this.nextLine2D){for(n=0;t[n]=64);do{o+=g=this._getWhiteCode()}while(g>=64)}else{do{s+=g=this._getWhiteCode()}while(g>=64);do{o+=g=this._getBlackCode()}while(g>=64)}this._addPixels(t[this.codingPos]+s,r);t[this.codingPos]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]0?--a:++a;for(;e[a]<=t[this.codingPos]&&e[a]=64);else do{s+=g=this._getWhiteCode()}while(g>=64);this._addPixels(t[this.codingPos]+s,r);r^=1}}let c=!1;this.byteAlign&&(this.inputBits&=-8);if(this.eoblock||this.row!==this.rows-1){s=this._lookBits(12);if(this.eoline)for(;s!==St&&1!==s;){this._eatBits(1);s=this._lookBits(12)}else for(;0===s;){this._eatBits(1);s=this._lookBits(12)}if(1===s){this._eatBits(12);c=!0}else s===St&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}if(this.eoblock&&c&&this.byteAlign){s=this._lookBits(12);if(1===s){this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}if(this.encoding>=0)for(n=0;n<4;++n){s=this._lookBits(12);1!==s&&info("bad rtc code: "+s);this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}}this.eof=!0}}else if(this.err&&this.eoline){for(;;){s=this._lookBits(13);if(s===St){this.eof=!0;return-1}if(s>>1==1)break;this._eatBits(1)}this._eatBits(12);if(this.encoding>0){this._eatBits(1);this.nextLine2D=!(1&s)}}this.outputBits=t[0]>0?t[this.codingPos=0]:t[this.codingPos=1];this.row++}if(this.outputBits>=8){o=1&this.codingPos?0:255;this.outputBits-=8;if(0===this.outputBits&&t[this.codingPos]s){o<<=s;1&this.codingPos||(o|=255>>8-s);this.outputBits-=s;s=0}else{o<<=this.outputBits;1&this.codingPos||(o|=255>>8-this.outputBits);s-=this.outputBits;this.outputBits=0;if(t[this.codingPos]0){o<<=s;s=0}}}while(s)}this.black&&(o^=255);return o}_addPixels(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}this.codingPos=a}_addPixelsNeg(e,t){const i=this.codingLine;let a=this.codingPos;if(e>i[a]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&a^t&&++a;i[a]=e}else if(e0&&e=r){const t=i[e-r];if(t[0]===a){this._eatBits(a);return[!0,t[1],!0]}}}return[!1,0,!1]}_getTwoDimCode(){let e,t=0;if(this.eoblock){t=this._lookBits(7);e=kt[t];if(e?.[0]>0){this._eatBits(e[0]);return e[1]}}else{const e=this._findTableCode(1,7,kt);if(e[0]&&e[2])return e[1]}info("Bad two dim code");return St}_getWhiteCode(){let e,t=0;if(this.eoblock){t=this._lookBits(12);if(t===St)return 1;e=t>>5?Nt[t>>3]:Rt[t];if(e[0]>0){this._eatBits(e[0]);return e[1]}}else{let e=this._findTableCode(1,9,Nt);if(e[0])return e[1];e=this._findTableCode(11,12,Rt);if(e[0])return e[1]}info("bad white code");this._eatBits(1);return 1}_getBlackCode(){let e,t;if(this.eoblock){e=this._lookBits(13);if(e===St)return 1;t=e>>7?!(e>>9)&&e>>7?Mt[(e>>1)-64]:Ut[e>>7]:Gt[e];if(t[0]>0){this._eatBits(t[0]);return t[1]}}else{let e=this._findTableCode(2,6,Ut);if(e[0])return e[1];e=this._findTableCode(7,12,Mt,64);if(e[0])return e[1];e=this._findTableCode(10,13,Gt);if(e[0])return e[1]}info("bad black code");this._eatBits(1);return 1}_lookBits(e){let t;for(;this.inputBits>16-e;this.inputBuf=this.inputBuf<<8|t;this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;i instanceof Dict||(i=Dict.empty);const a={next:()=>e.getByte()};this.ccittFaxDecoder=new CCITTFaxDecoder(a,{K:i.get("K"),EndOfLine:i.get("EndOfLine"),EncodedByteAlign:i.get("EncodedByteAlign"),Columns:i.get("Columns"),Rows:i.get("Rows"),EndOfBlock:i.get("EndOfBlock"),BlackIs1:i.get("BlackIs1")})}readBlock(){for(;!this.eof;){const e=this.ccittFaxDecoder.readNextChar();if(-1===e){this.eof=!0;return}this.ensureBuffer(this.bufferLength+1);this.buffer[this.bufferLength++]=e}}}const xt=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Lt=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),Ht=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Jt=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],vt=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class FlateStream extends DecodeStream{constructor(e,t){super(t);this.str=e;this.dict=e.dict;const i=e.getByte(),a=e.getByte();if(-1===i||-1===a)throw new FormatError(`Invalid header in flate stream: ${i}, ${a}`);if(8!=(15&i))throw new FormatError(`Unknown compression method in flate stream: ${i}, ${a}`);if(((i<<8)+a)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${i}, ${a}`);if(32&a)throw new FormatError(`FDICT bit set in flate stream: ${i}, ${a}`);this.codeSize=0;this.codeBuf=0}async getImageData(e,t){const i=await this.asyncGetBytes();return i?.subarray(0,e)||this.getBytes(e)}async asyncGetBytes(){this.str.reset();const e=this.str.getBytes();try{const{readable:t,writable:i}=new DecompressionStream("deflate"),a=i.getWriter();await a.ready;a.write(e).then((async()=>{await a.ready;await a.close()})).catch((()=>{}));const r=[];let s=0;for await(const e of t){r.push(e);s+=e.byteLength}const n=new Uint8Array(s);let o=0;for(const e of r){n.set(e,o);o+=e.byteLength}return n}catch{this.str=new Stream(e,2,e.length,this.str.dict);this.reset();return null}}get isAsync(){return!0}getBits(e){const t=this.str;let i,a=this.codeSize,r=this.codeBuf;for(;a>e;this.codeSize=a-=e;return i}getCode(e){const t=this.str,i=e[0],a=e[1];let r,s=this.codeSize,n=this.codeBuf;for(;s>16,c=65535&o;if(g<1||s>g;this.codeSize=s-g;return c}generateHuffmanTable(e){const t=e.length;let i,a=0;for(i=0;ia&&(a=e[i]);const r=1<>=1}for(i=e;i>=1;if(0===t){let t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let i=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}i|=t<<8;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}let r=t;if(-1===(t=a.getByte())){this.#m("Bad block header in flate stream");return}r|=t<<8;if(r!==(65535&~i)&&(0!==i||0!==r))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;const s=this.bufferLength,n=s+i;e=this.ensureBuffer(n);this.bufferLength=n;if(0===i)-1===a.peekByte()&&(this.eof=!0);else{const t=a.getBytes(i);e.set(t,s);t.length0;)l[o++]=Q}r=this.generateHuffmanTable(l.subarray(0,e));s=this.generateHuffmanTable(l.subarray(e,c))}}e=this.buffer;let n=e?e.length:0,o=this.bufferLength;for(;;){let t=this.getCode(r);if(t<256){if(o+1>=n){e=this.ensureBuffer(o+1);n=e.length}e[o++]=t;continue}if(256===t){this.bufferLength=o;return}t-=257;t=Lt[t];let a=t>>16;a>0&&(a=this.getBits(a));i=(65535&t)+a;t=this.getCode(s);t=Ht[t];a=t>>16;a>0&&(a=this.getBits(a));const g=(65535&t)+a;if(o+i>=n){e=this.ensureBuffer(o+i);n=e.length}for(let t=0;t>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}byteIn(){const e=this.data;let t=this.bp;if(255===e[t])if(e[t+1]>143){this.clow+=65280;this.ct=8}else{t++;this.clow+=e[t]<<9;this.ct=7;this.bp=t}else{t++;this.clow+=t65535){this.chigh+=this.clow>>16;this.clow&=65535}}readBit(e,t){let i=e[t]>>1,a=1&e[t];const r=Yt[i],s=r.qe;let n,o=this.a-s;if(this.chigh>15&1;this.clow=this.clow<<1&65535;this.ct--}while(!(32768&o));this.a=o;e[t]=i<<1|a;return n}}class Jbig2Error extends ct{constructor(e){super(e,"Jbig2Error")}}class ContextCache{getContexts(e){return e in this?this[e]:this[e]=new Int8Array(65536)}}class DecodingContext{constructor(e,t,i){this.data=e;this.start=t;this.end=i}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}function decodeInteger(e,t,i){const a=e.getContexts(t);let r=1;function readBits(e){let t=0;for(let s=0;s>>0}const s=readBits(1),n=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let o;0===s?o=n:n>0&&(o=-n);return o>=-2147483648&&o<=yt?o:null}function decodeIAID(e,t,i){const a=e.getContexts("IAID");let r=1;for(let e=0;e=S&&L=k){T=T<<1&d;for(u=0;u=0&&J=0){v=M[H][J];v&&(T|=v<=e?c<<=1:c=c<<1|w[o][g]}for(Q=0;Q=m||g<0||g>=p?c<<=1:c=c<<1|a[o][g]}const E=b.readBit(D,c);t[n]=E}}return w}function decodeTextRegion(e,t,i,a,r,s,n,o,g,c,l,h,C,Q,E,u,d,f,p){if(e&&t)throw new Jbig2Error("refinement with Huffman is not supported");const m=[];let y,w;for(y=0;y1&&(r=e?p.readBits(f):decodeInteger(D,"IAIT",b));const s=n*S+r,k=e?Q.symbolIDTable.decode(p):decodeIAID(D,b,g),R=t&&(e?p.readBit():decodeInteger(D,"IARI",b));let N=o[k],G=N[0].length,M=N.length;if(R){const e=decodeInteger(D,"IARDW",b),t=decodeInteger(D,"IARDH",b);G+=e;M+=t;N=decodeRefinement(G,M,E,N,(e>>1)+decodeInteger(D,"IARDX",b),(t>>1)+decodeInteger(D,"IARDY",b),!1,u,d)}let U=0;c?1&h?U=M-1:a+=M-1:h>1?a+=G-1:U=G-1;const x=s-(1&h?0:M-1),L=a-(2&h?G-1:0);let H,J,v;if(c)for(H=0;H>5&7;const g=[31&n];let c=t+6;if(7===n){o=536870911&readUint32(e,c-1);c+=3;let t=o+7>>3;g[0]=e[c++];for(;--t>0;)g.push(e[c++])}else if(5===n||6===n)throw new Jbig2Error("invalid referred-to flags");i.retainBits=g;let l=4;i.number<=256?l=1:i.number<=65536&&(l=2);const h=[];let C,Q;for(C=0;C>>24&255;s[3]=t.height>>16&255;s[4]=t.height>>8&255;s[5]=255&t.height;for(C=c,Q=e.length;C>2&3;e.huffmanDWSelector=t>>4&3;e.bitmapSizeSelector=t>>6&1;e.aggregationInstancesSelector=t>>7&1;e.bitmapCodingContextUsed=!!(256&t);e.bitmapCodingContextRetained=!!(512&t);e.template=t>>10&3;e.refinementTemplate=t>>12&1;c+=2;if(!e.huffman){g=0===e.template?4:1;n=[];for(o=0;o>2&3;l.stripSize=1<>4&3;l.transposed=!!(64&h);l.combinationOperator=h>>7&3;l.defaultPixelValue=h>>9&1;l.dsOffset=h<<17>>27;l.refinementTemplate=h>>15&1;if(l.huffman){const e=readUint16(a,c);c+=2;l.huffmanFS=3&e;l.huffmanDS=e>>2&3;l.huffmanDT=e>>4&3;l.huffmanRefinementDW=e>>6&3;l.huffmanRefinementDH=e>>8&3;l.huffmanRefinementDX=e>>10&3;l.huffmanRefinementDY=e>>12&3;l.huffmanRefinementSizeSelector=!!(16384&e)}if(l.refinement&&!l.refinementTemplate){n=[];for(o=0;o<2;o++){n.push({x:readInt8(a,c),y:readInt8(a,c+1)});c+=2}l.refinementAt=n}l.numberOfSymbolInstances=readUint32(a,c);c+=4;s=[l,i.referredTo,a,c,r];break;case 16:const C={},Q=a[c++];C.mmr=!!(1&Q);C.template=Q>>1&3;C.patternWidth=a[c++];C.patternHeight=a[c++];C.maxPatternIndex=readUint32(a,c);c+=4;s=[C,i.number,a,c,r];break;case 22:case 23:const E={};E.info=readRegionSegmentInformation(a,c);c+=Wt;const u=a[c++];E.mmr=!!(1&u);E.template=u>>1&3;E.enableSkip=!!(8&u);E.combinationOperator=u>>4&7;E.defaultPixelValue=u>>7&1;E.gridWidth=readUint32(a,c);c+=4;E.gridHeight=readUint32(a,c);c+=4;E.gridOffsetX=4294967295&readUint32(a,c);c+=4;E.gridOffsetY=4294967295&readUint32(a,c);c+=4;E.gridVectorX=readUint16(a,c);c+=2;E.gridVectorY=readUint16(a,c);c+=2;s=[E,i.referredTo,a,c,r];break;case 38:case 39:const d={};d.info=readRegionSegmentInformation(a,c);c+=Wt;const f=a[c++];d.mmr=!!(1&f);d.template=f>>1&3;d.prediction=!!(8&f);if(!d.mmr){g=0===d.template?4:1;n=[];for(o=0;o>2&1;p.combinationOperator=m>>3&3;p.requiresBuffer=!!(32&m);p.combinationOperatorOverride=!!(64&m);s=[p];break;case 49:case 50:case 51:case 62:break;case 53:s=[i.number,a,c,r];break;default:throw new Jbig2Error(`segment type ${i.typeName}(${i.type}) is not implemented`)}const l="on"+i.typeName;l in t&&t[l].apply(t,s)}function processSegments(e,t){for(let i=0,a=e.length;i>3,i=new Uint8ClampedArray(t*e.height);e.defaultPixelValue&&i.fill(255);this.buffer=i}drawBitmap(e,t){const i=this.currentPageInfo,a=e.width,r=e.height,s=i.width+7>>3,n=i.combinationOperatorOverride?e.combinationOperator:i.combinationOperator,o=this.buffer,g=128>>(7&e.x);let c,l,h,C,Q=e.y*s+(e.x>>3);switch(n){case 0:for(c=0;c>=1;if(!h){h=128;C++}}Q+=s}break;case 2:for(c=0;c>=1;if(!h){h=128;C++}}Q+=s}break;default:throw new Jbig2Error(`operator ${n} is not supported`)}}onImmediateGenericRegion(e,t,i,a){const r=e.info,s=new DecodingContext(t,i,a),n=decodeBitmap(e.mmr,r.width,r.height,e.template,e.prediction,null,e.at,s);this.drawBitmap(r,n)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(e,t,i,a,r,s){let n,o;if(e.huffman){n=function getSymbolDictionaryHuffmanTables(e,t,i){let a,r,s,n,o=0;switch(e.huffmanDHSelector){case 0:case 1:a=getStandardTable(e.huffmanDHSelector+4);break;case 3:a=getCustomHuffmanTable(o,t,i);o++;break;default:throw new Jbig2Error("invalid Huffman DH selector")}switch(e.huffmanDWSelector){case 0:case 1:r=getStandardTable(e.huffmanDWSelector+2);break;case 3:r=getCustomHuffmanTable(o,t,i);o++;break;default:throw new Jbig2Error("invalid Huffman DW selector")}if(e.bitmapSizeSelector){s=getCustomHuffmanTable(o,t,i);o++}else s=getStandardTable(1);n=e.aggregationInstancesSelector?getCustomHuffmanTable(o,t,i):getStandardTable(1);return{tableDeltaHeight:a,tableDeltaWidth:r,tableBitmapSize:s,tableAggregateInstances:n}}(e,i,this.customTables);o=new Reader(a,r,s)}let g=this.symbols;g||(this.symbols=g={});const c=[];for(const e of i){const t=g[e];t&&c.push(...t)}const l=new DecodingContext(a,r,s);g[t]=function decodeSymbolDictionary(e,t,i,a,r,s,n,o,g,c,l,h){if(e&&t)throw new Jbig2Error("symbol refinement with Huffman is not supported");const C=[];let Q=0,E=log2(i.length+a);const u=l.decoder,d=l.contextCache;let f,p;if(e){f=getStandardTable(1);p=[];E=Math.max(E,1)}for(;C.length1)m=decodeTextRegion(e,t,a,Q,0,r,1,i.concat(C),E,0,0,1,0,s,g,c,l,0,h);else{const e=decodeIAID(d,u,E),t=decodeInteger(d,"IARDX",u),r=decodeInteger(d,"IARDY",u);m=decodeRefinement(a,Q,g,e=32){let i,a,n;switch(t){case 32:if(0===e)throw new Jbig2Error("no previous value in symbol ID table");a=r.readBits(2)+3;i=s[e-1].prefixLength;break;case 33:a=r.readBits(3)+3;i=0;break;case 34:a=r.readBits(7)+11;i=0;break;default:throw new Jbig2Error("invalid code length in symbol ID table")}for(n=0;n=0;d--){N=e?decodeMMRBitmap(R,g,c,!0):decodeBitmap(!1,g,c,i,!1,null,S,E);k[d]=N}for(G=0;G=0;f--){U^=k[f][G][M];x|=U<>8;J=h+G*C-M*Q>>8;if(H>=0&&H+w<=a&&J>=0&&J+b<=r)for(d=0;d=r)){Y=u[t];v=L[d];for(f=0;f=0&&e>1&7),g=1+(a>>4&7),c=[];let l,h,C=r;do{l=n.readBits(o);h=n.readBits(g);c.push(new HuffmanLine([C,l,h,0]));C+=1<>t&1;if(t<=0)this.children[i]=new HuffmanTreeNode(e);else{let a=this.children[i];a||(this.children[i]=a=new HuffmanTreeNode(null));a.buildTree(e,t-1)}}decodeNode(e){if(this.isLeaf){if(this.isOOB)return null;const t=e.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-t:t)}const t=this.children[e.readBit()];if(!t)throw new Jbig2Error("invalid Huffman data");return t.decodeNode(e)}}class HuffmanTable{constructor(e,t){t||this.assignPrefixCodes(e);this.rootNode=new HuffmanTreeNode(null);for(let t=0,i=e.length;t0&&this.rootNode.buildTree(i,i.prefixLength-1)}}decode(e){return this.rootNode.decodeNode(e)}assignPrefixCodes(e){const t=e.length;let i=0;for(let a=0;a=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++];this.shift=7}const e=this.currentByte>>this.shift&1;this.shift--;return e}readBits(e){let t,i=0;for(t=e-1;t>=0;t--)i|=this.readBit()<=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(e,t,i){let a=0;for(let r=0,s=t.length;r>i&1;i--}}if(a&&!o){const e=5;for(let t=0;t>2,c=new Uint32Array(e.buffer,t,g);if(FeatureTest.isLittleEndian){for(;n>>24|t<<8|4278190080;i[a+2]=t>>>16|r<<16|4278190080;i[a+3]=r>>>8|4278190080}for(let r=4*n,s=t+o;r>>8|255;i[a+2]=t<<16|r>>>16|255;i[a+3]=r<<8|255}for(let r=4*n,s=t+o;r>3,h=7&a,C=e.length;i=new Uint32Array(i.buffer);let Q=0;for(let a=0;a0&&!e[s-1];)s--;const n=[{children:[],index:0}];let o,g=n[0];for(i=0;i0;)g=n.pop();g.index++;n.push(g);for(;n.length<=i;){n.push(o={children:[],index:0});g.children[g.index]=o.children;g=o}r++}if(i+10){E--;return Q>>E&1}Q=e[t++];if(255===Q){const a=e[t++];if(a){if(220===a&&c){const a=readUint16(e,t+=2);t+=2;if(a>0&&a!==i.scanLines)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",a)}else if(217===a){if(c){const e=p*(8===i.precision?8:0);if(e>0&&Math.round(i.scanLines/e)>=5)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",e)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new JpegError(`unexpected marker ${(Q<<8|a).toString(16)}`)}}E=7;return Q>>>7}function decodeHuffman(e){let t=e;for(;;){t=t[readBit()];switch(typeof t){case"number":return t;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(e){let t=0;for(;e>0;){t=t<<1|readBit();e--}return t}function receiveAndExtend(e){if(1===e)return 1===readBit()?1:-1;const t=receive(e);return t>=1<0){u--;return}let i=s;const a=n;for(;i<=a;){const a=decodeHuffman(e.huffmanTableAC),r=15&a,s=a>>4;if(0===r){if(s<15){u=receive(s)+(1<>4;if(0===r)if(c<15){u=receive(c)+(1<>4;if(0===a){if(s<15)break;r+=16;continue}r+=s;const n=Xt[r];e.blockData[t+n]=receiveAndExtend(a);r++}};let R,N=0;const G=1===m?a[0].blocksPerLine*a[0].blocksPerColumn:l*i.mcusPerColumn;let M,U;for(;N<=G;){const i=r?Math.min(G-N,r):G;if(i>0){for(w=0;w0?"unexpected":"excessive"} MCU data, current marker is: ${R.invalid}`);t=R.offset}if(!(R.marker>=65488&&R.marker<=65495))break;t+=2}return t-C}function quantizeAndInverse(e,t,i){const a=e.quantizationTable,r=e.blockData;let s,n,o,g,c,l,h,C,Q,E,u,d,f,p,m,y,w;if(!a)throw new JpegError("missing required Quantization Table.");for(let e=0;e<64;e+=8){Q=r[t+e];E=r[t+e+1];u=r[t+e+2];d=r[t+e+3];f=r[t+e+4];p=r[t+e+5];m=r[t+e+6];y=r[t+e+7];Q*=a[e];if(E|u|d|f|p|m|y){E*=a[e+1];u*=a[e+2];d*=a[e+3];f*=a[e+4];p*=a[e+5];m*=a[e+6];y*=a[e+7];s=ei*Q+128>>8;n=ei*f+128>>8;o=u;g=m;c=ti*(E-y)+128>>8;C=ti*(E+y)+128>>8;l=d<<4;h=p<<4;s=s+n+1>>1;n=s-n;w=o*Ai+g*$t+128>>8;o=o*$t-g*Ai+128>>8;g=w;c=c+h+1>>1;h=c-h;C=C+l+1>>1;l=C-l;s=s+g+1>>1;g=s-g;n=n+o+1>>1;o=n-o;w=c*zt+C*_t+2048>>12;c=c*_t-C*zt+2048>>12;C=w;w=l*Zt+h*Vt+2048>>12;l=l*Vt-h*Zt+2048>>12;h=w;i[e]=s+C;i[e+7]=s-C;i[e+1]=n+h;i[e+6]=n-h;i[e+2]=o+l;i[e+5]=o-l;i[e+3]=g+c;i[e+4]=g-c}else{w=ei*Q+512>>10;i[e]=w;i[e+1]=w;i[e+2]=w;i[e+3]=w;i[e+4]=w;i[e+5]=w;i[e+6]=w;i[e+7]=w}}for(let e=0;e<8;++e){Q=i[e];E=i[e+8];u=i[e+16];d=i[e+24];f=i[e+32];p=i[e+40];m=i[e+48];y=i[e+56];if(E|u|d|f|p|m|y){s=ei*Q+2048>>12;n=ei*f+2048>>12;o=u;g=m;c=ti*(E-y)+2048>>12;C=ti*(E+y)+2048>>12;l=d;h=p;s=4112+(s+n+1>>1);n=s-n;w=o*Ai+g*$t+2048>>12;o=o*$t-g*Ai+2048>>12;g=w;c=c+h+1>>1;h=c-h;C=C+l+1>>1;l=C-l;s=s+g+1>>1;g=s-g;n=n+o+1>>1;o=n-o;w=c*zt+C*_t+2048>>12;c=c*_t-C*zt+2048>>12;C=w;w=l*Zt+h*Vt+2048>>12;l=l*Vt-h*Zt+2048>>12;h=w;Q=s+C;y=s-C;E=n+h;m=n-h;u=o+l;p=o-l;d=g+c;f=g-c;Q<16?Q=0:Q>=4080?Q=255:Q>>=4;E<16?E=0:E>=4080?E=255:E>>=4;u<16?u=0:u>=4080?u=255:u>>=4;d<16?d=0:d>=4080?d=255:d>>=4;f<16?f=0:f>=4080?f=255:f>>=4;p<16?p=0:p>=4080?p=255:p>>=4;m<16?m=0:m>=4080?m=255:m>>=4;y<16?y=0:y>=4080?y=255:y>>=4;r[t+e]=Q;r[t+e+8]=E;r[t+e+16]=u;r[t+e+24]=d;r[t+e+32]=f;r[t+e+40]=p;r[t+e+48]=m;r[t+e+56]=y}else{w=ei*Q+8192>>14;w=w<-2040?0:w>=2024?255:w+2056>>4;r[t+e]=w;r[t+e+8]=w;r[t+e+16]=w;r[t+e+24]=w;r[t+e+32]=w;r[t+e+40]=w;r[t+e+48]=w;r[t+e+56]=w}}}function buildComponentData(e,t){const i=t.blocksPerLine,a=t.blocksPerColumn,r=new Int16Array(64);for(let e=0;e=a)return null;const s=readUint16(e,t);if(s>=65472&&s<=65534)return{invalid:null,marker:s,offset:t};let n=readUint16(e,r);for(;!(n>=65472&&n<=65534);){if(++r>=a)return null;n=readUint16(e,r)}return{invalid:s.toString(16),marker:n,offset:r}}function prepareComponents(e){const t=Math.ceil(e.samplesPerLine/8/e.maxH),i=Math.ceil(e.scanLines/8/e.maxV);for(const a of e.components){const r=Math.ceil(Math.ceil(e.samplesPerLine/8)*a.h/e.maxH),s=Math.ceil(Math.ceil(e.scanLines/8)*a.v/e.maxV),n=t*a.h,o=64*(i*a.v)*(n+1);a.blockData=new Int16Array(o);a.blocksPerLine=r;a.blocksPerColumn=s}e.mcusPerLine=t;e.mcusPerColumn=i}function readDataBlock(e,t){const i=readUint16(e,t);let a=(t+=2)+i-2;const r=findNextFileMarker(e,a,t);if(r?.invalid){warn("readDataBlock - incorrect length, current marker is: "+r.invalid);a=r.offset}const s=e.subarray(t,a);return{appData:s,newOffset:t+=s.length}}function skipData(e,t){const i=readUint16(e,t),a=(t+=2)+i-2,r=findNextFileMarker(e,a,t);return r?.invalid?r.offset:a}class JpegImage{constructor({decodeTransform:e=null,colorTransform:t=-1}={}){this._decodeTransform=e;this._colorTransform=t}static canUseImageDecoder(e,t=-1){let i=0,a=null,r=readUint16(e,i);i+=2;if(65496!==r)throw new JpegError("SOI not found");r=readUint16(e,i);i+=2;A:for(;65497!==r;){switch(r){case 65472:case 65473:case 65474:a=e[i+7];break A;case 65535:255!==e[i]&&i--}i=skipData(e,i);r=readUint16(e,i);i+=2}return 4!==a&&(3!==a||0!==t)}parse(e,{dnlScanLines:t=null}={}){let i,a,r=0,s=null,n=null,o=0;const g=[],c=[],l=[];let h=readUint16(e,r);r+=2;if(65496!==h)throw new JpegError("SOI not found");h=readUint16(e,r);r+=2;A:for(;65497!==h;){let C,Q,E;switch(h){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const{appData:u,newOffset:d}=readDataBlock(e,r);r=d;65504===h&&74===u[0]&&70===u[1]&&73===u[2]&&70===u[3]&&0===u[4]&&(s={version:{major:u[5],minor:u[6]},densityUnits:u[7],xDensity:u[8]<<8|u[9],yDensity:u[10]<<8|u[11],thumbWidth:u[12],thumbHeight:u[13],thumbData:u.subarray(14,14+3*u[12]*u[13])});65518===h&&65===u[0]&&100===u[1]&&111===u[2]&&98===u[3]&&101===u[4]&&(n={version:u[5]<<8|u[6],flags0:u[7]<<8|u[8],flags1:u[9]<<8|u[10],transformCode:u[11]});break;case 65499:const f=readUint16(e,r);r+=2;const p=f+r-2;let m;for(;r>4){if(t>>4!=1)throw new JpegError("DQT - invalid table spec");for(Q=0;Q<64;Q++){m=Xt[Q];i[m]=readUint16(e,r);r+=2}}else for(Q=0;Q<64;Q++){m=Xt[Q];i[m]=e[r++]}g[15&t]=i}break;case 65472:case 65473:case 65474:if(i)throw new JpegError("Only single frame JPEGs supported");r+=2;i={};i.extended=65473===h;i.progressive=65474===h;i.precision=e[r++];const y=readUint16(e,r);r+=2;i.scanLines=t||y;i.samplesPerLine=readUint16(e,r);r+=2;i.components=[];i.componentIds={};const w=e[r++];let b=0,D=0;for(C=0;C>4,s=15&e[r+1];b>4?c:l)[15&t]=buildHuffmanTable(i,s)}break;case 65501:r+=2;a=readUint16(e,r);r+=2;break;case 65498:const k=1==++o&&!t;r+=2;const R=e[r++],N=[];for(C=0;C>4];s.huffmanTableAC=c[15&n];N.push(s)}const G=e[r++],M=e[r++],U=e[r++];try{r+=decodeScan(e,r,i,N,a,G,M,U>>4,15&U,k)}catch(t){if(t instanceof DNLMarkerError){warn(`${t.message} -- attempting to re-parse the JPEG image.`);return this.parse(e,{dnlScanLines:t.scanLines})}if(t instanceof EOIMarkerError){warn(`${t.message} -- ignoring the rest of the image data.`);break A}throw t}break;case 65500:r+=4;break;case 65535:255!==e[r]&&r--;break;default:const x=findNextFileMarker(e,r-2,r-3);if(x?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+x.invalid);r=x.offset;break}if(!x||r>=e.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break A}throw new JpegError("JpegImage.parse - unknown marker: "+h.toString(16))}h=readUint16(e,r);r+=2}if(!i)throw new JpegError("JpegImage.parse - no frame data found.");this.width=i.samplesPerLine;this.height=i.scanLines;this.jfif=s;this.adobe=n;this.components=[];for(const e of i.components){const t=g[e.quantizationId];t&&(e.quantizationTable=t);this.components.push({index:e.index,output:buildComponentData(0,e),scaleX:e.h/i.maxH,scaleY:e.v/i.maxV,blocksPerLine:e.blocksPerLine,blocksPerColumn:e.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(e,t,i=!1){const a=this.width/e,r=this.height/t;let s,n,o,g,c,l,h,C,Q,E,u,d=0;const f=this.components.length,p=e*t*f,m=new Uint8ClampedArray(p),y=new Uint32Array(e),w=4294967288;let b;for(h=0;h>8)+D[Q+1];return m}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(e){let t,i,a;for(let r=0,s=e.length;r4)throw new JpegError("Unsupported color mode");const s=this._getLinearizedBlockData(e,t,r);if(1===this.numComponents&&(i||a)){const e=s.length*(i?4:3),t=new Uint8ClampedArray(e);let a=0;if(i)!function grayToRGBA(e,t){if(FeatureTest.isLittleEndian)for(let i=0,a=e.length;i0&&(e=e.subarray(t));break}return e}decodeImage(e){if(this.eof)return this.buffer;e=this.#w(e||this.bytes);const t=new JpegImage(this.jpegOptions);t.parse(e);const i=t.getData({width:this.drawWidth,height:this.drawHeight,forceRGBA:this.forceRGBA,forceRGB:this.forceRGB,isSourcePDF:!0});this.buffer=i;this.bufferLength=i.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}async getTransferableImage(){if(!await JpegStream.canUseImageDecoder)return null;const e=this.jpegOptions;if(e.decodeTransform)return null;let t;try{const i=this.canAsyncDecodeImageFromBuffer&&await this.stream.asyncGetBytes()||this.bytes;if(!i)return null;const a=this.#w(i);if(!JpegImage.canUseImageDecoder(a,e.colorTransform))return null;t=new ImageDecoder({data:a,type:"image/jpeg",preferAnimation:!1});return(await t.decode()).image}catch(e){warn(`getTransferableImage - failed: "${e}".`);return null}finally{t?.close()}}}var ii,ai=(ii="undefined"!=typeof document?document.currentScript?.src:void 0,function(e={}){var t,i,a=e;new Promise(((e,a)=>{t=e;i=a}));a.decode=function(e,{numComponents:t=4,isIndexedColormap:i=!1,smaskInData:r=!1}){const s=e.length,n=a._malloc(s);a.HEAPU8.set(e,n);const o=a._jp2_decode(n,s,t>0?t:0,!!i,!!r);a._free(n);if(o){const{errorMessages:e}=a;if(e){delete a.errorMessages;return e}return"Unknown error"}const{imageData:g}=a;a.imageData=null;return g};var r=Object.assign({},a),s="./this.program",quit_=(e,t)=>{throw t},n="";"undefined"!=typeof document&&document.currentScript&&(n=document.currentScript.src);ii&&(n=ii);n=n.startsWith("blob:")?"":n.substr(0,n.replace(/[?#].*/,"").lastIndexOf("/")+1);var o=a.print||console.log.bind(console),g=a.printErr||console.error.bind(console);Object.assign(a,r);r=null;a.arguments&&a.arguments;a.thisProgram&&(s=a.thisProgram);var c,l=a.wasmBinary;function tryParseAsDataURI(e){if(isDataURI(e))return function intArrayFromBase64(e){for(var t=atob(e),i=new Uint8Array(t.length),a=0;ae.startsWith(D);function instantiateSync(e,t){var i,a=function getBinarySync(e){if(e==d&&l)return new Uint8Array(l);var t=tryParseAsDataURI(e);if(t)return t;throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}(e);i=new WebAssembly.Module(a);return[new WebAssembly.Instance(i,t),i]}class ExitStatus{name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`;this.status=e}}var S,callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(a)},k=a.noExitRuntime||!0,R=0,N={},handleException=e=>{if(e instanceof ExitStatus||"unwind"==e)return h;quit_(0,e)},keepRuntimeAlive=()=>k||R>0,_proc_exit=e=>{h=e;if(!keepRuntimeAlive()){a.onExit?.(e);u=!0}quit_(0,new ExitStatus(e))},_exit=(e,t)=>{h=e;_proc_exit(e)},callUserCallback=e=>{if(!u)try{e();(()=>{if(!keepRuntimeAlive())try{_exit(h)}catch(e){handleException(e)}})()}catch(e){handleException(e)}},growMemory=e=>{var t=(e-c.buffer.byteLength+65535)/65536|0;try{c.grow(t);updateMemoryViews();return 1}catch(e){}},G={},getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:s||"./this.program"};for(var t in G)void 0===G[t]?delete e[t]:e[t]=G[t];var i=[];for(var t in e)i.push(`${t}=${e[t]}`);getEnvStrings.strings=i}return getEnvStrings.strings},M=[null,[],[]],U="undefined"!=typeof TextDecoder?new TextDecoder:void 0,UTF8ArrayToString=(e,t=0,i=NaN)=>{for(var a=t+i,r=t;e[r]&&!(r>=a);)++r;if(r-t>16&&e.buffer&&U)return U.decode(e.subarray(t,r));for(var s="";t>10,56320|1023&c)}}else s+=String.fromCharCode((31&n)<<6|o)}else s+=String.fromCharCode(n)}return s},printChar=(e,t)=>{var i=M[e];if(0===t||10===t){(1===e?o:g)(UTF8ArrayToString(i));i.length=0}else i.push(t)},UTF8ToString=(e,t)=>e?UTF8ArrayToString(Q,e,t):"",x={m:()=>function abort(e){a.onAbort?.(e);g(e="Aborted("+e+")");u=!0;e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);i(t);throw t}(""),c:(e,t,i)=>Q.copyWithin(e,t,t+i),l:()=>{k=!1;R=0},n:(e,t)=>{if(N[e]){clearTimeout(N[e].id);delete N[e]}if(!t)return 0;var i=setTimeout((()=>{delete N[e];callUserCallback((()=>H(e,performance.now())))}),t);N[e]={id:i,timeout_ms:t};return 0},g:function _copy_pixels_1(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(t),r=a.HEAP32.subarray(e,e+t);i.set(r)},f:function _copy_pixels_3(e,t,i,r){e>>=2;t>>=2;i>>=2;const s=a.imageData=new Uint8ClampedArray(3*r),n=a.HEAP32.subarray(e,e+r),o=a.HEAP32.subarray(t,t+r),g=a.HEAP32.subarray(i,i+r);for(let e=0;e>=2;t>>=2;i>>=2;r>>=2;const n=a.imageData=new Uint8ClampedArray(4*s),o=a.HEAP32.subarray(e,e+s),g=a.HEAP32.subarray(t,t+s),c=a.HEAP32.subarray(i,i+s),l=a.HEAP32.subarray(r,r+s);for(let e=0;e{var t,i,a=Q.length,r=2147483648;if((e>>>=0)>r)return!1;for(var s=1;s<=4;s*=2){var n=a*(1+.2/s);n=Math.min(n,e+100663296);var o=Math.min(r,(t=Math.max(e,n),i=65536,Math.ceil(t/i)*i));if(growMemory(o))return!0}return!1},p:(e,t)=>{var i=0;getEnvStrings().forEach(((a,r)=>{var s=t+i;E[e+4*r>>2]=s;((e,t)=>{for(var i=0;i{var i=getEnvStrings();E[e>>2]=i.length;var a=0;i.forEach((e=>a+=e.length+1));E[t>>2]=a;return 0},r:e=>52,j:function _fd_seek(e,t,i,a,r){return 70},b:(e,t,i,a)=>{for(var r=0,s=0;s>2],o=E[t+4>>2];t+=8;for(var g=0;g>2]=r;return 0},s:function _gray_to_rgba(e,t){e>>=2;const i=a.imageData=new Uint8ClampedArray(4*t),r=a.HEAP32.subarray(e,e+t);for(let e=0;e>=2;t>>=2;const r=a.imageData=new Uint8ClampedArray(4*i),s=a.HEAP32.subarray(e,e+i),n=a.HEAP32.subarray(t,t+i);for(let e=0;e>=2;t>>=2;i>>=2;const s=a.imageData=new Uint8ClampedArray(4*r),n=a.HEAP32.subarray(e,e+r),o=a.HEAP32.subarray(t,t+r),g=a.HEAP32.subarray(i,i+r);for(let e=0;e0)){!function preRun(){if(a.preRun){"function"==typeof a.preRun&&(a.preRun=[a.preRun]);for(;a.preRun.length;)e=a.preRun.shift(),f.unshift(e)}var e;callRuntimeCallbacks(f)}();if(!(y>0))if(a.setStatus){a.setStatus("Running...");setTimeout((()=>{setTimeout((()=>a.setStatus("")),1);doRun()}),1)}else doRun()}function doRun(){if(!S){S=!0;a.calledRun=!0;if(!u){!function initRuntime(){callRuntimeCallbacks(p)}();t(a);a.onRuntimeInitialized?.();!function postRun(){if(a.postRun){"function"==typeof a.postRun&&(a.postRun=[a.postRun]);for(;a.postRun.length;)e=a.postRun.shift(),m.unshift(e)}var e;callRuntimeCallbacks(m)}()}}}}if(a.preInit){"function"==typeof a.preInit&&(a.preInit=[a.preInit]);for(;a.preInit.length>0;)a.preInit.pop()()}run();return a});const ri=ai;class JpxError extends ct{constructor(e){super(e,"JpxError")}}class JpxImage{static#b=null;static decode(e,t){t||={};this.#b||=ri({warn});const i=this.#b.decode(e,t);if("string"==typeof i)throw new JpxError(i);return i}static cleanup(){this.#b=null}static parseImageProperties(e){let t=e.getByte();for(;t>=0;){const i=t;t=e.getByte();if(65361===(i<<8|t)){e.skip(4);const t=e.getInt32()>>>0,i=e.getInt32()>>>0,a=e.getInt32()>>>0,r=e.getInt32()>>>0;e.skip(16);return{width:t-a,height:i-r,bitsPerComponent:8,componentsCount:e.getUint16()}}}throw new JpxError("No size marker found in JPX stream")}}class JpxStream extends DecodeStream{constructor(e,t,i){super(t);this.stream=e;this.dict=e.dict;this.maybeLength=t;this.params=i}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(e){}readBlock(e){this.decodeImage(null,e)}decodeImage(e,t){if(this.eof)return this.buffer;e||=this.bytes;this.buffer=JpxImage.decode(e,t);this.bufferLength=this.buffer.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}}class LZWStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.cachedData=0;this.bitsCached=0;const a=4096,r={earlyChange:i,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(a),dictionaryLengths:new Uint16Array(a),dictionaryPrevCodes:new Uint16Array(a),currentSequence:new Uint8Array(a),currentSequenceLength:0};for(let e=0;e<256;++e){r.dictionaryValues[e]=e;r.dictionaryLengths[e]=1}this.lzwState=r}readBits(e){let t=this.bitsCached,i=this.cachedData;for(;t>>t&(1<0;if(e<256){C[0]=e;Q=1}else{if(!(e>=258)){if(256===e){l=9;n=258;Q=0;continue}this.eof=!0;delete this.lzwState;break}if(e=0;t--){C[t]=o[i];i=c[i]}}else C[Q++]=C[0]}if(r){c[n]=h;g[n]=g[h]+1;o[n]=C[0];n++;l=n+s&n+s-1?l:0|Math.min(Math.log(n+s)/.6931471805599453+1,12)}h=e;E+=Q;if(a15))throw new FormatError(`Unsupported predictor: ${a}`);this.readBlock=2===a?this.readBlockTiff:this.readBlockPng;this.str=e;this.dict=e.dict;const r=this.colors=i.get("Colors")||1,s=this.bits=i.get("BPC","BitsPerComponent")||8,n=this.columns=i.get("Columns")||1;this.pixBytes=r*s+7>>3;this.rowBytes=n*r*s+7>>3;return this}readBlockTiff(){const e=this.rowBytes,t=this.bufferLength,i=this.ensureBuffer(t+e),a=this.bits,r=this.colors,s=this.str.getBytes(e);this.eof=!s.length;if(this.eof)return;let n,o=0,g=0,c=0,l=0,h=t;if(1===a&&1===r)for(n=0;n>1;e^=e>>2;e^=e>>4;o=(1&e)<<7;i[h++]=e}else if(8===a){for(n=0;n>8&255;i[h++]=255&e}}else{const e=new Uint8Array(r+1),h=(1<>c-a)&h;c-=a;g=g<=8){i[Q++]=g>>l-8&255;l-=8}}l>0&&(i[Q++]=(g<<8-l)+(o&(1<<8-l)-1))}this.bufferLength+=e}readBlockPng(){const e=this.rowBytes,t=this.pixBytes,i=this.str.getByte(),a=this.str.getBytes(e);this.eof=!a.length;if(this.eof)return;const r=this.bufferLength,s=this.ensureBuffer(r+e);let n=s.subarray(r-e,r);0===n.length&&(n=new Uint8Array(e));let o,g,c,l=r;switch(i){case 0:for(o=0;o>1)+a[o];for(;o>1)+a[o]&255;l++}break;case 4:for(o=0;o0){const e=this.str.getBytes(a);t.set(e,i);i+=a}}else{a=257-a;const r=e[1];t=this.ensureBuffer(i+a+1);for(let e=0;e>")&&this.buf1!==Et;){if(!(this.buf1 instanceof Name)){info("Malformed dictionary: key must be a name object");this.shift();continue}const t=this.buf1.name;this.shift();if(this.buf1===Et)break;a.set(t,this.getObj(e))}if(this.buf1===Et){if(this.recoveryMode)return a;throw new ParserEOFException("End of file inside dictionary.")}if(isCmd(this.buf2,"stream"))return this.allowStreams?this.makeStream(a,e):a;this.shift();return a;default:return t}if(Number.isInteger(t)){if(Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")){const e=Ref.get(t,this.buf1);this.shift();this.shift();return e}return t}return"string"==typeof t&&e?e.decryptString(t):t}findDefaultInlineStreamEnd(e){const{knownCommands:t}=this.lexer,i=e.pos;let a,r,s=0;for(;-1!==(a=e.getByte());)if(0===s)s=69===a?1:0;else if(1===s)s=73===a?2:0;else if(32===a||10===a||13===a){r=e.pos;const i=e.peekBytes(15),n=i.length;if(0===n)break;for(let e=0;e127))){s=0;break}}if(2!==s)continue;if(!t){warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const o=new Lexer(new Stream(i.slice()),t);o._hexStringWarn=()=>{};let g=0;for(;;){const e=o.getObj();if(e===Et){s=0;break}if(e instanceof Cmd){const i=t[e.cmd];if(!i){s=0;break}if(i.variableArgs?g<=i.numArgs:g===i.numArgs)break;g=0}else g++}if(2===s)break}else s=0;if(-1===a){warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker");if(r){warn('... trying to recover by using the last "EI" occurrence.');e.skip(-(e.pos-r))}}let n=4;e.skip(-n);a=e.peekByte();e.skip(n);isWhiteSpace(a)||n--;return e.pos-n-i}findDCTDecodeInlineStreamEnd(e){const t=e.pos;let i,a,r=!1;for(;-1!==(i=e.getByte());)if(255===i){switch(e.getByte()){case 0:break;case 255:e.skip(-1);break;case 217:r=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:a=e.getUint16();a>2?e.skip(a-2):e.skip(-2)}if(r)break}const s=e.pos-t;if(-1===i){warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead.");e.skip(-s);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return s}findASCII85DecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte());)if(126===i){const t=e.pos;i=e.peekByte();for(;isWhiteSpace(i);){e.skip();i=e.peekByte()}if(62===i){e.skip();break}if(e.pos>t){const t=e.peekBytes(2);if(69===t[0]&&73===t[1])break}}const a=e.pos-t;if(-1===i){warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}findASCIIHexDecodeInlineStreamEnd(e){const t=e.pos;let i;for(;-1!==(i=e.getByte())&&62!==i;);const a=e.pos-t;if(-1===i){warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-a);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return a}inlineStreamSkipEI(e){let t,i=0;for(;-1!==(t=e.getByte());)if(0===i)i=69===t?1:0;else if(1===i)i=73===t?2:0;else if(2===i)break}makeInlineImage(e){const t=this.lexer,i=t.stream,a=Object.create(null);let r;for(;!isCmd(this.buf1,"ID")&&this.buf1!==Et;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");const t=this.buf1.name;this.shift();if(this.buf1===Et)break;a[t]=this.getObj(e)}-1!==t.beginInlineImagePos&&(r=i.pos-t.beginInlineImagePos);const s=this.xref.fetchIfRef(a.F||a.Filter);let n;if(s instanceof Name)n=s.name;else if(Array.isArray(s)){const e=this.xref.fetchIfRef(s[0]);e instanceof Name&&(n=e.name)}const o=i.pos;let g,c;switch(n){case"DCT":case"DCTDecode":g=this.findDCTDecodeInlineStreamEnd(i);break;case"A85":case"ASCII85Decode":g=this.findASCII85DecodeInlineStreamEnd(i);break;case"AHx":case"ASCIIHexDecode":g=this.findASCIIHexDecodeInlineStreamEnd(i);break;default:g=this.findDefaultInlineStreamEnd(i)}if(g<1e3&&r>0){const e=i.pos;i.pos=t.beginInlineImagePos;c=function getInlineImageCacheKey(e){const t=[],i=e.length;let a=0;for(;a=a){let a=!1;for(const e of r){const t=e.length;let r=0;for(;r=s){a=!0;break}if(r>=t){if(isWhiteSpace(n[g+o+r])){info(`Found "${bytesToString([...i,...e])}" when searching for endstream command.`);a=!0}break}}if(a){t.pos+=g;return t.pos-e}}g++}t.pos+=o}return-1}makeStream(e,t){const i=this.lexer;let a=i.stream;i.skipToNextLine();const r=a.pos-1;let s=e.get("Length");if(!Number.isInteger(s)){info(`Bad length "${s&&s.toString()}" in stream.`);s=0}a.pos=r+s;i.nextChar();if(this.tryShift()&&isCmd(this.buf2,"endstream"))this.shift();else{s=this.#D(r);if(s<0)throw new FormatError("Missing endstream command.");i.nextChar();this.shift();this.shift()}this.shift();a=a.makeSubStream(r,s,e);t&&(a=t.createStream(a,s));a=this.filter(a,e,s);a.dict=e;return a}filter(e,t,i){let a=t.get("F","Filter"),r=t.get("DP","DecodeParms");if(a instanceof Name){Array.isArray(r)&&warn("/DecodeParms should not be an Array, when /Filter is a Name.");return this.makeFilter(e,a.name,i,r)}let s=i;if(Array.isArray(a)){const t=a,i=r;for(let n=0,o=t.length;n=48&&e<=57?15&e:e>=65&&e<=70||e>=97&&e<=102?9+(15&e):-1}class Lexer{constructor(e,t=null){this.stream=e;this.nextChar();this.strBuf=[];this.knownCommands=t;this._hexStringNumWarn=0;this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let e=this.currentChar,t=!1,i=0,a=1;if(45===e){a=-1;e=this.nextChar();45===e&&(e=this.nextChar())}else 43===e&&(e=this.nextChar());if(10===e||13===e)do{e=this.nextChar()}while(10===e||13===e);if(46===e){i=10;e=this.nextChar()}if(e<48||e>57){const t=`Invalid number: ${String.fromCharCode(e)} (charCode ${e})`;if(isWhiteSpace(e)||-1===e){info(`Lexer.getNumber - "${t}".`);return 0}throw new FormatError(t)}let r=e-48,s=0,n=1;for(;(e=this.nextChar())>=0;)if(e>=48&&e<=57){const a=e-48;if(t)s=10*s+a;else{0!==i&&(i*=10);r=10*r+a}}else if(46===e){if(0!==i)break;i=1}else if(45===e)warn("Badly formatted number: minus sign in the middle");else{if(69!==e&&101!==e)break;e=this.peekChar();if(43===e||45===e){n=45===e?-1:1;this.nextChar()}else if(e<48||e>57)break;t=!0}0!==i&&(r/=i);t&&(r*=10**(n*s));return a*r}getString(){let e=1,t=!1;const i=this.strBuf;i.length=0;let a=this.nextChar();for(;;){let r=!1;switch(0|a){case-1:warn("Unterminated string");t=!0;break;case 40:++e;i.push("(");break;case 41:if(0==--e){this.nextChar();t=!0}else i.push(")");break;case 92:a=this.nextChar();switch(a){case-1:warn("Unterminated string");t=!0;break;case 110:i.push("\n");break;case 114:i.push("\r");break;case 116:i.push("\t");break;case 98:i.push("\b");break;case 102:i.push("\f");break;case 92:case 40:case 41:i.push(String.fromCharCode(a));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let e=15&a;a=this.nextChar();r=!0;if(a>=48&&a<=55){e=(e<<3)+(15&a);a=this.nextChar();if(a>=48&&a<=55){r=!1;e=(e<<3)+(15&a)}}i.push(String.fromCharCode(e));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:i.push(String.fromCharCode(a))}break;default:i.push(String.fromCharCode(a))}if(t)break;r||(a=this.nextChar())}return i.join("")}getName(){let e,t;const i=this.strBuf;i.length=0;for(;(e=this.nextChar())>=0&&!si[e];)if(35===e){e=this.nextChar();if(si[e]){warn("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number.");i.push("#");break}const a=toHexDigit(e);if(-1!==a){t=e;e=this.nextChar();const r=toHexDigit(e);if(-1===r){warn(`Lexer_getName: Illegal digit (${String.fromCharCode(e)}) in hexadecimal number.`);i.push("#",String.fromCharCode(t));if(si[e])break;i.push(String.fromCharCode(e));continue}i.push(String.fromCharCode(a<<4|r))}else i.push("#",String.fromCharCode(e))}else i.push(String.fromCharCode(e));i.length>127&&warn(`Name token is longer than allowed by the spec: ${i.length}`);return Name.get(i.join(""))}_hexStringWarn(e){5!=this._hexStringNumWarn++?this._hexStringNumWarn>5||warn(`getHexString - ignoring invalid character: ${e}`):warn("getHexString - ignoring additional invalid characters.")}getHexString(){const e=this.strBuf;e.length=0;let t=this.currentChar,i=-1,a=-1;this._hexStringNumWarn=0;for(;;){if(t<0){warn("Unterminated hex string");break}if(62===t){this.nextChar();break}if(1!==si[t]){a=toHexDigit(t);if(-1===a)this._hexStringWarn(t);else if(-1===i)i=a;else{e.push(String.fromCharCode(i<<4|a));i=-1}t=this.nextChar()}else t=this.nextChar()}-1!==i&&e.push(String.fromCharCode(i<<4));return e.join("")}getObj(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Et;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(1!==si[t])break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:this.nextChar();return Cmd.get("[");case 93:this.nextChar();return Cmd.get("]");case 60:t=this.nextChar();if(60===t){this.nextChar();return Cmd.get("<<")}return this.getHexString();case 62:t=this.nextChar();if(62===t){this.nextChar();return Cmd.get(">>")}return Cmd.get(">");case 123:this.nextChar();return Cmd.get("{");case 125:this.nextChar();return Cmd.get("}");case 41:this.nextChar();throw new FormatError(`Illegal character: ${t}`)}let i=String.fromCharCode(t);if(t<32||t>127){const e=this.peekChar();if(e>=32&&e<=127){this.nextChar();return Cmd.get(i)}}const a=this.knownCommands;let r=void 0!==a?.[i];for(;(t=this.nextChar())>=0&&!si[t];){const e=i+String.fromCharCode(t);if(r&&void 0===a[e])break;if(128===i.length)throw new FormatError(`Command token too long: ${i.length}`);i=e;r=void 0!==a?.[i]}if("true"===i)return!0;if("false"===i)return!1;if("null"===i)return null;"BI"===i&&(this.beginInlineImagePos=this.stream.pos);return Cmd.get(i)}skipToNextLine(){let e=this.currentChar;for(;e>=0;){if(13===e){e=this.nextChar();10===e&&this.nextChar();break}if(10===e){this.nextChar();break}e=this.nextChar()}}}class Linearization{static create(e){function getInt(e,t,i=!1){const a=e.get(t);if(Number.isInteger(a)&&(i?a>=0:a>0))return a;throw new Error(`The "${t}" parameter in the linearization dictionary is invalid.`)}const t=new Parser({lexer:new Lexer(e),xref:null}),i=t.getObj(),a=t.getObj(),r=t.getObj(),s=t.getObj();let n,o;if(!(Number.isInteger(i)&&Number.isInteger(a)&&isCmd(r,"obj")&&s instanceof Dict&&"number"==typeof(n=s.get("Linearized"))&&n>0))return null;if((o=getInt(s,"L"))!==e.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:o,hints:function getHints(e){const t=e.get("H");let i;if(Array.isArray(t)&&(2===(i=t.length)||4===i)){for(let e=0;e0))throw new Error(`Hint (${e}) in the linearization dictionary is invalid.`)}return t}throw new Error("Hint array in the linearization dictionary is invalid.")}(s),objectNumberFirst:getInt(s,"O"),endFirst:getInt(s,"E"),numPages:getInt(s,"N"),mainXRefEntriesOffset:getInt(s,"T"),pageFirst:s.has("P")?getInt(s,"P",!0):0}}}const ni=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],oi=2**24-1;class CMap{constructor(e=!1){this.codespaceRanges=[[],[],[],[]];this.numCodespaceRanges=0;this._map=[];this.name="";this.vertical=!1;this.useCMap=null;this.builtInCMap=e}addCodespaceRange(e,t,i){this.codespaceRanges[e-1].push(t,i);this.numCodespaceRanges++}mapCidRange(e,t,i){if(t-e>oi)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;e<=t;)this._map[e++]=i++}mapBfRange(e,t,i){if(t-e>oi)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const a=i.length-1;for(;e<=t;){this._map[e++]=i;const t=i.charCodeAt(a)+1;t>255?i=i.substring(0,a-1)+String.fromCharCode(i.charCodeAt(a-1)+1)+"\0":i=i.substring(0,a)+String.fromCharCode(t)}}mapBfRangeToArray(e,t,i){if(t-e>oi)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const a=i.length;let r=0;for(;e<=t&&r>>0;const n=r[s];for(let e=0,t=n.length;e=t&&a<=r){i.charcode=a;i.length=s+1;return}}}i.charcode=0;i.length=1}getCharCodeLength(e){const t=this.codespaceRanges;for(let i=0,a=t.length;i=r&&e<=s)return i+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let e=0;e<65536;e++)if(this._map[e]!==e)return!1;return!0}}class IdentityCMap extends CMap{constructor(e,t){super();this.vertical=e;this.addCodespaceRange(t,0,65535)}mapCidRange(e,t,i){unreachable("should not call mapCidRange")}mapBfRange(e,t,i){unreachable("should not call mapBfRange")}mapBfRangeToArray(e,t,i){unreachable("should not call mapBfRangeToArray")}mapOne(e,t){unreachable("should not call mapCidOne")}lookup(e){return Number.isInteger(e)&&e<=65535?e:void 0}contains(e){return Number.isInteger(e)&&e<=65535}forEach(e){for(let t=0;t<=65535;t++)e(t,t)}charCodeOf(e){return Number.isInteger(e)&&e<=65535?e:-1}getMap(){const e=new Array(65536);for(let t=0;t<=65535;t++)e[t]=t;return e}get length(){return 65536}get isIdentityCMap(){unreachable("should not access .isIdentityCMap")}}function strToInt(e){let t=0;for(let i=0;i>>0}function expectString(e){if("string"!=typeof e)throw new FormatError("Malformed CMap: expected string.")}function expectInt(e){if(!Number.isInteger(e))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(e,t){for(;;){let i=t.getObj();if(i===Et)break;if(isCmd(i,"endbfchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const r=i;e.mapOne(a,r)}}function parseBfRange(e,t){for(;;){let i=t.getObj();if(i===Et)break;if(isCmd(i,"endbfrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const r=strToInt(i);i=t.getObj();if(Number.isInteger(i)||"string"==typeof i){const t=Number.isInteger(i)?String.fromCharCode(i):i;e.mapBfRange(a,r,t)}else{if(!isCmd(i,"["))break;{i=t.getObj();const s=[];for(;!isCmd(i,"]")&&i!==Et;){s.push(i);i=t.getObj()}e.mapBfRangeToArray(a,r,s)}}}throw new FormatError("Invalid bf range.")}function parseCidChar(e,t){for(;;){let i=t.getObj();if(i===Et)break;if(isCmd(i,"endcidchar"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectInt(i);const r=i;e.mapOne(a,r)}}function parseCidRange(e,t){for(;;){let i=t.getObj();if(i===Et)break;if(isCmd(i,"endcidrange"))return;expectString(i);const a=strToInt(i);i=t.getObj();expectString(i);const r=strToInt(i);i=t.getObj();expectInt(i);const s=i;e.mapCidRange(a,r,s)}}function parseCodespaceRange(e,t){for(;;){let i=t.getObj();if(i===Et)break;if(isCmd(i,"endcodespacerange"))return;if("string"!=typeof i)break;const a=strToInt(i);i=t.getObj();if("string"!=typeof i)break;const r=strToInt(i);e.addCodespaceRange(i.length,a,r)}throw new FormatError("Invalid codespace range.")}function parseWMode(e,t){const i=t.getObj();Number.isInteger(i)&&(e.vertical=!!i)}function parseCMapName(e,t){const i=t.getObj();i instanceof Name&&(e.name=i.name)}async function parseCMap(e,t,i,a){let r,s;A:for(;;)try{const i=t.getObj();if(i===Et)break;if(i instanceof Name){"WMode"===i.name?parseWMode(e,t):"CMapName"===i.name&&parseCMapName(e,t);r=i}else if(i instanceof Cmd)switch(i.cmd){case"endcmap":break A;case"usecmap":r instanceof Name&&(s=r.name);break;case"begincodespacerange":parseCodespaceRange(e,t);break;case"beginbfchar":parseBfChar(e,t);break;case"begincidchar":parseCidChar(e,t);break;case"beginbfrange":parseBfRange(e,t);break;case"begincidrange":parseCidRange(e,t)}}catch(e){if(e instanceof MissingDataException)throw e;warn("Invalid cMap data: "+e);continue}!a&&s&&(a=s);return a?extendCMap(e,i,a):e}async function extendCMap(e,t,i){e.useCMap=await createBuiltInCMap(i,t);if(0===e.numCodespaceRanges){const t=e.useCMap.codespaceRanges;for(let i=0;iextendCMap(r,t,e)));const s=new Lexer(new Stream(i));return parseCMap(r,s,t,null)}class CMapFactory{static async create({encoding:e,fetchBuiltInCMap:t,useCMap:i}){if(e instanceof Name)return createBuiltInCMap(e.name,t);if(e instanceof BaseStream){const a=await parseCMap(new CMap,new Lexer(e),t,i);return a.isIdentityCMap?createBuiltInCMap(a.name,t):a}throw new Error("Encoding required.")}}__webpack_require__(1795);const gi=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],Ii=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],ci=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],li=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],hi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],Ci=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],Bi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],Qi=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],Ei=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],ui=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(e){switch(e){case"WinAnsiEncoding":return Qi;case"StandardEncoding":return Bi;case"MacRomanEncoding":return Ci;case"SymbolSetEncoding":return Ei;case"ZapfDingbatsEncoding":return ui;case"ExpertEncoding":return li;case"MacExpertEncoding":return hi;default:return null}}const di=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],fi=391,pi=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],mi=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]+e[t-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]-e[t-1]}},{id:"div",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]/e[t-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(e,t){e[t-1]=-e[t-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]*e[t-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(e,t,i){this.bytes=e.getBytes();this.properties=t;this.seacAnalysisEnabled=!!i}parse(){const e=this.properties,t=new CFF;this.cff=t;const i=this.parseHeader(),a=this.parseIndex(i.endPos),r=this.parseIndex(a.endPos),s=this.parseIndex(r.endPos),n=this.parseIndex(s.endPos),o=this.parseDict(r.obj.get(0)),g=this.createDict(CFFTopDict,o,t.strings);t.header=i.obj;t.names=this.parseNameIndex(a.obj);t.strings=this.parseStringIndex(s.obj);t.topDict=g;t.globalSubrIndex=n.obj;this.parsePrivateDict(t.topDict);t.isCIDFont=g.hasName("ROS");const c=g.getByName("CharStrings"),l=this.parseIndex(c).obj,h=g.getByName("FontMatrix");h&&(e.fontMatrix=h);const C=g.getByName("FontBBox");if(C){e.ascent=Math.max(C[3],C[1]);e.descent=Math.min(C[1],C[3]);e.ascentScaled=!0}let Q,E;if(t.isCIDFont){const e=this.parseIndex(g.getByName("FDArray")).obj;for(let i=0,a=e.count;i=t)throw new FormatError("Invalid CFF header");if(0!==i){info("cff data is shifted");e=e.subarray(i);this.bytes=e}const a=e[0],r=e[1],s=e[2],n=e[3];return{obj:new CFFHeader(a,r,s,n),endPos:s}}parseDict(e){let t=0;function parseOperand(){let i=e[t++];if(30===i)return function parseFloatOperand(){let i="";const a=15,r=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],s=e.length;for(;t>4,o=15&s;if(n===a)break;i+=r[n];if(o===a)break;i+=r[o]}return parseFloat(i)}();if(28===i){i=e[t++];i=(i<<24|e[t++]<<16)>>16;return i}if(29===i){i=e[t++];i=i<<8|e[t++];i=i<<8|e[t++];i=i<<8|e[t++];return i}if(i>=32&&i<=246)return i-139;if(i>=247&&i<=250)return 256*(i-247)+e[t++]+108;if(i>=251&&i<=254)return-256*(i-251)-e[t++]-108;warn('CFFParser_parseDict: "'+i+'" is a reserved command.');return NaN}let i=[];const a=[];t=0;const r=e.length;for(;t10)return!1;let r=e.stackSize;const s=e.stack;let n=t.length;for(let o=0;o>16;o+=2;r++}else if(14===g){if(r>=4){r-=4;if(this.seacAnalysisEnabled){e.seac=s.slice(r,r+4);return!1}}c=pi[g]}else if(g>=32&&g<=246){s[r]=g-139;r++}else if(g>=247&&g<=254){s[r]=g<251?(g-247<<8)+t[o]+108:-(g-251<<8)-t[o]-108;o++;r++}else if(255===g){s[r]=(t[o]<<24|t[o+1]<<16|t[o+2]<<8|t[o+3])/65536;o+=4;r++}else if(19===g||20===g){e.hints+=r>>1;if(0===e.hints){t.copyWithin(o-1,o,-1);o-=1;n-=1;continue}o+=e.hints+7>>3;r%=2;c=pi[g]}else{if(10===g||29===g){const t=10===g?i:a;if(!t){c=pi[g];warn("Missing subrsIndex for "+c.id);return!1}let n=32768;t.count<1240?n=107:t.count<33900&&(n=1131);const o=s[--r]+n;if(o<0||o>=t.count||isNaN(o)){c=pi[g];warn("Out of bounds subrIndex for "+c.id);return!1}e.stackSize=r;e.callDepth++;if(!this.parseCharString(e,t.get(o),i,a))return!1;e.callDepth--;r=e.stackSize;continue}if(11===g){e.stackSize=r;return!0}if(0===g&&o===t.length){t[o-1]=14;c=pi[14]}else{if(9===g){t.copyWithin(o-1,o,-1);o-=1;n-=1;continue}c=pi[g]}}if(c){if(c.stem){e.hints+=r>>1;if(3===g||23===g)e.hasVStems=!0;else if(e.hasVStems&&(1===g||18===g)){warn("CFF stem hints are in wrong order");t[o-1]=1===g?3:23}}if("min"in c&&!e.undefStack&&r=2&&c.stem?r%=2:r>1&&warn("Found too many parameters for stack-clearing command");r>0&&(e.width=s[r-1])}if("stackDelta"in c){"stackFn"in c&&c.stackFn(s,r);r+=c.stackDelta}else if(c.stackClearing)r=0;else if(c.resetStack){r=0;e.undefStack=!1}else if(c.undefStack){r=0;e.undefStack=!0;e.firstStackClearing=!1}}}n=r.length){warn("Invalid fd index for glyph index.");h=!1}if(h){Q=r[e].privateDict;C=Q.subrsIndex}}else t&&(C=t);h&&(h=this.parseCharString(l,g,C,i));if(null!==l.width){const e=Q.getByName("nominalWidthX");o[c]=e+l.width}else{const e=Q.getByName("defaultWidthX");o[c]=e}null!==l.seac&&(n[c]=l.seac);h||e.set(c,new Uint8Array([14]))}return{charStrings:e,seacs:n,widths:o}}emptyPrivateDictionary(e){const t=this.createDict(CFFPrivateDict,[],e.strings);e.setByKey(18,[0,0]);e.privateDict=t}parsePrivateDict(e){if(!e.hasName("Private")){this.emptyPrivateDictionary(e);return}const t=e.getByName("Private");if(!Array.isArray(t)||2!==t.length){e.removeByName("Private");return}const i=t[0],a=t[1];if(0===i||a>=this.bytes.length){this.emptyPrivateDictionary(e);return}const r=a+i,s=this.bytes.subarray(a,r),n=this.parseDict(s),o=this.createDict(CFFPrivateDict,n,e.strings);e.privateDict=o;0===o.getByName("ExpansionFactor")&&o.setByName("ExpansionFactor",.06);if(!o.getByName("Subrs"))return;const g=o.getByName("Subrs"),c=a+g;if(0===g||c>=this.bytes.length){this.emptyPrivateDictionary(e);return}const l=this.parseIndex(c);o.subrsIndex=l.obj}parseCharsets(e,t,i,a){if(0===e)return new CFFCharset(!0,bi.ISO_ADOBE,gi);if(1===e)return new CFFCharset(!0,bi.EXPERT,Ii);if(2===e)return new CFFCharset(!0,bi.EXPERT_SUBSET,ci);const r=this.bytes,s=e,n=r[e++],o=[a?0:".notdef"];let g,c,l;t-=1;switch(n){case 0:for(l=0;l=65535){warn("Not enough space in charstrings to duplicate first glyph.");return}const e=this.charStrings.get(0);this.charStrings.add(e);this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(e){if(e<0||e>=this.charStrings.count)return!1;return this.charStrings.get(e).length>0}}class CFFHeader{constructor(e,t,i,a){this.major=e;this.minor=t;this.hdrSize=i;this.offSize=a}}class CFFStrings{constructor(){this.strings=[]}get(e){return e>=0&&e<=390?di[e]:e-fi<=this.strings.length?this.strings[e-fi]:di[0]}getSID(e){let t=di.indexOf(e);if(-1!==t)return t;t=this.strings.indexOf(e);return-1!==t?t+fi:-1}add(e){this.strings.push(e)}get count(){return this.strings.length}}class CFFIndex{constructor(){this.objects=[];this.length=0}add(e){this.length+=e.length;this.objects.push(e)}set(e,t){this.length+=t.length-this.objects[e].length;this.objects[e]=t}get(e){return this.objects[e]}get count(){return this.objects.length}}class CFFDict{constructor(e,t){this.keyToNameMap=e.keyToNameMap;this.nameToKeyMap=e.nameToKeyMap;this.defaults=e.defaults;this.types=e.types;this.opcodes=e.opcodes;this.order=e.order;this.strings=t;this.values=Object.create(null)}setByKey(e,t){if(!(e in this.keyToNameMap))return!1;if(0===t.length)return!0;for(const i of t)if(isNaN(i)){warn(`Invalid CFFDict value: "${t}" for key "${e}".`);return!0}const i=this.types[e];"num"!==i&&"sid"!==i&&"offset"!==i||(t=t[0]);this.values[e]=t;return!0}setByName(e,t){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name "${e}"`);this.values[this.nameToKeyMap[e]]=t}hasName(e){return this.nameToKeyMap[e]in this.values}getByName(e){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name ${e}"`);const t=this.nameToKeyMap[e];return t in this.values?this.values[t]:this.defaults[t]}removeByName(e){delete this.values[this.nameToKeyMap[e]]}static createTables(e){const t={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const i of e){const e=Array.isArray(i[0])?(i[0][0]<<8)+i[0][1]:i[0];t.keyToNameMap[e]=i[1];t.nameToKeyMap[i[1]]=e;t.types[e]=i[2];t.defaults[e]=i[3];t.opcodes[e]=Array.isArray(i[0])?i[0]:[i[0]];t.order.push(e)}return t}}const yi=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class CFFTopDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(yi))}constructor(e){super(CFFTopDict.tables,e);this.privateDict=null}}const wi=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class CFFPrivateDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(wi))}constructor(e){super(CFFPrivateDict.tables,e);this.subrsIndex=null}}const bi={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class CFFCharset{constructor(e,t,i,a){this.predefined=e;this.format=t;this.charset=i;this.raw=a}}class CFFEncoding{constructor(e,t,i,a){this.predefined=e;this.format=t;this.encoding=i;this.raw=a}}class CFFFDSelect{constructor(e,t){this.format=e;this.fdSelect=t}getFDIndex(e){return e<0||e>=this.fdSelect.length?-1:this.fdSelect[e]}}class CFFOffsetTracker{constructor(){this.offsets=Object.create(null)}isTracking(e){return e in this.offsets}track(e,t){if(e in this.offsets)throw new FormatError(`Already tracking location of ${e}`);this.offsets[e]=t}offset(e){for(const t in this.offsets)this.offsets[t]+=e}setEntryLocation(e,t,i){if(!(e in this.offsets))throw new FormatError(`Not tracking location of ${e}`);const a=i.data,r=this.offsets[e];for(let e=0,i=t.length;e>24&255;a[n]=c>>16&255;a[o]=c>>8&255;a[g]=255&c}}}class CFFCompiler{constructor(e){this.cff=e}compile(){const e=this.cff,t={data:[],length:0,add(e){try{this.data.push(...e)}catch{this.data=this.data.concat(e)}this.length=this.data.length}},i=this.compileHeader(e.header);t.add(i);const a=this.compileNameIndex(e.names);t.add(a);if(e.isCIDFont&&e.topDict.hasName("FontMatrix")){const t=e.topDict.getByName("FontMatrix");e.topDict.removeByName("FontMatrix");for(const i of e.fdArray){let e=t.slice(0);i.hasName("FontMatrix")&&(e=Util.transform(e,i.getByName("FontMatrix")));i.setByName("FontMatrix",e)}}const r=e.topDict.getByName("XUID");r?.length>16&&e.topDict.removeByName("XUID");e.topDict.setByName("charset",0);let s=this.compileTopDicts([e.topDict],t.length,e.isCIDFont);t.add(s.output);const n=s.trackers[0],o=this.compileStringIndex(e.strings.strings);t.add(o);const g=this.compileIndex(e.globalSubrIndex);t.add(g);if(e.encoding&&e.topDict.hasName("Encoding"))if(e.encoding.predefined)n.setEntryLocation("Encoding",[e.encoding.format],t);else{const i=this.compileEncoding(e.encoding);n.setEntryLocation("Encoding",[t.length],t);t.add(i)}const c=this.compileCharset(e.charset,e.charStrings.count,e.strings,e.isCIDFont);n.setEntryLocation("charset",[t.length],t);t.add(c);const l=this.compileCharStrings(e.charStrings);n.setEntryLocation("CharStrings",[t.length],t);t.add(l);if(e.isCIDFont){n.setEntryLocation("FDSelect",[t.length],t);const i=this.compileFDSelect(e.fdSelect);t.add(i);s=this.compileTopDicts(e.fdArray,t.length,!0);n.setEntryLocation("FDArray",[t.length],t);t.add(s.output);const a=s.trackers;this.compilePrivateDicts(e.fdArray,a,t)}this.compilePrivateDicts([e.topDict],[n],t);t.add([0]);return t.data}encodeNumber(e){return Number.isInteger(e)?this.encodeInteger(e):this.encodeFloat(e)}static get EncodeFloatRegExp(){return shadow(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(e){let t=e.toString();const i=CFFCompiler.EncodeFloatRegExp.exec(t);if(i){const a=parseFloat("1e"+((i[2]?+i[2]:0)+i[1].length));t=(Math.round(e*a)/a).toString()}let a,r,s="";for(a=0,r=t.length;a=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?[28,e>>8&255,255&e]:[29,e>>24&255,e>>16&255,e>>8&255,255&e];return t}compileHeader(e){return[e.major,e.minor,4,e.offSize]}compileNameIndex(e){const t=new CFFIndex;for(const i of e){const e=Math.min(i.length,127);let a=new Array(e);for(let t=0;t"~"||"["===e||"]"===e||"("===e||")"===e||"{"===e||"}"===e||"<"===e||">"===e||"/"===e||"%"===e)&&(e="_");a[t]=e}a=a.join("");""===a&&(a="Bad_Font_Name");t.add(stringToBytes(a))}return this.compileIndex(t)}compileTopDicts(e,t,i){const a=[];let r=new CFFIndex;for(const s of e){if(i){s.removeByName("CIDFontVersion");s.removeByName("CIDFontRevision");s.removeByName("CIDFontType");s.removeByName("CIDCount");s.removeByName("UIDBase")}const e=new CFFOffsetTracker,n=this.compileDict(s,e);a.push(e);r.add(n);e.offset(t)}r=this.compileIndex(r,a);return{trackers:a,output:r}}compilePrivateDicts(e,t,i){for(let a=0,r=e.length;a>8&255,255&s]);else{r=new Uint8Array(1+2*s);r[0]=0;let t=0;const a=e.charset.length;let n=!1;for(let s=1;s>8&255;r[s+1]=255&o}}return this.compileTypedArray(r)}compileEncoding(e){return this.compileTypedArray(e.raw)}compileFDSelect(e){const t=e.format;let i,a;switch(t){case 0:i=new Uint8Array(1+e.fdSelect.length);i[0]=t;for(a=0;a>8&255,255&r,s];for(a=1;a>8&255,255&a,t);s=t}}const o=(n.length-3)/3;n[1]=o>>8&255;n[2]=255&o;n.push(a>>8&255,255&a);i=new Uint8Array(n)}return this.compileTypedArray(i)}compileTypedArray(e){return Array.from(e)}compileIndex(e,t=[]){const i=e.objects,a=i.length;if(0===a)return[0,0];const r=[a>>8&255,255&a];let s,n,o=1;for(s=0;s>8&255,255&g):3===n?r.push(g>>16&255,g>>8&255,255&g):r.push(g>>>24&255,g>>16&255,g>>8&255,255&g);i[s]&&(g+=i[s].length)}for(s=0;s=5&&t<=7))return-1;a=e.substring(1)}if(a===a.toUpperCase()){i=parseInt(a,16);if(i>=0)return i}}return-1}const ki=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function getUnicodeRangeFor(e,t=-1){if(-1!==t){const i=ki[t];for(let a=0,r=i.length;a=i[a]&&e<=i[a+1])return t}for(let t=0,i=ki.length;t=i[a]&&e<=i[a+1])return t}return-1}const Ri=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),Ni=new Map;const Gi=!0,Mi=1,xi=2,Hi=4,Ji=32,vi=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(e,t){if(void 0!==t[e])return e;const i=getUnicodeForGlyph(e,t);if(-1!==i)for(const e in t)if(t[e]===i)return e;info("Unable to recover a standard glyph name for: "+e);return e}function type1FontGlyphMapping(e,t,i){const a=Object.create(null);let r,s,n;const o=!!(e.flags&Hi);if(e.isInternalFont){n=t;for(s=0;s=0?r:0}}else if(e.baseEncodingName){n=getEncoding(e.baseEncodingName);for(s=0;s=0?r:0}}else if(o)for(s in t)a[s]=t[s];else{n=Bi;for(s=0;s=0?r:0}}const g=e.differences;let c;if(g)for(s in g){const e=g[s];r=i.indexOf(e);if(-1===r){c||(c=Di());const t=recoverGlyphName(e,c);t!==e&&(r=i.indexOf(t))}a[s]=r>=0?r:0}return a}function normalizeFontName(e){return e.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const Yi=getLookupTableFactory((e=>{e[8211]=65074;e[8212]=65073;e[8229]=65072;e[8230]=65049;e[12289]=65041;e[12290]=65042;e[12296]=65087;e[12297]=65088;e[12298]=65085;e[12299]=65086;e[12300]=65089;e[12301]=65090;e[12302]=65091;e[12303]=65092;e[12304]=65083;e[12305]=65084;e[12308]=65081;e[12309]=65082;e[12310]=65047;e[12311]=65048;e[65103]=65076;e[65281]=65045;e[65288]=65077;e[65289]=65078;e[65292]=65040;e[65306]=65043;e[65307]=65044;e[65311]=65046;e[65339]=65095;e[65341]=65096;e[65343]=65075;e[65371]=65079;e[65373]=65080})),Ki=getLookupTableFactory((function(e){e["Times-Roman"]="Times-Roman";e.Helvetica="Helvetica";e.Courier="Courier";e.Symbol="Symbol";e["Times-Bold"]="Times-Bold";e["Helvetica-Bold"]="Helvetica-Bold";e["Courier-Bold"]="Courier-Bold";e.ZapfDingbats="ZapfDingbats";e["Times-Italic"]="Times-Italic";e["Helvetica-Oblique"]="Helvetica-Oblique";e["Courier-Oblique"]="Courier-Oblique";e["Times-BoldItalic"]="Times-BoldItalic";e["Helvetica-BoldOblique"]="Helvetica-BoldOblique";e["Courier-BoldOblique"]="Courier-BoldOblique";e.ArialNarrow="Helvetica";e["ArialNarrow-Bold"]="Helvetica-Bold";e["ArialNarrow-BoldItalic"]="Helvetica-BoldOblique";e["ArialNarrow-Italic"]="Helvetica-Oblique";e.ArialBlack="Helvetica";e["ArialBlack-Bold"]="Helvetica-Bold";e["ArialBlack-BoldItalic"]="Helvetica-BoldOblique";e["ArialBlack-Italic"]="Helvetica-Oblique";e["Arial-Black"]="Helvetica";e["Arial-Black-Bold"]="Helvetica-Bold";e["Arial-Black-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Black-Italic"]="Helvetica-Oblique";e.Arial="Helvetica";e["Arial-Bold"]="Helvetica-Bold";e["Arial-BoldItalic"]="Helvetica-BoldOblique";e["Arial-Italic"]="Helvetica-Oblique";e.ArialMT="Helvetica";e["Arial-BoldItalicMT"]="Helvetica-BoldOblique";e["Arial-BoldMT"]="Helvetica-Bold";e["Arial-ItalicMT"]="Helvetica-Oblique";e["Arial-BoldItalicMT-BoldItalic"]="Helvetica-BoldOblique";e["Arial-BoldMT-Bold"]="Helvetica-Bold";e["Arial-ItalicMT-Italic"]="Helvetica-Oblique";e.ArialUnicodeMS="Helvetica";e["ArialUnicodeMS-Bold"]="Helvetica-Bold";e["ArialUnicodeMS-BoldItalic"]="Helvetica-BoldOblique";e["ArialUnicodeMS-Italic"]="Helvetica-Oblique";e["Courier-BoldItalic"]="Courier-BoldOblique";e["Courier-Italic"]="Courier-Oblique";e.CourierNew="Courier";e["CourierNew-Bold"]="Courier-Bold";e["CourierNew-BoldItalic"]="Courier-BoldOblique";e["CourierNew-Italic"]="Courier-Oblique";e["CourierNewPS-BoldItalicMT"]="Courier-BoldOblique";e["CourierNewPS-BoldMT"]="Courier-Bold";e["CourierNewPS-ItalicMT"]="Courier-Oblique";e.CourierNewPSMT="Courier";e["Helvetica-BoldItalic"]="Helvetica-BoldOblique";e["Helvetica-Italic"]="Helvetica-Oblique";e["HelveticaLTStd-Bold"]="Helvetica-Bold";e["Symbol-Bold"]="Symbol";e["Symbol-BoldItalic"]="Symbol";e["Symbol-Italic"]="Symbol";e.TimesNewRoman="Times-Roman";e["TimesNewRoman-Bold"]="Times-Bold";e["TimesNewRoman-BoldItalic"]="Times-BoldItalic";e["TimesNewRoman-Italic"]="Times-Italic";e.TimesNewRomanPS="Times-Roman";e["TimesNewRomanPS-Bold"]="Times-Bold";e["TimesNewRomanPS-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPS-BoldItalicMT"]="Times-BoldItalic";e["TimesNewRomanPS-BoldMT"]="Times-Bold";e["TimesNewRomanPS-Italic"]="Times-Italic";e["TimesNewRomanPS-ItalicMT"]="Times-Italic";e.TimesNewRomanPSMT="Times-Roman";e["TimesNewRomanPSMT-Bold"]="Times-Bold";e["TimesNewRomanPSMT-BoldItalic"]="Times-BoldItalic";e["TimesNewRomanPSMT-Italic"]="Times-Italic"})),Ti=getLookupTableFactory((function(e){e.Courier="FoxitFixed.pfb";e["Courier-Bold"]="FoxitFixedBold.pfb";e["Courier-BoldOblique"]="FoxitFixedBoldItalic.pfb";e["Courier-Oblique"]="FoxitFixedItalic.pfb";e.Helvetica="LiberationSans-Regular.ttf";e["Helvetica-Bold"]="LiberationSans-Bold.ttf";e["Helvetica-BoldOblique"]="LiberationSans-BoldItalic.ttf";e["Helvetica-Oblique"]="LiberationSans-Italic.ttf";e["Times-Roman"]="FoxitSerif.pfb";e["Times-Bold"]="FoxitSerifBold.pfb";e["Times-BoldItalic"]="FoxitSerifBoldItalic.pfb";e["Times-Italic"]="FoxitSerifItalic.pfb";e.Symbol="FoxitSymbol.pfb";e.ZapfDingbats="FoxitDingbats.pfb";e["LiberationSans-Regular"]="LiberationSans-Regular.ttf";e["LiberationSans-Bold"]="LiberationSans-Bold.ttf";e["LiberationSans-Italic"]="LiberationSans-Italic.ttf";e["LiberationSans-BoldItalic"]="LiberationSans-BoldItalic.ttf"})),qi=getLookupTableFactory((function(e){e.Calibri="Helvetica";e["Calibri-Bold"]="Helvetica-Bold";e["Calibri-BoldItalic"]="Helvetica-BoldOblique";e["Calibri-Italic"]="Helvetica-Oblique";e.CenturyGothic="Helvetica";e["CenturyGothic-Bold"]="Helvetica-Bold";e["CenturyGothic-BoldItalic"]="Helvetica-BoldOblique";e["CenturyGothic-Italic"]="Helvetica-Oblique";e.ComicSansMS="Comic Sans MS";e["ComicSansMS-Bold"]="Comic Sans MS-Bold";e["ComicSansMS-BoldItalic"]="Comic Sans MS-BoldItalic";e["ComicSansMS-Italic"]="Comic Sans MS-Italic";e.GillSansMT="Helvetica";e["GillSansMT-Bold"]="Helvetica-Bold";e["GillSansMT-BoldItalic"]="Helvetica-BoldOblique";e["GillSansMT-Italic"]="Helvetica-Oblique";e.Impact="Helvetica";e["ItcSymbol-Bold"]="Helvetica-Bold";e["ItcSymbol-BoldItalic"]="Helvetica-BoldOblique";e["ItcSymbol-Book"]="Helvetica";e["ItcSymbol-BookItalic"]="Helvetica-Oblique";e["ItcSymbol-Medium"]="Helvetica";e["ItcSymbol-MediumItalic"]="Helvetica-Oblique";e.LucidaConsole="Courier";e["LucidaConsole-Bold"]="Courier-Bold";e["LucidaConsole-BoldItalic"]="Courier-BoldOblique";e["LucidaConsole-Italic"]="Courier-Oblique";e["LucidaSans-Demi"]="Helvetica-Bold";e["MS-Gothic"]="MS Gothic";e["MS-Gothic-Bold"]="MS Gothic-Bold";e["MS-Gothic-BoldItalic"]="MS Gothic-BoldItalic";e["MS-Gothic-Italic"]="MS Gothic-Italic";e["MS-Mincho"]="MS Mincho";e["MS-Mincho-Bold"]="MS Mincho-Bold";e["MS-Mincho-BoldItalic"]="MS Mincho-BoldItalic";e["MS-Mincho-Italic"]="MS Mincho-Italic";e["MS-PGothic"]="MS PGothic";e["MS-PGothic-Bold"]="MS PGothic-Bold";e["MS-PGothic-BoldItalic"]="MS PGothic-BoldItalic";e["MS-PGothic-Italic"]="MS PGothic-Italic";e["MS-PMincho"]="MS PMincho";e["MS-PMincho-Bold"]="MS PMincho-Bold";e["MS-PMincho-BoldItalic"]="MS PMincho-BoldItalic";e["MS-PMincho-Italic"]="MS PMincho-Italic";e.NuptialScript="Times-Italic";e.SegoeUISymbol="Helvetica"})),Oi=getLookupTableFactory((function(e){e["Adobe Jenson"]=!0;e["Adobe Text"]=!0;e.Albertus=!0;e.Aldus=!0;e.Alexandria=!0;e.Algerian=!0;e["American Typewriter"]=!0;e.Antiqua=!0;e.Apex=!0;e.Arno=!0;e.Aster=!0;e.Aurora=!0;e.Baskerville=!0;e.Bell=!0;e.Bembo=!0;e["Bembo Schoolbook"]=!0;e.Benguiat=!0;e["Berkeley Old Style"]=!0;e["Bernhard Modern"]=!0;e["Berthold City"]=!0;e.Bodoni=!0;e["Bauer Bodoni"]=!0;e["Book Antiqua"]=!0;e.Bookman=!0;e["Bordeaux Roman"]=!0;e["Californian FB"]=!0;e.Calisto=!0;e.Calvert=!0;e.Capitals=!0;e.Cambria=!0;e.Cartier=!0;e.Caslon=!0;e.Catull=!0;e.Centaur=!0;e["Century Old Style"]=!0;e["Century Schoolbook"]=!0;e.Chaparral=!0;e["Charis SIL"]=!0;e.Cheltenham=!0;e["Cholla Slab"]=!0;e.Clarendon=!0;e.Clearface=!0;e.Cochin=!0;e.Colonna=!0;e["Computer Modern"]=!0;e["Concrete Roman"]=!0;e.Constantia=!0;e["Cooper Black"]=!0;e.Corona=!0;e.Ecotype=!0;e.Egyptienne=!0;e.Elephant=!0;e.Excelsior=!0;e.Fairfield=!0;e["FF Scala"]=!0;e.Folkard=!0;e.Footlight=!0;e.FreeSerif=!0;e["Friz Quadrata"]=!0;e.Garamond=!0;e.Gentium=!0;e.Georgia=!0;e.Gloucester=!0;e["Goudy Old Style"]=!0;e["Goudy Schoolbook"]=!0;e["Goudy Pro Font"]=!0;e.Granjon=!0;e["Guardian Egyptian"]=!0;e.Heather=!0;e.Hercules=!0;e["High Tower Text"]=!0;e.Hiroshige=!0;e["Hoefler Text"]=!0;e["Humana Serif"]=!0;e.Imprint=!0;e["Ionic No. 5"]=!0;e.Janson=!0;e.Joanna=!0;e.Korinna=!0;e.Lexicon=!0;e.LiberationSerif=!0;e["Liberation Serif"]=!0;e["Linux Libertine"]=!0;e.Literaturnaya=!0;e.Lucida=!0;e["Lucida Bright"]=!0;e.Melior=!0;e.Memphis=!0;e.Miller=!0;e.Minion=!0;e.Modern=!0;e["Mona Lisa"]=!0;e["Mrs Eaves"]=!0;e["MS Serif"]=!0;e["Museo Slab"]=!0;e["New York"]=!0;e["Nimbus Roman"]=!0;e["NPS Rawlinson Roadway"]=!0;e.NuptialScript=!0;e.Palatino=!0;e.Perpetua=!0;e.Plantin=!0;e["Plantin Schoolbook"]=!0;e.Playbill=!0;e["Poor Richard"]=!0;e["Rawlinson Roadway"]=!0;e.Renault=!0;e.Requiem=!0;e.Rockwell=!0;e.Roman=!0;e["Rotis Serif"]=!0;e.Sabon=!0;e.Scala=!0;e.Seagull=!0;e.Sistina=!0;e.Souvenir=!0;e.STIX=!0;e["Stone Informal"]=!0;e["Stone Serif"]=!0;e.Sylfaen=!0;e.Times=!0;e.Trajan=!0;e["Trinité"]=!0;e["Trump Mediaeval"]=!0;e.Utopia=!0;e["Vale Type"]=!0;e["Bitstream Vera"]=!0;e["Vera Serif"]=!0;e.Versailles=!0;e.Wanted=!0;e.Weiss=!0;e["Wide Latin"]=!0;e.Windsor=!0;e.XITS=!0})),Pi=getLookupTableFactory((function(e){e.Dingbats=!0;e.Symbol=!0;e.ZapfDingbats=!0;e.Wingdings=!0;e["Wingdings-Bold"]=!0;e["Wingdings-Regular"]=!0})),Wi=getLookupTableFactory((function(e){e[2]=10;e[3]=32;e[4]=33;e[5]=34;e[6]=35;e[7]=36;e[8]=37;e[9]=38;e[10]=39;e[11]=40;e[12]=41;e[13]=42;e[14]=43;e[15]=44;e[16]=45;e[17]=46;e[18]=47;e[19]=48;e[20]=49;e[21]=50;e[22]=51;e[23]=52;e[24]=53;e[25]=54;e[26]=55;e[27]=56;e[28]=57;e[29]=58;e[30]=894;e[31]=60;e[32]=61;e[33]=62;e[34]=63;e[35]=64;e[36]=65;e[37]=66;e[38]=67;e[39]=68;e[40]=69;e[41]=70;e[42]=71;e[43]=72;e[44]=73;e[45]=74;e[46]=75;e[47]=76;e[48]=77;e[49]=78;e[50]=79;e[51]=80;e[52]=81;e[53]=82;e[54]=83;e[55]=84;e[56]=85;e[57]=86;e[58]=87;e[59]=88;e[60]=89;e[61]=90;e[62]=91;e[63]=92;e[64]=93;e[65]=94;e[66]=95;e[67]=96;e[68]=97;e[69]=98;e[70]=99;e[71]=100;e[72]=101;e[73]=102;e[74]=103;e[75]=104;e[76]=105;e[77]=106;e[78]=107;e[79]=108;e[80]=109;e[81]=110;e[82]=111;e[83]=112;e[84]=113;e[85]=114;e[86]=115;e[87]=116;e[88]=117;e[89]=118;e[90]=119;e[91]=120;e[92]=121;e[93]=122;e[94]=123;e[95]=124;e[96]=125;e[97]=126;e[98]=196;e[99]=197;e[100]=199;e[101]=201;e[102]=209;e[103]=214;e[104]=220;e[105]=225;e[106]=224;e[107]=226;e[108]=228;e[109]=227;e[110]=229;e[111]=231;e[112]=233;e[113]=232;e[114]=234;e[115]=235;e[116]=237;e[117]=236;e[118]=238;e[119]=239;e[120]=241;e[121]=243;e[122]=242;e[123]=244;e[124]=246;e[125]=245;e[126]=250;e[127]=249;e[128]=251;e[129]=252;e[130]=8224;e[131]=176;e[132]=162;e[133]=163;e[134]=167;e[135]=8226;e[136]=182;e[137]=223;e[138]=174;e[139]=169;e[140]=8482;e[141]=180;e[142]=168;e[143]=8800;e[144]=198;e[145]=216;e[146]=8734;e[147]=177;e[148]=8804;e[149]=8805;e[150]=165;e[151]=181;e[152]=8706;e[153]=8721;e[154]=8719;e[156]=8747;e[157]=170;e[158]=186;e[159]=8486;e[160]=230;e[161]=248;e[162]=191;e[163]=161;e[164]=172;e[165]=8730;e[166]=402;e[167]=8776;e[168]=8710;e[169]=171;e[170]=187;e[171]=8230;e[179]=8220;e[180]=8221;e[181]=8216;e[182]=8217;e[200]=193;e[203]=205;e[207]=211;e[210]=218;e[223]=711;e[224]=321;e[225]=322;e[226]=352;e[227]=353;e[228]=381;e[229]=382;e[233]=221;e[234]=253;e[252]=263;e[253]=268;e[254]=269;e[258]=258;e[260]=260;e[261]=261;e[265]=280;e[266]=281;e[267]=282;e[268]=283;e[269]=313;e[275]=323;e[276]=324;e[278]=328;e[283]=344;e[284]=345;e[285]=346;e[286]=347;e[292]=367;e[295]=377;e[296]=378;e[298]=380;e[305]=963;e[306]=964;e[307]=966;e[308]=8215;e[309]=8252;e[310]=8319;e[311]=8359;e[312]=8592;e[313]=8593;e[337]=9552;e[493]=1039;e[494]=1040;e[672]=1488;e[673]=1489;e[674]=1490;e[675]=1491;e[676]=1492;e[677]=1493;e[678]=1494;e[679]=1495;e[680]=1496;e[681]=1497;e[682]=1498;e[683]=1499;e[684]=1500;e[685]=1501;e[686]=1502;e[687]=1503;e[688]=1504;e[689]=1505;e[690]=1506;e[691]=1507;e[692]=1508;e[693]=1509;e[694]=1510;e[695]=1511;e[696]=1512;e[697]=1513;e[698]=1514;e[705]=1524;e[706]=8362;e[710]=64288;e[711]=64298;e[759]=1617;e[761]=1776;e[763]=1778;e[775]=1652;e[777]=1764;e[778]=1780;e[779]=1781;e[780]=1782;e[782]=771;e[783]=64726;e[786]=8363;e[788]=8532;e[790]=768;e[791]=769;e[792]=768;e[795]=803;e[797]=64336;e[798]=64337;e[799]=64342;e[800]=64343;e[801]=64344;e[802]=64345;e[803]=64362;e[804]=64363;e[805]=64364;e[2424]=7821;e[2425]=7822;e[2426]=7823;e[2427]=7824;e[2428]=7825;e[2429]=7826;e[2430]=7827;e[2433]=7682;e[2678]=8045;e[2679]=8046;e[2830]=1552;e[2838]=686;e[2840]=751;e[2842]=753;e[2843]=754;e[2844]=755;e[2846]=757;e[2856]=767;e[2857]=848;e[2858]=849;e[2862]=853;e[2863]=854;e[2864]=855;e[2865]=861;e[2866]=862;e[2906]=7460;e[2908]=7462;e[2909]=7463;e[2910]=7464;e[2912]=7466;e[2913]=7467;e[2914]=7468;e[2916]=7470;e[2917]=7471;e[2918]=7472;e[2920]=7474;e[2921]=7475;e[2922]=7476;e[2924]=7478;e[2925]=7479;e[2926]=7480;e[2928]=7482;e[2929]=7483;e[2930]=7484;e[2932]=7486;e[2933]=7487;e[2934]=7488;e[2936]=7490;e[2937]=7491;e[2938]=7492;e[2940]=7494;e[2941]=7495;e[2942]=7496;e[2944]=7498;e[2946]=7500;e[2948]=7502;e[2950]=7504;e[2951]=7505;e[2952]=7506;e[2954]=7508;e[2955]=7509;e[2956]=7510;e[2958]=7512;e[2959]=7513;e[2960]=7514;e[2962]=7516;e[2963]=7517;e[2964]=7518;e[2966]=7520;e[2967]=7521;e[2968]=7522;e[2970]=7524;e[2971]=7525;e[2972]=7526;e[2974]=7528;e[2975]=7529;e[2976]=7530;e[2978]=1537;e[2979]=1538;e[2980]=1539;e[2982]=1549;e[2983]=1551;e[2984]=1552;e[2986]=1554;e[2987]=1555;e[2988]=1556;e[2990]=1623;e[2991]=1624;e[2995]=1775;e[2999]=1791;e[3002]=64290;e[3003]=64291;e[3004]=64292;e[3006]=64294;e[3007]=64295;e[3008]=64296;e[3011]=1900;e[3014]=8223;e[3015]=8244;e[3017]=7532;e[3018]=7533;e[3019]=7534;e[3075]=7590;e[3076]=7591;e[3079]=7594;e[3080]=7595;e[3083]=7598;e[3084]=7599;e[3087]=7602;e[3088]=7603;e[3091]=7606;e[3092]=7607;e[3095]=7610;e[3096]=7611;e[3099]=7614;e[3100]=7615;e[3103]=7618;e[3104]=7619;e[3107]=8337;e[3108]=8338;e[3116]=1884;e[3119]=1885;e[3120]=1885;e[3123]=1886;e[3124]=1886;e[3127]=1887;e[3128]=1887;e[3131]=1888;e[3132]=1888;e[3135]=1889;e[3136]=1889;e[3139]=1890;e[3140]=1890;e[3143]=1891;e[3144]=1891;e[3147]=1892;e[3148]=1892;e[3153]=580;e[3154]=581;e[3157]=584;e[3158]=585;e[3161]=588;e[3162]=589;e[3165]=891;e[3166]=892;e[3169]=1274;e[3170]=1275;e[3173]=1278;e[3174]=1279;e[3181]=7622;e[3182]=7623;e[3282]=11799;e[3316]=578;e[3379]=42785;e[3393]=1159;e[3416]=8377})),ji=getLookupTableFactory((function(e){e[227]=322;e[264]=261;e[291]=346})),Xi=getLookupTableFactory((function(e){e[1]=32;e[4]=65;e[5]=192;e[6]=193;e[9]=196;e[17]=66;e[18]=67;e[21]=268;e[24]=68;e[28]=69;e[29]=200;e[30]=201;e[32]=282;e[38]=70;e[39]=71;e[44]=72;e[47]=73;e[48]=204;e[49]=205;e[58]=74;e[60]=75;e[62]=76;e[68]=77;e[69]=78;e[75]=79;e[76]=210;e[80]=214;e[87]=80;e[89]=81;e[90]=82;e[92]=344;e[94]=83;e[97]=352;e[100]=84;e[104]=85;e[109]=220;e[115]=86;e[116]=87;e[121]=88;e[122]=89;e[124]=221;e[127]=90;e[129]=381;e[258]=97;e[259]=224;e[260]=225;e[263]=228;e[268]=261;e[271]=98;e[272]=99;e[273]=263;e[275]=269;e[282]=100;e[286]=101;e[287]=232;e[288]=233;e[290]=283;e[295]=281;e[296]=102;e[336]=103;e[346]=104;e[349]=105;e[350]=236;e[351]=237;e[361]=106;e[364]=107;e[367]=108;e[371]=322;e[373]=109;e[374]=110;e[381]=111;e[382]=242;e[383]=243;e[386]=246;e[393]=112;e[395]=113;e[396]=114;e[398]=345;e[400]=115;e[401]=347;e[403]=353;e[410]=116;e[437]=117;e[442]=252;e[448]=118;e[449]=119;e[454]=120;e[455]=121;e[457]=253;e[460]=122;e[462]=382;e[463]=380;e[853]=44;e[855]=58;e[856]=46;e[876]=47;e[878]=45;e[882]=45;e[894]=40;e[895]=41;e[896]=91;e[897]=93;e[923]=64;e[1004]=48;e[1005]=49;e[1006]=50;e[1007]=51;e[1008]=52;e[1009]=53;e[1010]=54;e[1011]=55;e[1012]=56;e[1013]=57;e[1081]=37;e[1085]=43;e[1086]=45}));function getStandardFontName(e){const t=normalizeFontName(e);return Ki()[t]}function isKnownFontName(e){const t=normalizeFontName(e);return!!(Ki()[t]||qi()[t]||Oi()[t]||Pi()[t])}class ToUnicodeMap{constructor(e=[]){this._map=e}get length(){return this._map.length}forEach(e){for(const t in this._map)e(t,this._map[t].codePointAt(0))}has(e){return void 0!==this._map[e]}get(e){return this._map[e]}charCodeOf(e){const t=this._map;if(t.length<=65536)return t.indexOf(e);for(const i in t)if(t[i]===e)return 0|i;return-1}amend(e){for(const t in e)this._map[t]=e[t]}}class IdentityToUnicodeMap{constructor(e,t){this.firstChar=e;this.lastChar=t}get length(){return this.lastChar+1-this.firstChar}forEach(e){for(let t=this.firstChar,i=this.lastChar;t<=i;t++)e(t,t)}has(e){return this.firstChar<=e&&e<=this.lastChar}get(e){if(this.firstChar<=e&&e<=this.lastChar)return String.fromCharCode(e)}charCodeOf(e){return Number.isInteger(e)&&e>=this.firstChar&&e<=this.lastChar?e:-1}amend(e){unreachable("Should not call amend()")}}class CFFFont{constructor(e,t){this.properties=t;const i=new CFFParser(e,t,Gi);this.cff=i.parse();this.cff.duplicateFirstGlyph();const a=new CFFCompiler(this.cff);this.seacs=this.cff.seacs;try{this.data=a.compile()}catch{warn("Failed to compile font "+t.loadedName);this.data=e}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const e=this.cff,t=this.properties,{cidToGidMap:i,cMap:a}=t,r=e.charset.charset;let s,n;if(t.composite){let t,o;if(i?.length>0){t=Object.create(null);for(let e=0,a=i.length;e=0){const a=i[t];a&&(r[e]=a)}}r.length>0&&(this.properties.builtInEncoding=r)}}function getUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function getUint16(e,t){return e[t]<<8|e[t+1]}function getInt16(e,t){return(e[t]<<24|e[t+1]<<16)>>16}function getInt8(e,t){return e[t]<<24>>24}function getFloat214(e,t){return getInt16(e,t)/16384}function getSubroutineBias(e){const t=e.length;let i=32768;t<1240?i=107:t<33900&&(i=1131);return i}function parseCmap(e,t,i){const a=1===getUint16(e,t+2)?getUint32(e,t+8):getUint32(e,t+16),r=getUint16(e,t+a);let s,n,o;if(4===r){getUint16(e,t+a+2);const i=getUint16(e,t+a+6)>>1;n=t+a+14;s=[];for(o=0;o>1;i0;)l.push({flags:s})}for(i=0;i>1;p=!0;break;case 4:n+=r.pop();moveTo(s,n);p=!0;break;case 5:for(;r.length>0;){s+=r.shift();n+=r.shift();lineTo(s,n)}break;case 6:for(;r.length>0;){s+=r.shift();lineTo(s,n);if(0===r.length)break;n+=r.shift();lineTo(s,n)}break;case 7:for(;r.length>0;){n+=r.shift();lineTo(s,n);if(0===r.length)break;s+=r.shift();lineTo(s,n)}break;case 8:for(;r.length>0;){c=s+r.shift();h=n+r.shift();l=c+r.shift();C=h+r.shift();s=l+r.shift();n=C+r.shift();bezierCurveTo(c,h,l,C,s,n)}break;case 10:d=r.pop();f=null;if(i.isCFFCIDFont){const e=i.fdSelect.getFDIndex(a);if(e>=0&&eMath.abs(n-t)?s+=r.shift():n+=r.shift();bezierCurveTo(c,h,l,C,s,n);break;default:throw new FormatError(`unknown operator: 12 ${m}`)}break;case 14:if(r.length>=4){const e=r.pop(),a=r.pop();n=r.pop();s=r.pop();t.save();t.translate(s,n);let o=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[Bi[e]]));compileCharString(i.glyphs[o.glyphId],t,i,o.glyphId);t.restore();o=lookupCmap(i.cmap,String.fromCharCode(i.glyphNameMap[Bi[a]]));compileCharString(i.glyphs[o.glyphId],t,i,o.glyphId)}return;case 19:case 20:o+=r.length>>1;g+=o+7>>3;p=!0;break;case 21:n+=r.pop();s+=r.pop();moveTo(s,n);p=!0;break;case 22:s+=r.pop();moveTo(s,n);p=!0;break;case 24:for(;r.length>2;){c=s+r.shift();h=n+r.shift();l=c+r.shift();C=h+r.shift();s=l+r.shift();n=C+r.shift();bezierCurveTo(c,h,l,C,s,n)}s+=r.shift();n+=r.shift();lineTo(s,n);break;case 25:for(;r.length>6;){s+=r.shift();n+=r.shift();lineTo(s,n)}c=s+r.shift();h=n+r.shift();l=c+r.shift();C=h+r.shift();s=l+r.shift();n=C+r.shift();bezierCurveTo(c,h,l,C,s,n);break;case 26:r.length%2&&(s+=r.shift());for(;r.length>0;){c=s;h=n+r.shift();l=c+r.shift();C=h+r.shift();s=l;n=C+r.shift();bezierCurveTo(c,h,l,C,s,n)}break;case 27:r.length%2&&(n+=r.shift());for(;r.length>0;){c=s+r.shift();h=n;l=c+r.shift();C=h+r.shift();s=l+r.shift();n=C;bezierCurveTo(c,h,l,C,s,n)}break;case 28:r.push((e[g]<<24|e[g+1]<<16)>>16);g+=2;break;case 29:d=r.pop()+i.gsubrsBias;f=i.gsubrs[d];f&&parse(f);break;case 30:for(;r.length>0;){c=s;h=n+r.shift();l=c+r.shift();C=h+r.shift();s=l+r.shift();n=C+(1===r.length?r.shift():0);bezierCurveTo(c,h,l,C,s,n);if(0===r.length)break;c=s+r.shift();h=n;l=c+r.shift();C=h+r.shift();n=C+r.shift();s=l+(1===r.length?r.shift():0);bezierCurveTo(c,h,l,C,s,n)}break;case 31:for(;r.length>0;){c=s+r.shift();h=n;l=c+r.shift();C=h+r.shift();n=C+r.shift();s=l+(1===r.length?r.shift():0);bezierCurveTo(c,h,l,C,s,n);if(0===r.length)break;c=s;h=n+r.shift();l=c+r.shift();C=h+r.shift();s=l+r.shift();n=C+(1===r.length?r.shift():0);bezierCurveTo(c,h,l,C,s,n)}break;default:if(m<32)throw new FormatError(`unknown operator: ${m}`);if(m<247)r.push(m-139);else if(m<251)r.push(256*(m-247)+e[g++]+108);else if(m<255)r.push(256*-(m-251)-e[g++]-108);else{r.push((e[g]<<24|e[g+1]<<16|e[g+2]<<8|e[g+3])/65536);g+=4}}p&&(r.length=0)}}(e)}class Commands{cmds=[];transformStack=[];currentTransform=[1,0,0,1,0,0];add(e,t){if(t){const[i,a,r,s,n,o]=this.currentTransform;for(let e=0,g=t.length;e=0&&e2*getUint16(e,t)}const s=[];let n=r(t,0);for(let i=a;ie+(t.getSize()+3&-4)),0)}write(){const e=this.getSize(),t=new DataView(new ArrayBuffer(e)),i=e>131070,a=i?4:2,r=new DataView(new ArrayBuffer((this.glyphs.length+1)*a));i?r.setUint32(0,0):r.setUint16(0,0);let s=0,n=0;for(const e of this.glyphs){s+=e.write(s,t);s=s+3&-4;n+=a;i?r.setUint32(n,s):r.setUint16(n,s>>1)}return{isLocationLong:i,loca:new Uint8Array(r.buffer),glyf:new Uint8Array(t.buffer)}}scale(e){for(let t=0,i=this.glyphs.length;te+t.getSize()),0);return this.header.getSize()+e}write(e,t){if(!this.header)return 0;const i=e;e+=this.header.write(e,t);if(this.simple)e+=this.simple.write(e,t);else for(const i of this.composites)e+=i.write(e,t);return e-i}scale(e){if(!this.header)return;const t=(this.header.xMin+this.header.xMax)/2;this.header.scale(t,e);if(this.simple)this.simple.scale(t,e);else for(const i of this.composites)i.scale(t,e)}}class GlyphHeader{constructor({numberOfContours:e,xMin:t,yMin:i,xMax:a,yMax:r}){this.numberOfContours=e;this.xMin=t;this.yMin=i;this.xMax=a;this.yMax=r}static parse(e,t){return[10,new GlyphHeader({numberOfContours:t.getInt16(e),xMin:t.getInt16(e+2),yMin:t.getInt16(e+4),xMax:t.getInt16(e+6),yMax:t.getInt16(e+8)})]}getSize(){return 10}write(e,t){t.setInt16(e,this.numberOfContours);t.setInt16(e+2,this.xMin);t.setInt16(e+4,this.yMin);t.setInt16(e+6,this.xMax);t.setInt16(e+8,this.yMax);return 10}scale(e,t){this.xMin=Math.round(e+(this.xMin-e)*t);this.xMax=Math.round(e+(this.xMax-e)*t)}}class Contour{constructor({flags:e,xCoordinates:t,yCoordinates:i}){this.xCoordinates=t;this.yCoordinates=i;this.flags=e}}class SimpleGlyph{constructor({contours:e,instructions:t}){this.contours=e;this.instructions=t}static parse(e,t,i){const a=[];for(let r=0;r255?e+=2:o>0&&(e+=1);t=s;o=Math.abs(n-i);o>255?e+=2:o>0&&(e+=1);i=n}}return e}write(e,t){const i=e,a=[],r=[],s=[];let n=0,o=0;for(const i of this.contours){for(let e=0,t=i.xCoordinates.length;e=0?18:2;a.push(e)}else a.push(c)}n=g;const l=i.yCoordinates[e];c=l-o;if(0===c){t|=32;r.push(0)}else{const e=Math.abs(c);if(e<=255){t|=c>=0?36:4;r.push(e)}else r.push(c)}o=l;s.push(t)}t.setUint16(e,a.length-1);e+=2}t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}for(const i of s)t.setUint8(e++,i);for(let i=0,r=a.length;i=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(e+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(e+=2);return e}write(e,t){const i=e;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1);t.setUint16(e,this.flags);t.setUint16(e+2,this.glyphIndex);e+=4;if(1&this.flags){if(2&this.flags){t.setInt16(e,this.argument1);t.setInt16(e+2,this.argument2)}else{t.setUint16(e,this.argument1);t.setUint16(e+2,this.argument2)}e+=4}else{t.setUint8(e,this.argument1);t.setUint8(e+1,this.argument2);e+=2}if(256&this.flags){t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}}return e-i}scale(e,t){}}function writeInt16(e,t,i){e[t]=i>>8&255;e[t+1]=255&i}function writeInt32(e,t,i){e[t]=i>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}function writeData(e,t,i){if(i instanceof Uint8Array)e.set(i,t);else if("string"==typeof i)for(let a=0,r=i.length;ai;){i<<=1;a++}const r=i*t;return{range:r,entry:a,rangeShift:t*e-r}}toArray(){let e=this.sfnt;const t=this.tables,i=Object.keys(t);i.sort();const a=i.length;let r,s,n,o,g,c=12+16*a;const l=[c];for(r=0;r>>0;l.push(c)}const h=new Uint8Array(c);for(r=0;r>>0}writeInt32(h,c+4,e);writeInt32(h,c+8,l[r]);writeInt32(h,c+12,t[g].length);c+=16}return h}addTable(e,t){if(e in this.tables)throw new Error("Table "+e+" already exists");this.tables[e]=t}}const _i=[4],zi=[5],$i=[6],Aa=[7],ea=[8],ta=[12,35],ia=[14],aa=[21],ra=[22],sa=[30],na=[31];class Type1CharString{constructor(){this.width=0;this.lsb=0;this.flexing=!1;this.output=[];this.stack=[]}convert(e,t,i){const a=e.length;let r,s,n,o=!1;for(let g=0;ga)return!0;const r=a-e;for(let e=r;e>8&255,255&t);else{t=65536*t|0;this.output.push(255,t>>24&255,t>>16&255,t>>8&255,255&t)}}this.output.push(...t);i?this.stack.splice(r,e):this.stack.length=0;return!1}}function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function decrypt(e,t,i){if(i>=e.length)return new Uint8Array(0);let a,r,s=0|t;for(a=0;a>8;s=52845*(t+s)+22719&65535}return o}function isSpecial(e){return 47===e||91===e||93===e||123===e||125===e||40===e||41===e}class Type1Parser{constructor(e,t,i){if(t){const t=e.getBytes(),i=!((isHexDigit(t[0])||isWhiteSpace(t[0]))&&isHexDigit(t[1])&&isHexDigit(t[2])&&isHexDigit(t[3])&&isHexDigit(t[4])&&isHexDigit(t[5])&&isHexDigit(t[6])&&isHexDigit(t[7]));e=new Stream(i?decrypt(t,55665,4):function decryptAscii(e,t,i){let a=0|t;const r=e.length,s=new Uint8Array(r>>>1);let n,o;for(n=0,o=0;n>8;a=52845*(e+a)+22719&65535}}return s.slice(i,o)}(t,55665,4))}this.seacAnalysisEnabled=!!i;this.stream=e;this.nextChar()}readNumberArray(){this.getToken();const e=[];for(;;){const t=this.getToken();if(null===t||"]"===t||"}"===t)break;e.push(parseFloat(t||0))}return e}readNumber(){const e=this.getToken();return parseFloat(e||0)}readInt(){const e=this.getToken();return 0|parseInt(e||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){this.stream.skip(-2);return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(-1===t)return null;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}if(isSpecial(t)){this.nextChar();return String.fromCharCode(t)}let i="";do{i+=String.fromCharCode(t);t=this.nextChar()}while(t>=0&&!isWhiteSpace(t)&&!isSpecial(t));return i}readCharStrings(e,t){return-1===t?e:decrypt(e,4330,t)}extractFontProgram(e){const t=this.stream,i=[],a=[],r=Object.create(null);r.lenIV=4;const s={subrs:[],charstrings:[],properties:{privateData:r}};let n,o,g,c;for(;null!==(n=this.getToken());)if("/"===n){n=this.getToken();switch(n){case"CharStrings":this.getToken();this.getToken();this.getToken();this.getToken();for(;;){n=this.getToken();if(null===n||"end"===n)break;if("/"!==n)continue;const e=this.getToken();o=this.readInt();this.getToken();g=o>0?t.getBytes(o):new Uint8Array(0);c=s.properties.privateData.lenIV;const i=this.readCharStrings(g,c);this.nextChar();n=this.getToken();"noaccess"===n?this.getToken():"/"===n&&this.prevChar();a.push({glyph:e,encoded:i})}break;case"Subrs":this.readInt();this.getToken();for(;"dup"===this.getToken();){const e=this.readInt();o=this.readInt();this.getToken();g=o>0?t.getBytes(o):new Uint8Array(0);c=s.properties.privateData.lenIV;const a=this.readCharStrings(g,c);this.nextChar();n=this.getToken();"noaccess"===n&&this.getToken();i[e]=a}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const e=this.readNumberArray();e.length>0&&e.length,0;break;case"StemSnapH":case"StemSnapV":s.properties.privateData[n]=this.readNumberArray();break;case"StdHW":case"StdVW":s.properties.privateData[n]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":s.properties.privateData[n]=this.readNumber();break;case"ExpansionFactor":s.properties.privateData[n]=this.readNumber()||.06;break;case"ForceBold":s.properties.privateData[n]=this.readBoolean()}}for(const{encoded:t,glyph:r}of a){const a=new Type1CharString,n=a.convert(t,i,this.seacAnalysisEnabled);let o=a.output;n&&(o=[14]);const g={glyphName:r,charstring:o,width:a.width,lsb:a.lsb,seac:a.seac};".notdef"===r?s.charstrings.unshift(g):s.charstrings.push(g);if(e.builtInEncoding){const t=e.builtInEncoding.indexOf(r);t>-1&&void 0===e.widths[t]&&t>=e.firstChar&&t<=e.lastChar&&(e.widths[t]=a.width)}}return s}extractFontHeader(e){let t;for(;null!==(t=this.getToken());)if("/"===t){t=this.getToken();switch(t){case"FontMatrix":const i=this.readNumberArray();e.fontMatrix=i;break;case"Encoding":const a=this.getToken();let r;if(/^\d+$/.test(a)){r=[];const e=0|parseInt(a,10);this.getToken();for(let i=0;i=r){n+=i;for(;n=0&&(a[e]=r)}}return type1FontGlyphMapping(e,a,i)}hasGlyphId(e){if(e<0||e>=this.numGlyphs)return!1;if(0===e)return!0;return this.charstrings[e-1].charstring.length>0}getSeacs(e){const t=[];for(let i=0,a=e.length;i0;e--)t[e]-=t[e-1];Q.setByName(e,t)}s.topDict.privateDict=Q;const u=new CFFIndex;for(l=0,h=a.length;l0&&e.toUnicode.amend(t)}class fonts_Glyph{constructor(e,t,i,a,r,s,n,o,g){this.originalCharCode=e;this.fontChar=t;this.unicode=i;this.accent=a;this.width=r;this.vmetric=s;this.operatorListId=n;this.isSpace=o;this.isInFont=g}get category(){return shadow(this,"category",function getCharUnicodeCategory(e){const t=Ni.get(e);if(t)return t;const i=e.match(Ri),a={isWhitespace:!!i?.[1],isZeroWidthDiacritic:!!i?.[2],isInvisibleFormatMark:!!i?.[3]};Ni.set(e,a);return a}(this.unicode),!0)}}function int16(e,t){return(e<<8)+t}function writeSignedInt16(e,t,i){e[t+1]=i;e[t]=i>>>8}function signedInt16(e,t){const i=(e<<8)+t;return 32768&i?i-65536:i}function string16(e){return String.fromCharCode(e>>8&255,255&e)}function safeString16(e){e>32767?e=32767:e<-32768&&(e=-32768);return String.fromCharCode(e>>8&255,255&e)}function isTrueTypeCollectionFile(e){return"ttcf"===bytesToString(e.peekBytes(4))}function getFontFileType(e,{type:t,subtype:i,composite:a}){let r,s;if(function isTrueTypeFile(e){const t=e.peekBytes(4);return 65536===readUint32(t,0)||"true"===bytesToString(t)}(e)||isTrueTypeCollectionFile(e))r=a?"CIDFontType2":"TrueType";else if(function isOpenTypeFile(e){return"OTTO"===bytesToString(e.peekBytes(4))}(e))r=a?"CIDFontType2":"OpenType";else if(function isType1File(e){const t=e.peekBytes(2);return 37===t[0]&&33===t[1]||128===t[0]&&1===t[1]}(e))r=a?"CIDFontType0":"MMType1"===t?"MMType1":"Type1";else if(function isCFFFile(e){const t=e.peekBytes(4);return t[0]>=1&&t[3]>=1&&t[3]<=4}(e))if(a){r="CIDFontType0";s="CIDFontType0C"}else{r="MMType1"===t?"MMType1":"Type1";s="Type1C"}else{warn("getFontFileType: Unable to detect correct font file Type/Subtype.");r=t;s=i}return[r,s]}function applyStandardFontGlyphMap(e,t){for(const i in t)e[+i]=t[i]}function buildToFontChar(e,t,i){const a=[];let r;for(let i=0,s=e.length;il){g++;if(g>=oa.length){warn("Ran out of space in font private use area.");break}c=oa[g][0];l=oa[g][1]}const E=c++;0===Q&&(Q=i);let u=a.get(C);"string"==typeof u&&(u=u.codePointAt(0));if(u&&!(h=u,oa[0][0]<=h&&h<=oa[0][1]||oa[1][0]<=h&&h<=oa[1][1])&&!o.has(Q)){s.set(u,Q);o.add(Q)}r[E]=Q;n[C]=E}var h;return{toFontChar:n,charCodeToGlyphId:r,toUnicodeExtraMap:s,nextAvailableFontCharCode:c}}function createCmapTable(e,t,i){const a=function getRanges(e,t,i){const a=[];for(const t in e)e[t]>=i||a.push({fontCharCode:0|t,glyphId:e[t]});if(t)for(const[e,r]of t)r>=i||a.push({fontCharCode:e,glyphId:r});0===a.length&&a.push({fontCharCode:0,glyphId:0});a.sort((function fontGetRangesSort(e,t){return e.fontCharCode-t.fontCharCode}));const r=[],s=a.length;for(let e=0;e65535?2:1;let s,n,o,g,c="\0\0"+string16(r)+"\0\0"+string32(4+8*r);for(s=a.length-1;s>=0&&!(a[s][0]<=65535);--s);const l=s+1;a[s][0]<65535&&65535===a[s][1]&&(a[s][1]=65534);const h=a[s][1]<65535?1:0,C=l+h,Q=OpenTypeFileBuilder.getSearchParams(C,2);let E,u,d,f,p="",m="",y="",w="",b="",D=0;for(s=0,n=l;s0){m+="ÿÿ";p+="ÿÿ";y+="\0";w+="\0\0"}const S="\0\0"+string16(2*C)+string16(Q.range)+string16(Q.entry)+string16(Q.rangeShift)+m+"\0\0"+p+y+w+b;let k="",R="";if(r>1){c+="\0\0\n"+string32(4+8*r+4+S.length);k="";for(s=0,n=a.length;se||!o)&&(o=e);g 123 are reserved for internal usage");n|=1<65535&&(g=65535)}else{o=0;g=255}const l=e.bbox||[0,0,0,0],h=i.unitsPerEm||(e.fontMatrix?1/Math.max(...e.fontMatrix.slice(0,4).map(Math.abs)):1e3),C=e.ascentScaled?1:h/ga,Q=i.ascent||Math.round(C*(e.ascent||l[3]));let E=i.descent||Math.round(C*(e.descent||l[1]));E>0&&e.descent>0&&l[1]<0&&(E=-E);const u=i.yMax||Q,d=-i.yMin||-E;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(e.fixedPitch?9:0)+"\0\0\0\0\0\0"+string32(a)+string32(r)+string32(s)+string32(n)+"*21*"+string16(e.italicAngle?1:0)+string16(o||e.firstChar)+string16(g||e.lastChar)+string16(Q)+string16(E)+"\0d"+string16(u)+string16(d)+"\0\0\0\0\0\0\0\0"+string16(e.xHeight)+string16(e.capHeight)+string16(0)+string16(o||e.firstChar)+"\0"}function createPostTable(e){return"\0\0\0"+string32(Math.floor(65536*e.italicAngle))+"\0\0\0\0"+string32(e.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function createPostscriptName(e){return e.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function createNameTable(e,t){t||(t=[[],[]]);const i=[t[0][0]||"Original licence",t[0][1]||e,t[0][2]||"Unknown",t[0][3]||"uniqueID",t[0][4]||e,t[0][5]||"Version 0.11",t[0][6]||createPostscriptName(e),t[0][7]||"Unknown",t[0][8]||"Unknown",t[0][9]||"Unknown"],a=[];let r,s,n,o,g;for(r=0,s=i.length;r0;if((n||o)&&"CIDFontType2"===i&&this.cidEncoding.startsWith("Identity-")){const i=e.cidToGidMap,a=[];applyStandardFontGlyphMap(a,Wi());/Arial-?Black/i.test(t)?applyStandardFontGlyphMap(a,ji()):/Calibri/i.test(t)&&applyStandardFontGlyphMap(a,Xi());if(i){for(const e in a){const t=a[e];void 0!==i[t]&&(a[+e]=i[t])}i.length!==this.toUnicode.length&&e.hasIncludedToUnicodeMap&&this.toUnicode instanceof IdentityToUnicodeMap&&this.toUnicode.forEach((function(e,t){const r=a[e];void 0===i[r]&&(a[+e]=t)}))}this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(e,t){a[+e]=t}));this.toFontChar=a;this.toUnicode=new ToUnicodeMap(a)}else if(/Symbol/i.test(a))this.toFontChar=buildToFontChar(Ei,Di(),this.differences);else if(/Dingbats/i.test(a))this.toFontChar=buildToFontChar(ui,Fi(),this.differences);else if(n||o){const e=buildToFontChar(this.defaultEncoding,Di(),this.differences);"CIDFontType2"!==i||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach((function(t,i){e[+t]=i}));this.toFontChar=e}else{const e=Di(),i=[];this.toUnicode.forEach(((t,a)=>{if(!this.composite){const i=getUnicodeForGlyph(this.differences[t]||this.defaultEncoding[t],e);-1!==i&&(a=i)}i[+t]=a}));this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(t)&&applyStandardFontGlyphMap(i,Wi());this.toFontChar=i}amendFallbackToUnicode(e);this.loadedName=a.split("-",1)[0]}checkAndRepair(e,t,i){const a=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(e,t){const i=Object.create(null);i["OS/2"]=null;i.cmap=null;i.head=null;i.hhea=null;i.hmtx=null;i.maxp=null;i.name=null;i.post=null;for(let r=0;r>>0,a=e.getInt32()>>>0,r=e.getInt32()>>>0,s=e.pos;e.pos=e.start||0;e.skip(a);const n=e.getBytes(r);e.pos=s;if("head"===t){n[8]=n[9]=n[10]=n[11]=0;n[17]|=32}return{tag:t,checksum:i,length:r,offset:a,data:n}}function readOpenTypeHeader(e){return{version:e.getString(4),numTables:e.getUint16(),searchRange:e.getUint16(),entrySelector:e.getUint16(),rangeShift:e.getUint16()}}function sanitizeGlyph(e,t,i,a,r,s){const n={length:0,sizeOfInstructions:0};if(t<0||t>=e.length||i>e.length||i-t<=12)return n;const o=e.subarray(t,i),g=signedInt16(o[2],o[3]),c=signedInt16(o[4],o[5]),l=signedInt16(o[6],o[7]),h=signedInt16(o[8],o[9]);if(g>l){writeSignedInt16(o,2,l);writeSignedInt16(o,6,g)}if(c>h){writeSignedInt16(o,4,h);writeSignedInt16(o,8,c)}const C=signedInt16(o[0],o[1]);if(C<0){if(C<-1)return n;a.set(o,r);n.length=o.length;return n}let Q,E=10,u=0;for(Q=0;Qo.length)return n;if(!s&&f>0){a.set(o.subarray(0,d),r);a.set([0,0],r+d);a.set(o.subarray(p,y),r+d+2);y-=f;o.length-y>3&&(y=y+3&-4);n.length=y;return n}if(o.length-y>3){y=y+3&-4;a.set(o.subarray(0,y),r);n.length=y;return n}a.set(o,r);n.length=o.length;return n}function readNameTable(e){const i=(t.start||0)+e.offset;t.pos=i;const a=[[],[]],r=[],s=e.length,n=i+s;if(0!==t.getUint16()||s<6)return[a,r];const o=t.getUint16(),g=t.getUint16();let c,l;for(c=0;cn)continue;t.pos=s;const o=e.name;if(e.encoding){let i="";for(let a=0,r=e.length;a0&&(c+=e-1)}}else{if(d||p){warn("TT: nested FDEFs not allowed");u=!0}d=!0;h=c;n=C.pop();t.functionsDefined[n]={data:g,i:c}}else if(!d&&!p){n=C.at(-1);if(isNaN(n))info("TT: CALL empty stack (or invalid entry).");else{t.functionsUsed[n]=!0;if(n in t.functionsStackDeltas){const e=C.length+t.functionsStackDeltas[n];if(e<0){warn("TT: CALL invalid functions stack delta.");t.hintsValid=!1;return}C.length=e}else if(n in t.functionsDefined&&!E.includes(n)){Q.push({data:g,i:c,stackTop:C.length-1});E.push(n);o=t.functionsDefined[n];if(!o){warn("TT: CALL non-existent function");t.hintsValid=!1;return}g=o.data;c=o.i}}}if(!d&&!p){let t=0;e<=142?t=r[e]:e>=192&&e<=223?t=-1:e>=224&&(t=-2);if(e>=113&&e<=117){a=C.pop();isNaN(a)||(t=2*-a)}for(;t<0&&C.length>0;){C.pop();t++}for(;t>0;){C.push(NaN);t--}}}t.tooComplexToFollowFunctions=u;const m=[g];c>g.length&&m.push(new Uint8Array(c-g.length));if(h>l){warn("TT: complementing a missing function tail");m.push(new Uint8Array([34,45]))}!function foldTTTable(e,t){if(t.length>1){let i,a,r=0;for(i=0,a=t.length;i>>0,s=[];for(let t=0;t>>0);const n={ttcTag:t,majorVersion:i,minorVersion:a,numFonts:r,offsetTable:s};switch(i){case 1:return n;case 2:n.dsigTag=e.getInt32()>>>0;n.dsigLength=e.getInt32()>>>0;n.dsigOffset=e.getInt32()>>>0;return n}throw new FormatError(`Invalid TrueType Collection majorVersion: ${i}.`)}(e),r=t.split("+");let s;for(let n=0;n0||!(i.cMap instanceof IdentityCMap));if("OTTO"===s.version&&!t||!n.head||!n.hhea||!n.maxp||!n.post){g=new Stream(n["CFF "].data);o=new CFFFont(g,i);adjustWidths(i);return this.convert(e,o,i)}delete n.glyf;delete n.loca;delete n.fpgm;delete n.prep;delete n["cvt "];this.isOpenType=!0}if(!n.maxp)throw new FormatError('Required "maxp" table is not found');t.pos=(t.start||0)+n.maxp.offset;let l=t.getInt32();const h=t.getUint16();if(65536!==l&&20480!==l){if(6===n.maxp.length)l=20480;else{if(!(n.maxp.length>=32))throw new FormatError('"maxp" table has a wrong version number');l=65536}!function writeUint32(e,t,i){e[t+3]=255&i;e[t+2]=i>>>8;e[t+1]=i>>>16;e[t]=i>>>24}(n.maxp.data,0,l)}if(i.scaleFactors?.length===h&&c){const{scaleFactors:e}=i,t=int16(n.head.data[50],n.head.data[51]),a=new GlyfTable({glyfTable:n.glyf.data,isGlyphLocationsLong:t,locaTable:n.loca.data,numGlyphs:h});a.scale(e);const{glyf:r,loca:s,isLocationLong:o}=a.write();n.glyf.data=r;n.loca.data=s;if(o!==!!t){n.head.data[50]=0;n.head.data[51]=o?1:0}const g=n.hmtx.data;for(let t=0;t>8&255;g[i+1]=255&a;writeSignedInt16(g,i+2,Math.round(e[t]*signedInt16(g[i+2],g[i+3])))}}let C=h+1,Q=!0;if(C>65535){Q=!1;C=h;warn("Not enough space in glyfs to duplicate first glyph.")}let E=0,u=0;if(l>=65536&&n.maxp.length>=32){t.pos+=8;if(t.getUint16()>2){n.maxp.data[14]=0;n.maxp.data[15]=2}t.pos+=4;E=t.getUint16();t.pos+=4;u=t.getUint16()}n.maxp.data[4]=C>>8;n.maxp.data[5]=255&C;const d=function sanitizeTTPrograms(e,t,i,a){const r={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};e&&sanitizeTTProgram(e,r);t&&sanitizeTTProgram(t,r);e&&function checkInvalidFunctions(e,t){if(!e.tooComplexToFollowFunctions)if(e.functionsDefined.length>t){warn("TT: more functions defined than expected");e.hintsValid=!1}else for(let i=0,a=e.functionsUsed.length;it){warn("TT: invalid function id: "+i);e.hintsValid=!1;return}if(e.functionsUsed[i]&&!e.functionsDefined[i]){warn("TT: undefined function: "+i);e.hintsValid=!1;return}}}(r,a);if(i&&1&i.length){const e=new Uint8Array(i.length+1);e.set(i.data);i.data=e}return r.hintsValid}(n.fpgm,n.prep,n["cvt "],E);if(!d){delete n.fpgm;delete n.prep;delete n["cvt "]}!function sanitizeMetrics(e,t,i,a,r,s){if(!t){i&&(i.data=null);return}e.pos=(e.start||0)+t.offset;e.pos+=4;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;const n=e.getUint16();e.pos+=8;e.pos+=2;let o=e.getUint16();if(0!==n){if(!(2&int16(a.data[44],a.data[45]))){t.data[22]=0;t.data[23]=0}}if(o>r){info(`The numOfMetrics (${o}) should not be greater than the numGlyphs (${r}).`);o=r;t.data[34]=(65280&o)>>8;t.data[35]=255&o}const g=r-o-(i.length-4*o>>1);if(g>0){const e=new Uint8Array(i.length+2*g);e.set(i.data);if(s){e[i.length]=i.data[2];e[i.length+1]=i.data[3]}i.data=e}}(t,n.hhea,n.hmtx,n.head,C,Q);if(!n.head)throw new FormatError('Required "head" table is not found');!function sanitizeHead(e,t,i){const a=e.data,r=function int32(e,t,i,a){return(e<<24)+(t<<16)+(i<<8)+a}(a[0],a[1],a[2],a[3]);if(r>>16!=1){info("Attempting to fix invalid version in head table: "+r);a[0]=0;a[1]=1;a[2]=0;a[3]=0}const s=int16(a[50],a[51]);if(s<0||s>1){info("Attempting to fix invalid indexToLocFormat in head table: "+s);const e=t+1;if(i===e<<1){a[50]=0;a[51]=0}else{if(i!==e<<2)throw new FormatError("Could not fix indexToLocFormat: "+s);a[50]=0;a[51]=1}}}(n.head,h,c?n.loca.length:0);let f=Object.create(null);if(c){const e=int16(n.head.data[50],n.head.data[51]),t=function sanitizeGlyphLocations(e,t,i,a,r,s,n){let o,g,c;if(a){o=4;g=function fontItemDecodeLong(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]};c=function fontItemEncodeLong(e,t,i){e[t]=i>>>24&255;e[t+1]=i>>16&255;e[t+2]=i>>8&255;e[t+3]=255&i}}else{o=2;g=function fontItemDecode(e,t){return e[t]<<9|e[t+1]<<1};c=function fontItemEncode(e,t,i){e[t]=i>>9&255;e[t+1]=i>>1&255}}const l=s?i+1:i,h=o*(1+l),C=new Uint8Array(h);C.set(e.data.subarray(0,h));e.data=C;const Q=t.data,E=Q.length,u=new Uint8Array(E);let d,f;const p=[];for(d=0,f=0;dE&&(e=E);p.push({index:d,offset:e,endOffset:0})}p.sort(((e,t)=>e.offset-t.offset));for(d=0;de.index-t.index));for(d=0;dn&&(n=e.sizeOfInstructions);w+=t;c(C,f,w)}if(0===w){const e=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(d=0,f=o;di+w)t.data=u.subarray(0,i+w);else{t.data=new Uint8Array(i+w);t.data.set(u.subarray(0,w))}t.data.set(u.subarray(0,i),w);c(e.data,C.length-o,w+i)}else t.data=u.subarray(0,w);return{missingGlyphs:y,maxSizeOfInstructions:n}}(n.loca,n.glyf,h,e,d,Q,u);f=t.missingGlyphs;if(l>=65536&&n.maxp.length>=32){n.maxp.data[26]=t.maxSizeOfInstructions>>8;n.maxp.data[27]=255&t.maxSizeOfInstructions}}if(!n.hhea)throw new FormatError('Required "hhea" table is not found');if(0===n.hhea.data[10]&&0===n.hhea.data[11]){n.hhea.data[10]=255;n.hhea.data[11]=255}const p={unitsPerEm:int16(n.head.data[18],n.head.data[19]),yMax:signedInt16(n.head.data[42],n.head.data[43]),yMin:signedInt16(n.head.data[38],n.head.data[39]),ascent:signedInt16(n.hhea.data[4],n.hhea.data[5]),descent:signedInt16(n.hhea.data[6],n.hhea.data[7]),lineGap:signedInt16(n.hhea.data[8],n.hhea.data[9])};this.ascent=p.ascent/p.unitsPerEm;this.descent=p.descent/p.unitsPerEm;this.lineGap=p.lineGap/p.unitsPerEm;if(this.cssFontInfo?.lineHeight){this.lineHeight=this.cssFontInfo.metrics.lineHeight;this.lineGap=this.cssFontInfo.metrics.lineGap}else this.lineHeight=this.ascent-this.descent+this.lineGap;n.post&&function readPostScriptTable(e,i,a){const r=(t.start||0)+e.offset;t.pos=r;const s=r+e.length,n=t.getInt32();t.skip(28);let o,g,c=!0;switch(n){case 65536:o=vi;break;case 131072:const e=t.getUint16();if(e!==a){c=!1;break}const r=[];for(g=0;g=32768){c=!1;break}r.push(e)}if(!c)break;const l=[],h=[];for(;t.pos65535)throw new FormatError("Max size of CID is 65,535");let r=-1;t?r=a:void 0!==e[a]&&(r=e[a]);r>=0&&r>>0;let l=!1;if(o?.platformId!==r||o?.encodingId!==s){if(0!==r||0!==s&&1!==s&&3!==s)if(1===r&&0===s)l=!0;else if(3!==r||1!==s||!a&&o){if(i&&3===r&&0===s){l=!0;let i=!0;if(e>3;e.push(a);i=Math.max(a,i)}const a=[];for(let e=0;e<=i;e++)a.push({firstCode:t.getUint16(),entryCount:t.getUint16(),idDelta:signedInt16(t.getByte(),t.getByte()),idRangePos:t.pos+t.getUint16()});for(let i=0;i<256;i++)if(0===e[i]){t.pos=a[0].idRangePos+2*i;Q=t.getUint16();h.push({charCode:i,glyphId:Q})}else{const r=a[e[i]];for(C=0;C>1;t.skip(6);const i=[];let a;for(a=0;a>1)-(e-a);r.offsetIndex=n;o=Math.max(o,n+r.end-r.start+1)}else r.offsetIndex=-1}const g=[];for(C=0;C>>0;for(C=0;C>>0,i=t.getInt32()>>>0;let a=t.getInt32()>>>0;for(let t=e;t<=i;t++)h.push({charCode:t,glyphId:a++})}}}h.sort((function(e,t){return e.charCode-t.charCode}));for(let e=1;e=61440&&t<=61695&&(t&=255);m[t]=e.glyphId}else for(const e of s)m[e.charCode]=e.glyphId;if(i.glyphNames&&(o.length||this.differences.length))for(let e=0;e<256;++e){if(!g&&void 0!==m[e])continue;const t=this.differences[e]||o[e];if(!t)continue;const a=i.glyphNames.indexOf(t);a>0&&hasGlyph(a)&&(m[e]=a)}}0===m.length&&(m[0]=0);let y=C-1;Q||(y=0);if(!i.cssFontInfo){const e=adjustMapping(m,hasGlyph,y,this.toUnicode);this.toFontChar=e.toFontChar;n.cmap={tag:"cmap",data:createCmapTable(e.charCodeToGlyphId,e.toUnicodeExtraMap,C)};n["OS/2"]&&function validateOS2Table(e,t){t.pos=(t.start||0)+e.offset;const i=t.getUint16();t.skip(60);const a=t.getUint16();if(i<4&&768&a)return!1;if(t.getUint16()>t.getUint16())return!1;t.skip(6);if(0===t.getUint16())return!1;e.data[8]=e.data[9]=0;return!0}(n["OS/2"],t)||(n["OS/2"]={tag:"OS/2",data:createOS2Table(i,e.charCodeToGlyphId,p)})}if(!c)try{g=new Stream(n["CFF "].data);o=new CFFParser(g,i,Gi).parse();o.duplicateFirstGlyph();const e=new CFFCompiler(o);n["CFF "].data=e.compile()}catch{warn("Failed to compile font "+i.loadedName)}if(n.name){const[t,a]=readNameTable(n.name);n.name.data=createNameTable(e,t);this.psName=t[0][6]||null;i.composite||function adjustTrueTypeToUnicode(e,t,i){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(e.hasEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;if(!t)return;if(0===i.length)return;if(e.defaultEncoding===Qi)return;for(const e of i)if(!isWinNameRecord(e))return;const a=Qi,r=[],s=Di();for(const e in a){const t=a[e];if(""===t)continue;const i=s[t];void 0!==i&&(r[e]=String.fromCharCode(i))}r.length>0&&e.toUnicode.amend(r)}(i,this.isSymbolicFont,a)}else n.name={tag:"name",data:createNameTable(this.name)};const w=new OpenTypeFileBuilder(s.version);for(const e in n)w.addTable(e,n[e].data);return w.toArray()}convert(e,t,i){i.fixedPitch=!1;i.builtInEncoding&&function adjustType1ToUnicode(e,t){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(t===e.defaultEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const i=[],a=Di();for(const r in t){if(e.hasEncoding&&(e.baseEncodingName||void 0!==e.differences[r]))continue;const s=getUnicodeForGlyph(t[r],a);-1!==s&&(i[r]=String.fromCharCode(s))}i.length>0&&e.toUnicode.amend(i)}(i,i.builtInEncoding);let a=1;t instanceof CFFFont&&(a=t.numGlyphs-1);const s=t.getGlyphMapping(i);let n=null,o=s,g=null;if(!i.cssFontInfo){n=adjustMapping(s,t.hasGlyphId.bind(t),a,this.toUnicode);this.toFontChar=n.toFontChar;o=n.charCodeToGlyphId;g=n.toUnicodeExtraMap}const c=t.numGlyphs;function getCharCodes(e,t){let i=null;for(const a in e)t===e[a]&&(i||=[]).push(0|a);return i}function createCharCode(e,t){for(const i in e)if(t===e[i])return 0|i;n.charCodeToGlyphId[n.nextAvailableFontCharCode]=t;return n.nextAvailableFontCharCode++}const l=t.seacs;if(n&&l?.length){const e=i.fontMatrix||r,a=t.getCharset(),o=Object.create(null);for(let t in l){t|=0;const i=l[t],r=Bi[i[2]],g=Bi[i[3]],c=a.indexOf(r),h=a.indexOf(g);if(c<0||h<0)continue;const C={x:i[0]*e[0]+i[1]*e[2]+e[4],y:i[0]*e[1]+i[1]*e[3]+e[5]},Q=getCharCodes(s,t);if(Q)for(const e of Q){const t=n.charCodeToGlyphId,i=createCharCode(t,c),a=createCharCode(t,h);o[e]={baseFontCharCode:i,accentFontCharCode:a,accentOffset:C}}}i.seacMap=o}const h=i.fontMatrix?1/Math.max(...i.fontMatrix.slice(0,4).map(Math.abs)):1e3,C=new OpenTypeFileBuilder("OTTO");C.addTable("CFF ",t.data);C.addTable("OS/2",createOS2Table(i,o));C.addTable("cmap",createCmapTable(o,g,c));C.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+safeString16(h)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+safeString16(i.descent)+"ÿ"+safeString16(i.ascent)+string16(i.italicAngle?2:0)+"\0\0\0\0\0\0\0");C.addTable("hhea","\0\0\0"+safeString16(i.ascent)+safeString16(i.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+safeString16(i.capHeight)+safeString16(Math.tan(i.italicAngle)*i.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+string16(c));C.addTable("hmtx",function fontFieldsHmtx(){const e=t.charstrings,i=t.cff?t.cff.widths:null;let a="\0\0\0\0";for(let t=1,r=c;t=65520&&e<=65535?0:e>=62976&&e<=63743?Si()[e]||e:173===e?45:e}(i)}this.isType3Font&&(r=i);let l=null;if(this.seacMap?.[e]){c=!0;const t=this.seacMap[e];i=t.baseFontCharCode;l={fontChar:String.fromCodePoint(t.accentFontCharCode),offset:t.accentOffset}}let h="";"number"==typeof i&&(i<=1114111?h=String.fromCodePoint(i):warn(`charToGlyph - invalid fontCharCode: ${i}`));if(this.missingFile&&this.vertical&&1===h.length){const e=Yi()[h.charCodeAt(0)];e&&(h=g=String.fromCharCode(e))}s=new fonts_Glyph(e,h,g,l,a,o,r,t,c);return this._glyphCache[e]=s}charsToGlyphs(e){let t=this._charsCache[e];if(t)return t;t=[];if(this.cMap){const i=Object.create(null),a=e.length;let r=0;for(;rt.length%2==1,a=this.toUnicode instanceof IdentityToUnicodeMap?e=>this.toUnicode.charCodeOf(e):e=>this.toUnicode.charCodeOf(String.fromCodePoint(e));for(let r=0,s=e.length;r55295&&(s<57344||s>65533)&&r++;if(this.toUnicode){const e=a(s);if(-1!==e){if(hasCurrentBufErrors()){t.push(i.join(""));i.length=0}for(let t=(this.cMap?this.cMap.getCharCodeLength(e):1)-1;t>=0;t--)i.push(String.fromCharCode(e>>8*t&255));continue}}if(!hasCurrentBufErrors()){t.push(i.join(""));i.length=0}i.push(String.fromCodePoint(s))}t.push(i.join(""));return t}}class ErrorFont{constructor(e){this.error=e;this.loadedName="g_font_error";this.missingFile=!0}charsToGlyphs(){return[]}encodeString(e){return[e]}exportData(e=!1){return{error:this.error}}}const la=2,ha=3,Ca=4,Ba=5,Qa=6,Ea=7;class Pattern{constructor(){unreachable("Cannot initialize Pattern.")}static parseShading(e,t,i,a,r){const s=e instanceof BaseStream?e.dict:e,n=s.get("ShadingType");try{switch(n){case la:case ha:return new RadialAxialShading(s,t,i,a,r);case Ca:case Ba:case Qa:case Ea:return new MeshShading(e,t,i,a,r);default:throw new FormatError("Unsupported ShadingType: "+n)}}catch(e){if(e instanceof MissingDataException)throw e;warn(e);return new DummyShading}}}class BaseShading{static SMALL_NUMBER=1e-6;getIR(){unreachable("Abstract method `getIR` called.")}}class RadialAxialShading extends BaseShading{constructor(e,t,i,a,r){super();this.shadingType=e.get("ShadingType");let s=0;this.shadingType===la?s=4:this.shadingType===ha&&(s=6);this.coordsArr=e.getArray("Coords");if(!isNumberArray(this.coordsArr,s))throw new FormatError("RadialAxialShading: Invalid /Coords array.");const n=ColorSpace.parse({cs:e.getRaw("CS")||e.getRaw("ColorSpace"),xref:t,resources:i,pdfFunctionFactory:a,localColorSpaceCache:r});this.bbox=lookupNormalRect(e.getArray("BBox"),null);let o=0,g=1;const c=e.getArray("Domain");isNumberArray(c,2)&&([o,g]=c);let l=!1,h=!1;const C=e.getArray("Extend");(function isBooleanArray(e,t){return Array.isArray(e)&&(null===t||e.length===t)&&e.every((e=>"boolean"==typeof e))})(C,2)&&([l,h]=C);if(!(this.shadingType!==ha||l&&h)){const[e,t,i,a,r,s]=this.coordsArr,n=Math.hypot(e-a,t-r);i<=s+n&&s<=i+n&&warn("Unsupported radial gradient.")}this.extendStart=l;this.extendEnd=h;const Q=e.getRaw("Function"),E=a.createFromArray(Q),u=(g-o)/840,d=this.colorStops=[];if(o>=g||u<=0){info("Bad shading domain.");return}const f=new Float32Array(n.numComps),p=new Float32Array(1);let m,y=0;p[0]=o;E(p,0,f,0);let w=n.getRgb(f,0);const b=Util.makeHexColor(w[0],w[1],w[2]);d.push([0,b]);let D=1;p[0]=o+u;E(p,0,f,0);let S=n.getRgb(f,0),k=S[0]-w[0]+1,R=S[1]-w[1]+1,N=S[2]-w[2]+1,G=S[0]-w[0]-1,M=S[1]-w[1]-1,U=S[2]-w[2]-1;for(let e=2;e<840;e++){p[0]=o+e*u;E(p,0,f,0);m=n.getRgb(f,0);const t=e-y;k=Math.min(k,(m[0]-w[0]+1)/t);R=Math.min(R,(m[1]-w[1]+1)/t);N=Math.min(N,(m[2]-w[2]+1)/t);G=Math.max(G,(m[0]-w[0]-1)/t);M=Math.max(M,(m[1]-w[1]-1)/t);U=Math.max(U,(m[2]-w[2]-1)/t);if(!(G<=k&&M<=R&&U<=N)){const e=Util.makeHexColor(S[0],S[1],S[2]);d.push([D/840,e]);k=m[0]-S[0]+1;R=m[1]-S[1]+1;N=m[2]-S[2]+1;G=m[0]-S[0]-1;M=m[1]-S[1]-1;U=m[2]-S[2]-1;y=D;w=S}D=e;S=m}const x=Util.makeHexColor(S[0],S[1],S[2]);d.push([1,x]);let L="transparent";if(e.has("Background")){m=n.getRgb(e.get("Background"),0);L=Util.makeHexColor(m[0],m[1],m[2])}if(!l){d.unshift([0,L]);d[1][0]+=BaseShading.SMALL_NUMBER}if(!h){d.at(-1)[0]-=BaseShading.SMALL_NUMBER;d.push([1,L])}this.colorStops=d}getIR(){const{coordsArr:e,shadingType:t}=this;let i,a,r,s,n;if(t===la){a=[e[0],e[1]];r=[e[2],e[3]];s=null;n=null;i="axial"}else if(t===ha){a=[e[0],e[1]];r=[e[3],e[4]];s=e[2];n=e[5];i="radial"}else unreachable(`getPattern type unknown: ${t}`);return["RadialAxial",i,this.bbox,this.colorStops,a,r,s,n]}}class MeshStreamReader{constructor(e,t){this.stream=e;this.context=t;this.buffer=0;this.bufferLength=0;const i=t.numComps;this.tmpCompsBuf=new Float32Array(i);const a=t.colorSpace.numComps;this.tmpCsCompsBuf=t.colorFn?new Float32Array(a):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const e=this.stream.getByte();if(e<0)return!1;this.buffer=e;this.bufferLength=8;return!0}readBits(e){let t=this.buffer,i=this.bufferLength;if(32===e){if(0===i)return(this.stream.getByte()<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte())>>>0;t=t<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte();const e=this.stream.getByte();this.buffer=e&(1<>i)>>>0}if(8===e&&0===i)return this.stream.getByte();for(;i>i}align(){this.buffer=0;this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const e=this.context.bitsPerCoordinate,t=this.readBits(e),i=this.readBits(e),a=this.context.decode,r=e<32?1/((1<s?s:e;t=t>n?n:t;i=ie*r[t])):i;let n,o=-2;const g=[];for(const[e,t]of a.map(((e,t)=>[e,t])).sort((([e],[t])=>e-t)))if(-1!==e)if(e===o+1){n.push(s[t]);o+=1}else{o=e;n=[s[t]];g.push(e,n)}return g}(e),i=new Dict(null);i.set("BaseFont",Name.get(e));i.set("Type",Name.get("Font"));i.set("Subtype",Name.get("CIDFontType2"));i.set("Encoding",Name.get("Identity-H"));i.set("CIDToGIDMap",Name.get("Identity"));i.set("W",t);i.set("FirstChar",t[0]);i.set("LastChar",t.at(-2)+t.at(-1).length-1);const a=new Dict(null);i.set("FontDescriptor",a);const r=new Dict(null);r.set("Ordering","Identity");r.set("Registry","Adobe");r.set("Supplement",0);i.set("CIDSystemInfo",r);return i}class PostScriptParser{constructor(e){this.lexer=e;this.operators=[];this.token=null;this.prev=null}nextToken(){this.prev=this.token;this.token=this.lexer.getToken()}accept(e){if(this.token.type===e){this.nextToken();return!0}return!1}expect(e){if(this.accept(e))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${e}.`)}parse(){this.nextToken();this.expect(sr.LBRACE);this.parseBlock();this.expect(sr.RBRACE);return this.operators}parseBlock(){for(;;)if(this.accept(sr.NUMBER))this.operators.push(this.prev.value);else if(this.accept(sr.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(sr.LBRACE))return;this.parseCondition()}}parseCondition(){const e=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(sr.RBRACE);if(this.accept(sr.IF)){this.operators[e]=this.operators.length;this.operators[e+1]="jz"}else{if(!this.accept(sr.LBRACE))throw new FormatError("PS Function: error parsing conditional.");{const t=this.operators.length;this.operators.push(null,null);const i=this.operators.length;this.parseBlock();this.expect(sr.RBRACE);this.expect(sr.IFELSE);this.operators[t]=this.operators.length;this.operators[t+1]="j";this.operators[e]=i;this.operators[e+1]="jz"}}}}const sr={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(e,t){this.type=e;this.value=t}static getOperator(e){return PostScriptToken.opCache[e]||=new PostScriptToken(sr.OPERATOR,e)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(sr.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(sr.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(sr.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(sr.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(e){this.stream=e;this.nextChar();this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(t<0)return Et;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(sr.NUMBER,this.getNumber());case 123:this.nextChar();return PostScriptToken.LBRACE;case 125:this.nextChar();return PostScriptToken.RBRACE}const i=this.strBuf;i.length=0;i[0]=String.fromCharCode(t);for(;(t=this.nextChar())>=0&&(t>=65&&t<=90||t>=97&&t<=122);)i.push(String.fromCharCode(t));const a=i.join("");switch(a.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(a)}}getNumber(){let e=this.currentChar;const t=this.strBuf;t.length=0;t[0]=String.fromCharCode(e);for(;(e=this.nextChar())>=0&&(e>=48&&e<=57||45===e||46===e);)t.push(String.fromCharCode(e));const i=parseFloat(t.join(""));if(isNaN(i))throw new FormatError(`Invalid floating point number: ${i}`);return i}}class BaseLocalCache{constructor(e){this._onlyRefs=!0===e?.onlyRefs;if(!this._onlyRefs){this._nameRefMap=new Map;this._imageMap=new Map}this._imageCache=new RefSetCache}getByName(e){this._onlyRefs&&unreachable("Should not call `getByName` method.");const t=this._nameRefMap.get(e);return t?this.getByRef(t):this._imageMap.get(e)||null}getByRef(e){return this._imageCache.get(e)||null}set(e,t,i){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalImageCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalColorSpaceCache extends BaseLocalCache{set(e=null,t=null,i){if("string"!=typeof e&&!t)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(t){if(this._imageCache.has(t))return;null!==e&&this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalFunctionCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class LocalGStateCache extends BaseLocalCache{set(e,t=null,i){if("string"!=typeof e)throw new Error('LocalGStateCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,i)}else this._imageMap.has(e)||this._imageMap.set(e,i)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class RegionalImageCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,i){if(!t)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,i)}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;#F=new RefSet;constructor(){this._refCache=new RefSetCache;this._imageCache=new RefSetCache}get#S(){let e=0;for(const t of this._imageCache)e+=t.byteSize;return e}get#k(){return!(this._imageCache.size+e)):null}class PDFFunction{static getSampleArray(e,t,i,a){let r,s,n=1;for(r=0,s=e.length;r>g)*l;c&=(1<i?e=i:e0&&(C=s[h-1]);let Q=a[1];h>1,c=r.length>>1,l=new PostScriptEvaluator(o),h=Object.create(null);let C=8192;const Q=new Float32Array(c);return function constructPostScriptFn(e,t,i,a){let r,n,o="";const E=Q;for(r=0;re&&(n=e)}d[r]=n}if(C>0){C--;h[o]=d}i.set(d,a)}}}function isPDFFunction(e){let t;if(e instanceof Dict)t=e;else{if(!(e instanceof BaseStream))return!1;t=e.dict}return t.has("FunctionType")}class PostScriptStack{static MAX_STACK_SIZE=100;constructor(e){this.stack=e?Array.from(e):[]}push(e){if(this.stack.length>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(e)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(e){if(this.stack.length+e>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const t=this.stack;for(let i=t.length-e,a=e-1;a>=0;a--,i++)t.push(t[i])}index(e){this.push(this.stack[this.stack.length-e-1])}roll(e,t){const i=this.stack,a=i.length-e,r=i.length-1,s=a+(t-Math.floor(t/e)*e);for(let e=a,t=r;e0?t.push(n<>o);break;case"ceiling":n=t.pop();t.push(Math.ceil(n));break;case"copy":n=t.pop();t.copy(n);break;case"cos":n=t.pop();t.push(Math.cos(n%360/180*Math.PI));break;case"cvi":n=0|t.pop();t.push(n);break;case"cvr":break;case"div":o=t.pop();n=t.pop();t.push(n/o);break;case"dup":t.copy(1);break;case"eq":o=t.pop();n=t.pop();t.push(n===o);break;case"exch":t.roll(2,1);break;case"exp":o=t.pop();n=t.pop();t.push(n**o);break;case"false":t.push(!1);break;case"floor":n=t.pop();t.push(Math.floor(n));break;case"ge":o=t.pop();n=t.pop();t.push(n>=o);break;case"gt":o=t.pop();n=t.pop();t.push(n>o);break;case"idiv":o=t.pop();n=t.pop();t.push(n/o|0);break;case"index":n=t.pop();t.index(n);break;case"le":o=t.pop();n=t.pop();t.push(n<=o);break;case"ln":n=t.pop();t.push(Math.log(n));break;case"log":n=t.pop();t.push(Math.log10(n));break;case"lt":o=t.pop();n=t.pop();t.push(n=t?new AstLiteral(t):e.max<=t?e:new AstMin(e,t)}class PostScriptCompiler{compile(e,t,i){const a=[],r=[],s=t.length>>1,n=i.length>>1;let o,g,c,l,h,C,Q,E,u=0;for(let e=0;et.min){o.unshift("Math.max(",s,", ");o.push(")")}if(n4){a=!0;t=0}else{a=!1;t=1}const g=[];for(s=0;s=0&&"ET"===Ir[e];--e)Ir[e]="EN";for(let e=s+1;e0&&(t=Ir[s-1]);let i=h;e+1E&&isOdd(E)&&(d=E)}for(E=u;E>=d;--E){let e=-1;for(s=0,n=g.length;s=0){reverseValues(gr,e,s);e=-1}}else e<0&&(e=s);e>=0&&reverseValues(gr,e,g.length)}for(s=0,n=gr.length;s"!==e||(gr[s]="")}return createBidiText(gr.join(""),a)}const cr={style:"normal",weight:"normal"},lr={style:"normal",weight:"bold"},hr={style:"italic",weight:"normal"},Cr={style:"italic",weight:"bold"},Qr=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:cr,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:lr,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:hr,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:Cr,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:cr,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:lr,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:hr,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:Cr,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:cr,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:lr,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:hr,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:Cr,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:cr,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:lr,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:hr,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:Cr,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:cr,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:lr,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:hr,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:Cr,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:cr}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),Er=new Map([["Arial-Black","ArialBlack"]]);function getFamilyName(e){const t=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return e.split(/[- ,+]+/g).filter((e=>!t.has(e.toLowerCase()))).join(" ")}function generateFont({alias:e,local:t,path:i,fallback:a,style:r,ultimate:s},n,o,g=!0,c=!0,l=""){const h={style:null,ultimate:null};if(t){const e=l?` ${l}`:"";for(const i of t)n.push(`local(${i}${e})`)}if(e){const t=Qr.get(e),s=l||function getStyleToAppend(e){switch(e){case lr:return"Bold";case hr:return"Italic";case Cr:return"Bold Italic";default:if("bold"===e?.weight)return"Bold";if("italic"===e?.style)return"Italic"}return""}(r);Object.assign(h,generateFont(t,n,o,g&&!a,c&&!i,s))}r&&(h.style=r);s&&(h.ultimate=s);if(g&&a){const e=Qr.get(a),{ultimate:t}=generateFont(e,n,o,g,c&&!i,l);h.ultimate||=t}c&&i&&o&&n.push(`url(${o}${i})`);return h}function getFontSubstitution(e,t,i,a,r,s){if(a.startsWith("InvalidPDFjsFont_"))return null;"TrueType"!==s&&"Type1"!==s||!/^[A-Z]{6}\+/.test(a)||(a=a.slice(7));const n=a=normalizeFontName(a);let o=e.get(n);if(o)return o;let g=Qr.get(a);if(!g)for(const[e,t]of Er)if(a.startsWith(e)){a=`${t}${a.substring(e.length)}`;g=Qr.get(a);break}let c=!1;if(!g){g=Qr.get(r);c=!0}const l=`${t.getDocId()}_s${t.createFontId()}`;if(!g){if(!validateFontName(a)){warn(`Cannot substitute the font because of its name: ${a}`);e.set(n,null);return null}const t=/bold/gi.test(a),i=/oblique|italic/gi.test(a),r=t&&i&&Cr||t&&lr||i&&hr||cr;o={css:`"${getFamilyName(a)}",${l}`,guessFallback:!0,loadedName:l,baseFontName:a,src:`local(${a})`,style:r};e.set(n,o);return o}const h=[];c&&validateFontName(a)&&h.push(`local(${a})`);const{style:C,ultimate:Q}=generateFont(g,h,i),E=null===Q,u=E?"":`,${Q}`;o={css:`"${getFamilyName(a)}",${l}${u}`,guessFallback:E,loadedName:l,baseFontName:a,src:h.join(","),style:C};e.set(n,o);return o}class ImageResizer{static#R=2048;static#y=FeatureTest.isImageDecoderSupported;constructor(e,t){this._imgData=e;this._isMask=t}static get canUseImageDecoder(){return shadow(this,"canUseImageDecoder",this.#y?ImageDecoder.isTypeSupported("image/bmp"):Promise.resolve(!1))}static needsToBeResized(e,t){if(e<=this.#R&&t<=this.#R)return!1;const{MAX_DIM:i}=this;if(e>i||t>i)return!0;const a=e*t;if(this._hasMaxArea)return a>this.MAX_AREA;if(a(this.MAX_AREA=this.#R**2)}static get MAX_DIM(){return shadow(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){this._hasMaxArea=!0;return shadow(this,"MAX_AREA",this._guessMax(this.#R,this.MAX_DIM,128,0)**2)}static set MAX_AREA(e){if(e>=0){this._hasMaxArea=!0;shadow(this,"MAX_AREA",e)}}static setOptions({canvasMaxAreaInBytes:e=-1,isImageDecoderSupported:t=!1}){this._hasMaxArea||(this.MAX_AREA=e>>2);this.#y=t}static _areGoodDims(e,t){try{const i=new OffscreenCanvas(e,t),a=i.getContext("2d");a.fillRect(0,0,1,1);const r=a.getImageData(0,0,1,1).data[3];i.width=i.height=1;return 0!==r}catch{return!1}}static _guessMax(e,t,i,a){for(;e+i+1yt){const e=this.#N();if(e)return e}const a=this._encodeBMP();let r,s;if(await ImageResizer.canUseImageDecoder){r=new ImageDecoder({data:a,type:"image/bmp",preferAnimation:!1,transfer:[a.buffer]});s=r.decode().catch((e=>{warn(`BMP image decoding failed: ${e}`);return createImageBitmap(new Blob([this._encodeBMP().buffer],{type:"image/bmp"}))})).finally((()=>{r.close()}))}else s=createImageBitmap(new Blob([a.buffer],{type:"image/bmp"}));const{MAX_AREA:n,MAX_DIM:o}=ImageResizer,g=Math.max(t/o,i/o,Math.sqrt(t*i/n)),c=Math.max(g,2),l=Math.round(10*(g+1.25))/10/c,h=Math.floor(Math.log2(l)),C=new Array(h+2).fill(2);C[0]=c;C.splice(-1,1,l/(1<>n,g=a>>n;let c,l=a;try{c=new Uint8Array(s)}catch{let e=Math.floor(Math.log2(s+1));for(;;)try{c=new Uint8Array(2**e-1);break}catch{e-=1}l=Math.floor((2**e-1)/(4*i));const t=i*l*4;t>n;e>3,n=i+3&-4;if(i!==n){const e=new Uint8Array(n*t);let a=0;for(let s=0,o=t*i;s>>8;t[i++]=255&r}}}else{if(!ArrayBuffer.isView(e))throw new Error("Invalid data format, must be a string or TypedArray.");t=e.slice();i=t.byteLength}const a=i>>2,r=i-4*a,s=new Uint32Array(t.buffer,0,a);let n=0,o=0,g=this.h1,c=this.h2;const l=3432918353,h=461845907,C=11601,Q=13715;for(let e=0;e>>17;n=n*h&dr|n*Q&fr;g^=n;g=g<<13|g>>>19;g=5*g+3864292196}else{o=s[e];o=o*l&dr|o*C&fr;o=o<<15|o>>>17;o=o*h&dr|o*Q&fr;c^=o;c=c<<13|c>>>19;c=5*c+3864292196}n=0;switch(r){case 3:n^=t[4*a+2]<<16;case 2:n^=t[4*a+1]<<8;case 1:n^=t[4*a];n=n*l&dr|n*C&fr;n=n<<15|n>>>17;n=n*h&dr|n*Q&fr;1&a?g^=n:c^=n}this.h1=g;this.h2=c}hexdigest(){let e=this.h1,t=this.h2;e^=t>>>1;e=3981806797*e&dr|36045*e&fr;t=4283543511*t&dr|(2950163797*(t<<16|e>>>16)&dr)>>>16;e^=t>>>1;e=444984403*e&dr|60499*e&fr;t=3301882366*t&dr|(3120437893*(t<<16|e>>>16)&dr)>>>16;e^=t>>>1;return(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}function addState(e,t,i,a,r){let s=e;for(let e=0,i=t.length-1;e1e3){c=Math.max(c,C);Q+=h+2;C=0;h=0}l.push({transform:t,x:C,y:Q,w:i.width,h:i.height});C+=i.width+2;h=Math.max(h,i.height)}const E=Math.max(c,C)+1,u=Q+h+1,d=new Uint8Array(E*u*4),f=E<<2;for(let e=0;e=0;){t[s-4]=t[s];t[s-3]=t[s+1];t[s-2]=t[s+2];t[s-1]=t[s+3];t[s+i]=t[s+i-4];t[s+i+1]=t[s+i-3];t[s+i+2]=t[s+i-2];t[s+i+3]=t[s+i-1];s-=f}}const p={width:E,height:u};if(e.isOffscreenCanvasSupported){const e=new OffscreenCanvas(E,u);e.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(d.buffer),E,u),0,0);p.bitmap=e.transferToImageBitmap();p.data=null}else{p.kind=R;p.data=d}i.splice(s,4*g,et);a.splice(s,4*g,[p,l]);return s+1}));addState(pr,[xA,HA,_e,LA],null,(function iterateImageMaskGroup(e,t){const i=e.fnArray,a=(t-(e.iCurr-3))%4;switch(a){case 0:return i[t]===xA;case 1:return i[t]===HA;case 2:return i[t]===_e;case 3:return i[t]===LA}throw new Error(`iterateImageMaskGroup - invalid pos: ${a}`)}),(function foundImageMaskGroup(e,t){const i=e.fnArray,a=e.argsArray,r=e.iCurr,s=r-3,n=r-2,o=r-1;let g=Math.floor((t-s)/4);if(g<10)return t-(t-s)%4;let c,l,h=!1;const C=a[o][0],Q=a[n][0],E=a[n][1],u=a[n][2],d=a[n][3];if(E===u){h=!0;c=n+4;let e=o+4;for(let t=1;t=4&&i[s-4]===i[n]&&i[s-3]===i[o]&&i[s-2]===i[g]&&i[s-1]===i[c]&&a[s-4][0]===l&&a[s-4][1]===h){C++;Q-=5}let E=Q+4;for(let e=1;e=i)break}a=(a||pr)[e[t]];if(a&&!Array.isArray(a)){s.iCurr=t;t++;if(!a.checkFn||(0,a.checkFn)(s)){r=a;a=null}else a=null}else t++}this.state=a;this.match=r;this.lastProcessed=t}flush(){for(;this.match;){const e=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,e);this.match=null;this.state=null;this._optimize()}}reset(){this.state=null;this.match=null;this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;constructor(e=0,t){this._streamSink=t;this.fnArray=[];this.argsArray=[];this.optimizer=!t||e&u?new NullOptimizer(this):new QueueOptimizer(this);this.dependencies=new Set;this._totalLength=0;this.weight=0;this._resolved=t?null:Promise.resolve()}set isOffscreenCanvasSupported(e){this.optimizer.isOffscreenCanvasSupported=e}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(e,t){this.optimizer.push(e,t);this.weight++;this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(e===LA||e===ie))&&this.flush()}addImageOps(e,t,i,a=!1){if(a){this.addOp(xA);this.addOp(UA,[[["SMask",!1]]])}void 0!==i&&this.addOp(Ke,["OC",i]);this.addOp(e,t);void 0!==i&&this.addOp(Te,[]);a&&this.addOp(LA)}addDependency(e){if(!this.dependencies.has(e)){this.dependencies.add(e);this.addOp(DA,[e])}}addDependencies(e){for(const t of e)this.addDependency(t)}addOpList(e){if(e instanceof OperatorList){for(const t of e.dependencies)this.dependencies.add(t);for(let t=0,i=e.length;ta&&(e=a);return e}function resizeImageMask(e,t,i,a,r,s){const n=r*s;let o;o=t<=8?new Uint8Array(n):t<=16?new Uint16Array(n):new Uint32Array(n);const g=i/r,c=a/s;let l,h,C,Q,E=0;const u=new Uint16Array(r),d=i;for(l=0;l0&&Number.isInteger(i.height)&&i.height>0&&(i.width!==C||i.height!==Q)){warn("PDFImage - using the Width/Height of the image data, rather than the image dictionary.");C=i.width;Q=i.height}if(C<1||Q<1)throw new FormatError(`Invalid image width: ${C} or height: ${Q}`);this.width=C;this.height=Q;this.interpolate=c.get("I","Interpolate");this.imageMask=c.get("IM","ImageMask")||!1;this.matte=c.get("Matte")||!1;let E=i.bitsPerComponent;if(!E){E=c.get("BPC","BitsPerComponent");if(!E){if(!this.imageMask)throw new FormatError(`Bits per component missing in image: ${this.imageMask}`);E=1}}this.bpc=E;if(!this.imageMask){let r=c.getRaw("CS")||c.getRaw("ColorSpace");const s=!!r;if(s)this.jpxDecoderOptions?.smaskInData&&(r=Name.get("DeviceRGBA"));else if(this.jpxDecoderOptions)r=Name.get("DeviceRGBA");else switch(i.numComps){case 1:r=Name.get("DeviceGray");break;case 3:r=Name.get("DeviceRGB");break;case 4:r=Name.get("DeviceCMYK");break;default:throw new Error(`Images with ${i.numComps} color components not supported.`)}this.colorSpace=ColorSpace.parse({cs:r,xref:e,resources:a?t:null,pdfFunctionFactory:o,localColorSpaceCache:g});this.numComps=this.colorSpace.numComps;if(this.jpxDecoderOptions){this.jpxDecoderOptions.numComponents=s?this.numComp:0;this.jpxDecoderOptions.isIndexedColormap="Indexed"===this.colorSpace.name}}this.decode=c.getArray("D","Decode");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,E)||n&&!ColorSpace.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const e=(1<>3)*i,o=e.byteLength;let g,c;if(!a||r&&!(n===o))if(r){g=new Uint8Array(n);g.set(e);g.fill(255,o)}else g=new Uint8Array(e);else g=e;if(r)for(c=0;c>7&1;n[C+1]=h>>6&1;n[C+2]=h>>5&1;n[C+3]=h>>4&1;n[C+4]=h>>3&1;n[C+5]=h>>2&1;n[C+6]=h>>1&1;n[C+7]=1&h;C+=8}if(C>=1}}}}else{let i=0;h=0;for(C=0,l=s;C>a;r<0?r=0:r>c&&(r=c);n[C]=r;h&=(1<n[a+1]){t=255;break}}o[l]=t}}}if(o)for(l=0,C=3,h=t*a;l>3,l=t&&ImageResizer.needsToBeResized(i,a);if(!this.smask&&!this.mask&&"DeviceRGBA"===this.colorSpace.name){r.kind=R;const e=r.data=await this.getImageBytes(o*n*4,{});return t?l?ImageResizer.createImage(r,!1):this.createBitmap(R,i,a,e):r}if(!e){let e;"DeviceGray"===this.colorSpace.name&&1===g?e=S:"DeviceRGB"!==this.colorSpace.name||8!==g||this.needsDecode||(e=k);if(e&&!this.smask&&!this.mask&&i===n&&a===o){const s=await this.#G(n,o);if(s)return s;const g=await this.getImageBytes(o*c,{});if(t)return l?ImageResizer.createImage({data:g,kind:e,width:i,height:a,interpolate:this.interpolate},this.needsDecode):this.createBitmap(e,n,o,g);r.kind=e;r.data=g;if(this.needsDecode){assert(e===S,"PDFImage.createImageData: The image must be grayscale.");const t=r.data;for(let e=0,i=t.length;e>3,n=await this.getImageBytes(a*s,{internal:!0}),o=this.getComponents(n);let g,c;if(1===r){c=i*a;if(this.needsDecode)for(g=0;g0&&t.args[0].count++}class TimeSlotManager{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){if(++this.checkedh){const e="Image exceeded maximum allowed size and was removed.";if(this.options.ignoreErrors){warn(e);return}throw new Error(e)}let C;o.has("OC")&&(C=await this.parseMarkedContentProps(o.get("OC"),e));let Q,E;if(o.get("IM","ImageMask")||!1){const e=o.get("I","Interpolate"),i=c+7>>3,n=t.getBytes(i*l),h=o.getArray("D","Decode");if(this.parsingType3Font){Q=PDFImage.createRawMask({imgArray:n,width:c,height:l,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e});Q.cached=!!r;E=[Q];a.addImageOps(_e,E,C);if(r){const e={fn:_e,args:E,optionalContent:C};s.set(r,g,e);g&&this._regionalImageCache.set(null,g,e)}return}Q=await PDFImage.createMask({imgArray:n,width:c,height:l,imageIsFromDecodeStream:t instanceof DecodeStream,inverseDecode:h?.[0]>0,interpolate:e,isOffscreenCanvasSupported:this.options.isOffscreenCanvasSupported});if(Q.isSingleOpaquePixel){a.addImageOps(at,[],C);if(r){const e={fn:at,args:[],optionalContent:C};s.set(r,g,e);g&&this._regionalImageCache.set(null,g,e)}return}const u=`mask_${this.idFactory.createObjId()}`;a.addDependency(u);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;this._sendImgData(u,Q);E=[{data:u,width:Q.width,height:Q.height,interpolate:Q.interpolate,count:1}];a.addImageOps(_e,E,C);if(r){const e={objId:u,fn:_e,args:E,optionalContent:C};s.set(r,g,e);g&&this._regionalImageCache.set(null,g,e)}return}const u=o.has("SMask")||o.has("Mask");if(i&&c+l<200&&!u){try{const r=new PDFImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n});Q=await r.createImageData(!0,!1);a.isOffscreenCanvasSupported=this.options.isOffscreenCanvasSupported;a.addImageOps(At,[Q],C)}catch(e){const t=`Unable to decode inline image: "${e}".`;if(!this.options.ignoreErrors)throw new Error(t);warn(t)}return}let d=`img_${this.idFactory.createObjId()}`,f=!1;if(this.parsingType3Font)d=`${this.idFactory.getDocId()}_type3_${d}`;else if(r&&g){f=this.globalImageCache.shouldCache(g,this.pageIndex);if(f){assert(!i,"Cannot cache an inline image globally.");d=`${this.idFactory.getDocId()}_${d}`}}a.addDependency(d);E=[d,c,l];a.addImageOps($e,E,C,u);if(f){if(this.globalImageCache.hasDecodeFailed(g)){this.globalImageCache.setData(g,{objId:d,fn:$e,args:E,optionalContent:C,hasMask:u,byteSize:0});this._sendImgData(d,null,f);return}if(c*l>25e4||u){const e=await this.handler.sendWithPromise("commonobj",[d,"CopyLocalImage",{imageRef:g}]);if(e){this.globalImageCache.setData(g,{objId:d,fn:$e,args:E,optionalContent:C,hasMask:u,byteSize:0});this.globalImageCache.addByteSize(g,e);return}}}PDFImage.buildImage({xref:this.xref,res:e,image:t,isInline:i,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:n}).then((async e=>{Q=await e.createImageData(!1,this.options.isOffscreenCanvasSupported);Q.dataLen=Q.bitmap?Q.width*Q.height*4:Q.data.length;Q.ref=g;f&&this.globalImageCache.addByteSize(g,Q.dataLen);return this._sendImgData(d,Q,f)})).catch((e=>{warn(`Unable to decode image "${d}": "${e}".`);g&&this.globalImageCache.addDecodeFailed(g);return this._sendImgData(d,null,f)}));if(r){const e={objId:d,fn:$e,args:E,optionalContent:C,hasMask:u};s.set(r,g,e);if(g){this._regionalImageCache.set(null,g,e);f&&this.globalImageCache.setData(g,{objId:d,fn:$e,args:E,optionalContent:C,hasMask:u,byteSize:0})}}}handleSMask(e,t,i,a,r,s){const n=e.get("G"),o={subtype:e.get("S").name,backdrop:e.get("BC")},g=e.get("TR");if(isPDFFunction(g)){const e=this._pdfFunctionFactory.create(g),t=new Uint8Array(256),i=new Float32Array(1);for(let a=0;a<256;a++){i[0]=a/255;e(i,0,i,0);t[a]=255*i[0]|0}o.transferMap=t}return this.buildFormXObject(t,n,o,i,a,r.state.clone(),s)}handleTransferFunction(e){let t;if(Array.isArray(e))t=e;else{if(!isPDFFunction(e))return null;t=[e]}const i=[];let a=0,r=0;for(const e of t){const t=this.xref.fetchIfRef(e);a++;if(isName(t,"Identity")){i.push(null);continue}if(!isPDFFunction(t))return null;const s=this._pdfFunctionFactory.create(t),n=new Uint8Array(256),o=new Float32Array(1);for(let e=0;e<256;e++){o[0]=e/255;s(o,0,o,0);n[e]=255*o[0]|0}i.push(n);r++}return 1!==a&&4!==a||0===r?null:i}handleTilingType(e,t,i,a,r,s,n,o){const g=new OperatorList,c=Dict.merge({xref:this.xref,dictArray:[r.get("Resources"),i]});return this.getOperatorList({stream:a,task:n,resources:c,operatorList:g}).then((function(){const i=g.getIR(),a=getTilingPatternIR(i,r,t);s.addDependencies(g.dependencies);s.addOp(e,a);r.objId&&o.set(null,r.objId,{operatorListIR:i,dict:r})})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`handleTilingType - ignoring pattern: "${e}".`)}}))}async handleSetFont(e,t,i,a,r,s,n=null,o=null){const g=t?.[0]instanceof Name?t[0].name:null;let c=await this.loadFont(g,i,e,n,o);if(c.font.isType3Font)try{await c.loadType3Data(this,e,r);a.addDependencies(c.type3Dependencies)}catch(e){c=new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Type3 font load error: ${e}`),dict:c.font,evaluatorOptions:this.options})}s.font=c.font;c.send(this.handler);return c.loadedName}handleText(e,t){const i=t.font,a=i.charsToGlyphs(e);if(i.data){(!!(t.textRenderingMode&D)||"Pattern"===t.fillColorSpace.name||i.disableFontFace||this.options.disableFontFace)&&PartialEvaluator.buildFontPaths(i,a,this.handler,this.options)}return a}ensureStateFont(e){if(e.font)return;const t=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw t;warn(`ensureStateFont: "${t}".`)}async setGState({resources:e,gState:t,operatorList:i,cacheKey:a,task:r,stateManager:s,localGStateCache:n,localColorSpaceCache:o}){const g=t.objId;let c=!0;const l=[];let h=Promise.resolve();for(const a of t.getKeys()){const n=t.get(a);switch(a){case"Type":break;case"LW":case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":l.push([a,n]);break;case"Font":c=!1;h=h.then((()=>this.handleSetFont(e,null,n[0],i,r,s.state).then((function(e){i.addDependency(e);l.push([a,[e,n[1]]])}))));break;case"BM":l.push([a,normalizeBlendMode(n)]);break;case"SMask":if(isName(n,"None")){l.push([a,!1]);break}if(n instanceof Dict){c=!1;h=h.then((()=>this.handleSMask(n,e,i,r,s,o)));l.push([a,!0])}else warn("Unsupported SMask type");break;case"TR":const t=this.handleTransferFunction(n);l.push([a,t]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+a);break;default:info("Unknown graphic state operator "+a)}}await h;l.length>0&&i.addOp(UA,[l]);c&&n.set(a,g,l)}loadFont(e,t,i,a=null,r=null){const errorFont=async()=>new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${e}" is not available.`),dict:t,evaluatorOptions:this.options});let s;if(t)t instanceof Ref&&(s=t);else{const t=i.get("Font");t&&(s=t.getRaw(e))}if(s){if(this.type3FontRefs?.has(s))return errorFont();if(this.fontCache.has(s))return this.fontCache.get(s);try{t=this.xref.fetchIfRef(s)}catch(e){warn(`loadFont - lookup failed: "${e}".`)}}if(!(t instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font){warn(`Font "${e}" is not available.`);return errorFont()}warn(`Font "${e}" is not available -- attempting to fallback to a default font.`);t=a||PartialEvaluator.fallbackFontDict}if(t.cacheKey&&this.fontCache.has(t.cacheKey))return this.fontCache.get(t.cacheKey);const{promise:n,resolve:o}=Promise.withResolvers();let g;try{g=this.preEvaluateFont(t);g.cssFontInfo=r}catch(e){warn(`loadFont - preEvaluateFont failed: "${e}".`);return errorFont()}const{descriptor:c,hash:l}=g,h=s instanceof Ref;let C;if(l&&c instanceof Dict){const e=c.fontAliases||=Object.create(null);if(e[l]){const t=e[l].aliasRef;if(h&&t&&this.fontCache.has(t)){this.fontCache.putAlias(s,t);return this.fontCache.get(s)}}else e[l]={fontID:this.idFactory.createFontId()};h&&(e[l].aliasRef=s);C=e[l].fontID}else C=this.idFactory.createFontId();assert(C?.startsWith("f"),'The "fontID" must be (correctly) defined.');if(h)this.fontCache.put(s,n);else{t.cacheKey=`cacheKey_${C}`;this.fontCache.put(t.cacheKey,n)}t.loadedName=`${this.idFactory.getDocId()}_${C}`;this.translateFont(g).then((e=>{o(new TranslatedFont({loadedName:t.loadedName,font:e,dict:t,evaluatorOptions:this.options}))})).catch((e=>{warn(`loadFont - translateFont failed: "${e}".`);o(new TranslatedFont({loadedName:t.loadedName,font:new ErrorFont(e instanceof Error?e.message:e),dict:t,evaluatorOptions:this.options}))}));return n}buildPath(e,t,i,a=!1){const r=e.length-1;i||(i=[]);if(r<0||e.fnArray[r]!==rt){if(a){warn(`Encountered path operator "${t}" inside of a text object.`);e.addOp(xA,null)}let r;switch(t){case OA:const e=i[0]+i[2],t=i[1]+i[3];r=[Math.min(i[0],e),Math.min(i[1],t),Math.max(i[0],e),Math.max(i[1],t)];break;case JA:case vA:r=[i[0],i[1],i[0],i[1]];break;default:r=[1/0,1/0,-1/0,-1/0]}e.addOp(rt,[[t],i,r]);a&&e.addOp(LA,null)}else{const a=e.argsArray[r];a[0].push(t);a[1].push(...i);const s=a[2];switch(t){case OA:const e=i[0]+i[2],t=i[1]+i[3];s[0]=Math.min(s[0],i[0],e);s[1]=Math.min(s[1],i[1],t);s[2]=Math.max(s[2],i[0],e);s[3]=Math.max(s[3],i[1],t);break;case JA:case vA:s[0]=Math.min(s[0],i[0]);s[1]=Math.min(s[1],i[1]);s[2]=Math.max(s[2],i[0]);s[3]=Math.max(s[3],i[1])}}}parseColorSpace({cs:e,resources:t,localColorSpaceCache:i}){return ColorSpace.parseAsync({cs:e,xref:this.xref,resources:t,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:i}).catch((e=>{if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseColorSpace - ignoring ColorSpace: "${e}".`);return null}throw e}))}parseShading({shading:e,resources:t,localColorSpaceCache:i,localShadingPatternCache:a}){let r,s=a.get(e);if(s)return s;try{r=Pattern.parseShading(e,this.xref,t,this._pdfFunctionFactory,i).getIR()}catch(t){if(t instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseShading - ignoring shading: "${t}".`);a.set(e,null);return null}throw t}s=`pattern_${this.idFactory.createObjId()}`;this.parsingType3Font&&(s=`${this.idFactory.getDocId()}_type3_${s}`);a.set(e,s);this.parsingType3Font?this.handler.send("commonobj",[s,"Pattern",r]):this.handler.send("obj",[s,this.pageIndex,"Pattern",r]);return s}handleColorN(e,t,i,a,r,s,n,o,g,c){const l=i.pop();if(l instanceof Name){const h=r.getRaw(l.name),C=h instanceof Ref&&g.getByRef(h);if(C)try{const r=a.base?a.base.getRgb(i,0):null,s=getTilingPatternIR(C.operatorListIR,C.dict,r);e.addOp(t,s);return}catch{}const Q=this.xref.fetchIfRef(h);if(Q){const r=Q instanceof BaseStream?Q.dict:Q,l=r.get("PatternType");if(l===yr){const o=a.base?a.base.getRgb(i,0):null;return this.handleTilingType(t,o,s,Q,r,e,n,g)}if(l===wr){const i=r.get("Shading"),a=this.parseShading({shading:i,resources:s,localColorSpaceCache:o,localShadingPatternCache:c});if(a){const i=lookupMatrix(r.getArray("Matrix"),null);e.addOp(t,["Shading",a,i])}return}throw new FormatError(`Unknown PatternType: ${l}`)}}throw new FormatError(`Unknown PatternName: ${l}`)}_parseVisibilityExpression(e,t,i){if(++t>10){warn("Visibility expression is too deeply nested");return}const a=e.length,r=this.xref.fetchIfRef(e[0]);if(!(a<2)&&r instanceof Name){switch(r.name){case"And":case"Or":case"Not":i.push(r.name);break;default:warn(`Invalid operator ${r.name} in visibility expression`);return}for(let r=1;r0)return{type:"OCMD",expression:t}}const t=i.get("OCGs");if(Array.isArray(t)||t instanceof Dict){const e=[];if(Array.isArray(t))for(const i of t)e.push(i.toString());else e.push(t.objId);return{type:a,ids:e,policy:i.get("P")instanceof Name?i.get("P").name:null,expression:null}}if(t instanceof Ref)return{type:a,id:t.toString()}}return null}getOperatorList({stream:e,task:t,resources:i,operatorList:a,initialState:r=null,fallbackFontDict:s=null}){i||=Dict.empty;r||=new EvalState;if(!a)throw new Error('getOperatorList: missing "operatorList" parameter');const n=this,o=this.xref;let g=!1;const c=new LocalImageCache,l=new LocalColorSpaceCache,h=new LocalGStateCache,C=new LocalTilingPatternCache,Q=new Map,E=i.get("XObject")||Dict.empty,u=i.get("Pattern")||Dict.empty,d=new StateManager(r),f=new EvaluatorPreprocessor(e,o,d),p=new TimeSlotManager;function closePendingRestoreOPS(e){for(let e=0,t=f.savedStatesDepth;e0&&a.addOp(UA,[t]);e=null;continue}}next(new Promise((function(e,r){if(!k)throw new FormatError("GState must be referred to by name.");const s=i.get("ExtGState");if(!(s instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const o=s.get(S);if(!(o instanceof Dict))throw new FormatError("GState should be a dictionary.");n.setGState({resources:i,gState:o,operatorList:a,cacheKey:S,task:t,stateManager:d,localGStateCache:h,localColorSpaceCache:l}).then(e,r)})).catch((function(e){if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring ExtGState: "${e}".`)}})));return;case JA:case vA:case YA:case KA:case TA:case qA:case OA:n.buildPath(a,r,e,g);continue;case Je:case ve:case qe:case Oe:continue;case Ke:if(!(e[0]instanceof Name)){warn(`Expected name for beginMarkedContentProps arg0=${e[0]}`);a.addOp(Ke,["OC",null]);continue}if("OC"===e[0].name){next(n.parseMarkedContentProps(e[1],i).then((e=>{a.addOp(Ke,["OC",e])})).catch((e=>{if(!(e instanceof AbortException)){if(!n.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring beginMarkedContentProps: "${e}".`);a.addOp(Ke,["OC",null])}})));return}e=[e[0].name,e[1]instanceof Dict?e[1].get("MCID"):null];break;default:if(null!==e){for(w=0,b=e.length;w{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring errors during "${t.name}" task: "${e}".`);closePendingRestoreOPS()}}))}getTextContent({stream:e,task:t,resources:i,stateManager:s=null,includeMarkedContent:n=!1,sink:o,seenStyles:g=new Set,viewBox:c,lang:l=null,markedContentData:h=null,disableNormalization:C=!1,keepWhiteSpace:Q=!1}){i||=Dict.empty;s||=new StateManager(new TextState);n&&(h||={level:0});const E={items:[],styles:Object.create(null),lang:l},u={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},d=[" "," "];let f=0;function saveLastChar(e){const t=(f+1)%2,i=" "!==d[f]&&" "===d[t];d[f]=e;f=t;return!Q&&i}function shouldAddWhitepsace(){return!Q&&" "!==d[f]&&" "===d[(f+1)%2]}function resetLastChars(){d[0]=d[1]=" ";f=0}const p=this,m=this.xref,y=[];let w=null;const b=new LocalImageCache,D=new LocalGStateCache,S=new EvaluatorPreprocessor(e,m,s);let k;function pushWhitespace({width:e=0,height:t=0,transform:i=u.prevTransform,fontName:a=u.fontName}){E.items.push({str:" ",dir:"ltr",width:e,height:t,transform:i,fontName:a,hasEOL:!1})}function getCurrentTextTransform(){const e=k.font,t=[k.fontSize*k.textHScale,0,0,k.fontSize,0,k.textRise];if(e.isType3Font&&(k.fontSize<=1||e.isCharBBox)&&!isArrayEqual(k.fontMatrix,r)){const i=e.bbox[3]-e.bbox[1];i>0&&(t[3]*=i*k.fontMatrix[3])}return Util.transform(k.ctm,Util.transform(k.textMatrix,t))}function ensureTextContentItem(){if(u.initialized)return u;const{font:e,loadedName:t}=k;if(!g.has(t)){g.add(t);E.styles[t]={fontFamily:e.fallbackName,ascent:e.ascent,descent:e.descent,vertical:e.vertical};if(p.options.fontExtraProperties&&e.systemFontInfo){const i=E.styles[t];i.fontSubstitution=e.systemFontInfo.css;i.fontSubstitutionLoadedName=e.systemFontInfo.loadedName}}u.fontName=t;const i=u.transform=getCurrentTextTransform();if(e.vertical){u.width=u.totalWidth=Math.hypot(i[0],i[1]);u.height=u.totalHeight=0;u.vertical=!0}else{u.width=u.totalWidth=0;u.height=u.totalHeight=Math.hypot(i[2],i[3]);u.vertical=!1}const a=Math.hypot(k.textLineMatrix[0],k.textLineMatrix[1]),r=Math.hypot(k.ctm[0],k.ctm[1]);u.textAdvanceScale=r*a;const{fontSize:s}=k;u.trackingSpaceMin=.102*s;u.notASpace=.03*s;u.negativeSpaceMax=-.2*s;u.spaceInFlowMin=.102*s;u.spaceInFlowMax=.6*s;u.hasEOL=!1;u.initialized=!0;return u}function updateAdvanceScale(){if(!u.initialized)return;const e=Math.hypot(k.textLineMatrix[0],k.textLineMatrix[1]),t=Math.hypot(k.ctm[0],k.ctm[1])*e;if(t!==u.textAdvanceScale){if(u.vertical){u.totalHeight+=u.height*u.textAdvanceScale;u.height=0}else{u.totalWidth+=u.width*u.textAdvanceScale;u.width=0}u.textAdvanceScale=t}}function runBidiTransform(e){let t=e.str.join("");C||(t=function normalizeUnicode(e){if(!Ct){Ct=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;Bt=new Map([["ſt","ſt"]])}return e.replaceAll(Ct,((e,t,i)=>t?t.normalize("NFKC"):Bt.get(i)))}(t));const i=bidi(t,-1,e.vertical);return{str:i.str,dir:i.dir,width:Math.abs(e.totalWidth),height:Math.abs(e.totalHeight),transform:e.transform,fontName:e.fontName,hasEOL:e.hasEOL}}async function handleSetFont(e,a){const s=await p.loadFont(e,a,i);if(s.font.isType3Font)try{await s.loadType3Data(p,i,t)}catch{}k.loadedName=s.loadedName;k.font=s.font;k.fontMatrix=s.font.fontMatrix||r}function applyInverseRotation(e,t,i){const a=Math.hypot(i[0],i[1]);return[(i[0]*e+i[1]*t)/a,(i[2]*e+i[3]*t)/a]}function compareWithLastPosition(e){const t=getCurrentTextTransform();let i=t[4],a=t[5];if(k.font?.vertical){if(ic[2]||a+ec[3])return!1}else if(i+ec[2]||ac[3])return!1;if(!k.font||!u.prevTransform)return!0;let r=u.prevTransform[4],s=u.prevTransform[5];if(r===i&&s===a)return!0;let n=-1;t[0]&&0===t[1]&&0===t[2]?n=t[0]>0?0:180:t[1]&&0===t[0]&&0===t[3]&&(n=t[1]>0?90:270);switch(n){case 0:break;case 90:[i,a]=[a,i];[r,s]=[s,r];break;case 180:[i,a,r,s]=[-i,-a,-r,-s];break;case 270:[i,a]=[-a,-i];[r,s]=[-s,-r];break;default:[i,a]=applyInverseRotation(i,a,t);[r,s]=applyInverseRotation(r,s,u.prevTransform)}if(k.font.vertical){const e=(s-a)/u.textAdvanceScale,t=i-r,n=Math.sign(u.height);if(e.5*u.width){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(t)>u.width){appendEOL();return!0}e<=n*u.notASpace&&resetLastChars();if(e<=n*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({height:Math.abs(e)})}else u.height+=e;else if(!addFakeSpaces(e,u.prevTransform,n))if(0===u.str.length){resetLastChars();pushWhitespace({height:Math.abs(e)})}else u.height+=e;Math.abs(t)>.25*u.width&&flushTextContentItem();return!0}const o=(i-r)/u.textAdvanceScale,g=a-s,l=Math.sign(u.width);if(o.5*u.height){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(g)>u.height){appendEOL();return!0}o<=l*u.notASpace&&resetLastChars();if(o<=l*u.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({width:Math.abs(o)})}else u.width+=o;else if(!addFakeSpaces(o,u.prevTransform,l))if(0===u.str.length){resetLastChars();pushWhitespace({width:Math.abs(o)})}else u.width+=o;Math.abs(g)>.25*u.height&&flushTextContentItem();return!0}function buildTextContentItem({chars:e,extraSpacing:t}){const i=k.font;if(!e){const e=k.charSpacing+t;e&&(i.vertical?k.translateTextMatrix(0,-e):k.translateTextMatrix(e*k.textHScale,0));Q&&compareWithLastPosition(0);return}const a=i.charsToGlyphs(e),r=k.fontMatrix[0]*k.fontSize;for(let e=0,s=a.length;e0){const e=y.join("");y.length=0;buildTextContentItem({chars:e,extraSpacing:0})}break;case Be:if(!s.state.font){p.ensureStateFont(s.state);continue}buildTextContentItem({chars:G[0],extraSpacing:0});break;case Ee:if(!s.state.font){p.ensureStateFont(s.state);continue}k.carriageReturn();buildTextContentItem({chars:G[0],extraSpacing:0});break;case ue:if(!s.state.font){p.ensureStateFont(s.state);continue}k.wordSpacing=G[0];k.charSpacing=G[1];k.carriageReturn();buildTextContentItem({chars:G[2],extraSpacing:0});break;case He:flushTextContentItem();w??=i.get("XObject")||Dict.empty;N=G[0]instanceof Name;f=G[0].name;if(N&&b.getByName(f))break;next(new Promise((function(e,a){if(!N)throw new FormatError("XObject must be referred to by name.");let r=w.getRaw(f);if(r instanceof Ref){if(b.getByRef(r)){e();return}if(p.globalImageCache.getData(r,p.pageIndex)){e();return}r=m.fetch(r)}if(!(r instanceof BaseStream))throw new FormatError("XObject should be a stream");const E=r.dict.get("Subtype");if(!(E instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==E.name){b.set(f,r.dict.objId,!0);e();return}const u=s.state.clone(),d=new StateManager(u),y=lookupMatrix(r.dict.getArray("Matrix"),null);y&&d.transform(y);enqueueChunk();const D={enqueueInvoked:!1,enqueue(e,t){this.enqueueInvoked=!0;o.enqueue(e,t)},get desiredSize(){return o.desiredSize},get ready(){return o.ready}};p.getTextContent({stream:r,task:t,resources:r.dict.get("Resources")||i,stateManager:d,includeMarkedContent:n,sink:D,seenStyles:g,viewBox:c,lang:l,markedContentData:h,disableNormalization:C,keepWhiteSpace:Q}).then((function(){D.enqueueInvoked||b.set(f,r.dict.objId,!0);e()}),a)})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring XObject: "${e}".`)}})));return;case UA:N=G[0]instanceof Name;f=G[0].name;if(N&&D.getByName(f))break;next(new Promise((function(e,t){if(!N)throw new FormatError("GState must be referred to by name.");const a=i.get("ExtGState");if(!(a instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const r=a.get(f);if(!(r instanceof Dict))throw new FormatError("GState should be a dictionary.");const s=r.get("Font");if(s){flushTextContentItem();k.fontName=null;k.fontSize=s[1];handleSetFont(null,s[0]).then(e,t)}else{D.set(f,r.objId,!0);e()}})).catch((function(e){if(!(e instanceof AbortException)){if(!p.options.ignoreErrors)throw e;warn(`getTextContent - ignoring ExtGState: "${e}".`)}})));return;case Ye:flushTextContentItem();if(n){h.level++;E.items.push({type:"beginMarkedContent",tag:G[0]instanceof Name?G[0].name:null})}break;case Ke:flushTextContentItem();if(n){h.level++;let e=null;G[1]instanceof Dict&&(e=G[1].get("MCID"));E.items.push({type:"beginMarkedContentProps",id:Number.isInteger(e)?`${p.idFactory.getPageObjId()}_mc${e}`:null,tag:G[0]instanceof Name?G[0].name:null})}break;case Te:flushTextContentItem();if(n){if(0===h.level)break;h.level--;E.items.push({type:"endMarkedContent"})}break;case LA:!e||e.font===k.font&&e.fontSize===k.fontSize&&e.fontName===k.fontName||flushTextContentItem()}if(E.items.length>=o.desiredSize){d=!0;break}}if(d)next(br);else{flushTextContentItem();enqueueChunk();e()}})).catch((e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getTextContent - ignoring errors during "${t.name}" task: "${e}".`);flushTextContentItem();enqueueChunk()}}))}async extractDataStructures(e,t){const i=this.xref;let a;const r=this.readToUnicode(t.toUnicode);if(t.composite){const i=e.get("CIDSystemInfo");i instanceof Dict&&(t.cidSystemInfo={registry:stringToPDFString(i.get("Registry")),ordering:stringToPDFString(i.get("Ordering")),supplement:i.get("Supplement")});try{const t=e.get("CIDToGIDMap");t instanceof BaseStream&&(a=t.getBytes())}catch(e){if(!this.options.ignoreErrors)throw e;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${e}".`)}}const s=[];let n,o=null;if(e.has("Encoding")){n=e.get("Encoding");if(n instanceof Dict){o=n.get("BaseEncoding");o=o instanceof Name?o.name:null;if(n.has("Differences")){const e=n.get("Differences");let t=0;for(const a of e){const e=i.fetchIfRef(a);if("number"==typeof e)t=e;else{if(!(e instanceof Name))throw new FormatError(`Invalid entry in 'Differences' array: ${e}`);s[t++]=e.name}}}}else if(n instanceof Name)o=n.name;else{const e="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(e);warn(e)}"MacRomanEncoding"!==o&&"MacExpertEncoding"!==o&&"WinAnsiEncoding"!==o&&(o=null)}const g=!t.file||t.isInternalFont,c=Pi()[t.name];o&&g&&c&&(o=null);if(o)t.defaultEncoding=getEncoding(o);else{const e=!!(t.flags&Hi),i=!!(t.flags&Ji);n=Bi;"TrueType"!==t.type||i||(n=Qi);if(e||c){n=Ci;g&&(/Symbol/i.test(t.name)?n=Ei:/Dingbats/i.test(t.name)?n=ui:/Wingdings/i.test(t.name)&&(n=Qi))}t.defaultEncoding=n}t.differences=s;t.baseEncodingName=o;t.hasEncoding=!!o||s.length>0;t.dict=e;t.toUnicode=await r;const l=await this.buildToUnicode(t);t.toUnicode=l;a&&(t.cidToGidMap=this.readCidToGidMap(a,l));return t}_simpleFontToUnicode(e,t=!1){assert(!e.composite,"Must be a simple font.");const i=[],a=e.defaultEncoding.slice(),r=e.baseEncodingName,s=e.differences;for(const e in s){const t=s[e];".notdef"!==t&&(a[e]=t)}const n=Di();for(const s in a){let o=a[s];if(""===o)continue;let g=n[o];if(void 0!==g){i[s]=String.fromCharCode(g);continue}let c=0;switch(o[0]){case"G":3===o.length&&(c=parseInt(o.substring(1),16));break;case"g":5===o.length&&(c=parseInt(o.substring(1),16));break;case"C":case"c":if(o.length>=3&&o.length<=4){const i=o.substring(1);if(t){c=parseInt(i,16);break}c=+i;if(Number.isNaN(c)&&Number.isInteger(parseInt(i,16)))return this._simpleFontToUnicode(e,!0)}break;case"u":g=getUnicodeForGlyph(o,n);-1!==g&&(c=g);break;default:switch(o){case"f_h":case"f_t":case"T_h":i[s]=o.replaceAll("_","");continue}}if(c>0&&c<=1114111&&Number.isInteger(c)){if(r&&c===+s){const e=getEncoding(r);if(e&&(o=e[s])){i[s]=String.fromCharCode(n[o]);continue}}i[s]=String.fromCodePoint(c)}}return i}async buildToUnicode(e){e.hasIncludedToUnicodeMap=e.toUnicode?.length>0;if(e.hasIncludedToUnicodeMap){!e.composite&&e.hasEncoding&&(e.fallbackToUnicode=this._simpleFontToUnicode(e));return e.toUnicode}if(!e.composite)return new ToUnicodeMap(this._simpleFontToUnicode(e));if(e.composite&&(e.cMap.builtInCMap&&!(e.cMap instanceof IdentityCMap)||"Adobe"===e.cidSystemInfo?.registry&&("GB1"===e.cidSystemInfo.ordering||"CNS1"===e.cidSystemInfo.ordering||"Japan1"===e.cidSystemInfo.ordering||"Korea1"===e.cidSystemInfo.ordering))){const{registry:t,ordering:i}=e.cidSystemInfo,a=Name.get(`${t}-${i}-UCS2`),r=await CMapFactory.create({encoding:a,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),s=[],n=[];e.cMap.forEach((function(e,t){if(t>65535)throw new FormatError("Max size of CID is 65,535");const i=r.lookup(t);if(i){n.length=0;for(let e=0,t=i.length;e>1;(0!==r||t.has(s))&&(i[s]=r)}return i}extractWidths(e,t,i){const a=this.xref;let r=[],s=0;const n=[];let o;if(i.composite){const t=e.get("DW");s="number"==typeof t?Math.ceil(t):1e3;const g=e.get("W");if(Array.isArray(g))for(let e=0,t=g.length;e{const t=g.get(e),r=new OperatorList;return a.getOperatorList({stream:t,task:i,resources:c,operatorList:r}).then((()=>{r.fnArray[0]===fe&&this._removeType3ColorOperators(r,E);l[e]=r.getIR();for(const e of r.dependencies)n.add(e)})).catch((function(t){warn(`Type3 font resource "${e}" is not available.`);const i=new OperatorList;l[e]=i.getIR()}))}));this.type3Loaded=o.then((()=>{s.charProcOperatorList=l;if(this._bbox){s.isCharBBox=!0;s.bbox=this._bbox}}));return this.type3Loaded}_removeType3ColorOperators(e,t=NaN){const i=Util.normalizeRect(e.argsArray[0].slice(2)),a=i[2]-i[0],r=i[3]-i[1],s=Math.hypot(a,r);if(0===a||0===r){e.fnArray.splice(0,1);e.argsArray.splice(0,1)}else if(0===t||Math.round(s/t)>=10){this._bbox||(this._bbox=[1/0,1/0,-1/0,-1/0]);this._bbox[0]=Math.min(this._bbox[0],i[0]);this._bbox[1]=Math.min(this._bbox[1],i[1]);this._bbox[2]=Math.max(this._bbox[2],i[2]);this._bbox[3]=Math.max(this._bbox[3],i[3])}let n=0,o=e.length;for(;n=JA&&s<=$A;if(r.variableArgs)o>n&&info(`Command ${a}: expected [0, ${n}] args, but received ${o} args.`);else{if(o!==n){const e=this.nonProcessedArgs;for(;o>n;){e.push(t.shift());o--}for(;oEvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError(`Invalid ${e}`);warn(`Skipping ${e}`);null!==t&&(t.length=0);continue}}this.preprocessCommand(s,t);e.fn=s;e.args=t;return!0}if(i===Et)return!1;if(null!==i){null===t&&(t=[]);t.push(i);if(t.length>33)throw new FormatError("Too many arguments")}}}preprocessCommand(e,t){switch(0|e){case xA:this.stateManager.save();break;case LA:this.stateManager.restore();break;case HA:this.stateManager.transform(t)}}}class DefaultAppearanceEvaluator extends EvaluatorPreprocessor{constructor(e){super(new StringStream(e))}parse(){const e={fn:0,args:[]},t={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;;){e.args.length=0;if(!this.read(e))break;if(0!==this.savedStatesDepth)continue;const{fn:i,args:a}=e;switch(0|i){case oe:const[e,i]=a;e instanceof Name&&(t.fontName=e.name);"number"==typeof i&&i>0&&(t.fontSize=i);break;case Re:ColorSpace.singletons.rgb.getRgbItem(a,0,t.fontColor,0);break;case Se:ColorSpace.singletons.gray.getRgbItem(a,0,t.fontColor,0);break;case Ge:ColorSpace.singletons.cmyk.getRgbItem(a,0,t.fontColor,0)}}}catch(e){warn(`parseDefaultAppearance - ignoring errors: "${e}".`)}return t}}function parseDefaultAppearance(e){return new DefaultAppearanceEvaluator(e).parse()}class AppearanceStreamEvaluator extends EvaluatorPreprocessor{constructor(e,t,i){super(e);this.stream=e;this.evaluatorOptions=t;this.xref=i;this.resources=e.dict?.get("Resources")}parse(){const e={fn:0,args:[]};let t={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ColorSpace.singletons.gray},i=!1;const a=[];try{for(;;){e.args.length=0;if(i||!this.read(e))break;const{fn:r,args:s}=e;switch(0|r){case xA:a.push({scaleFactor:t.scaleFactor,fontSize:t.fontSize,fontName:t.fontName,fontColor:t.fontColor.slice(),fillColorSpace:t.fillColorSpace});break;case LA:t=a.pop()||t;break;case he:t.scaleFactor*=Math.hypot(s[0],s[1]);break;case oe:const[e,r]=s;e instanceof Name&&(t.fontName=e.name);"number"==typeof r&&r>0&&(t.fontSize=r*t.scaleFactor);break;case me:t.fillColorSpace=ColorSpace.parse({cs:s[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:this._localColorSpaceCache});break;case be:t.fillColorSpace.getRgbItem(s,0,t.fontColor,0);break;case Re:ColorSpace.singletons.rgb.getRgbItem(s,0,t.fontColor,0);break;case Se:ColorSpace.singletons.gray.getRgbItem(s,0,t.fontColor,0);break;case Ge:ColorSpace.singletons.cmyk.getRgbItem(s,0,t.fontColor,0);break;case Be:case Qe:case Ee:case ue:i=!0}}}catch(e){warn(`parseAppearanceStream - ignoring errors: "${e}".`)}this.stream.reset();delete t.scaleFactor;delete t.fillColorSpace;return t}get _localColorSpaceCache(){return shadow(this,"_localColorSpaceCache",new LocalColorSpaceCache)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function getPdfColor(e,t){if(e[0]===e[1]&&e[1]===e[2]){return`${numberToString(e[0]/255)} ${t?"g":"G"}`}return Array.from(e,(e=>numberToString(e/255))).join(" ")+" "+(t?"rg":"RG")}class FakeUnicodeFont{constructor(e,t){this.xref=e;this.widths=null;this.firstChar=1/0;this.lastChar=-1/0;this.fontFamily=t;const i=new OffscreenCanvas(1,1);this.ctxMeasure=i.getContext("2d",{willReadFrequently:!0});FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1);this.fontName=Name.get(`InvalidPDFjsFont_${t}_${FakeUnicodeFont._fontNameId++}`)}get fontDescriptorRef(){if(!FakeUnicodeFont._fontDescriptorRef){const e=new Dict(this.xref);e.set("Type",Name.get("FontDescriptor"));e.set("FontName",this.fontName);e.set("FontFamily","MyriadPro Regular");e.set("FontBBox",[0,0,0,0]);e.set("FontStretch",Name.get("Normal"));e.set("FontWeight",400);e.set("ItalicAngle",0);FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(e)}return FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("CIDFontType0"));e.set("CIDToGIDMap",Name.get("Identity"));e.set("FirstChar",this.firstChar);e.set("LastChar",this.lastChar);e.set("FontDescriptor",this.fontDescriptorRef);e.set("DW",1e3);const t=[],i=[...this.widths.entries()].sort();let a=null,r=null;for(const[e,s]of i)if(a)if(e===a+r.length)r.push(s);else{t.push(a,r);a=e;r=[s]}else{a=e;r=[s]}a&&t.push(a,r);e.set("W",t);const s=new Dict(this.xref);s.set("Ordering","Identity");s.set("Registry","Adobe");s.set("Supplement",0);e.set("CIDSystemInfo",s);return this.xref.getNewPersistentRef(e)}get baseFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type0"));e.set("Encoding",Name.get("Identity-H"));e.set("DescendantFonts",[this.descendantFontRef]);e.set("ToUnicode",Name.get("Identity-H"));return this.xref.getNewPersistentRef(e)}get resources(){const e=new Dict(this.xref),t=new Dict(this.xref);t.set(this.fontName.name,this.baseFontRef);e.set("Font",t);return e}_createContext(){this.widths=new Map;this.ctxMeasure.font=`1000px ${this.fontFamily}`;return this.ctxMeasure}createFontResources(e){const t=this._createContext();for(const i of e.split(/\r\n?|\n/))for(const e of i.split("")){const i=e.charCodeAt(0);if(this.widths.has(i))continue;const a=t.measureText(e),r=Math.ceil(a.width);this.widths.set(i,r);this.firstChar=Math.min(i,this.firstChar);this.lastChar=Math.max(i,this.lastChar)}return this.resources}static getFirstPositionInfo(e,t,i){const[a,r,o,g]=e;let c=o-a,l=g-r;t%180!=0&&([c,l]=[l,c]);const h=s*i;return{coords:[0,l+n*i-h],bbox:[0,0,c,l],matrix:0!==t?getRotationMatrix(t,l,h):void 0}}createAppearance(e,t,i,a,r,o){const g=this._createContext(),c=[];let l=-1/0;for(const t of e.split(/\r\n?|\n/)){c.push(t);const e=g.measureText(t).width;l=Math.max(l,e);for(const e of codePointIter(t)){const t=String.fromCodePoint(e);let i=this.widths.get(e);if(void 0===i){const a=g.measureText(t);i=Math.ceil(a.width);this.widths.set(e,i);this.firstChar=Math.min(e,this.firstChar);this.lastChar=Math.max(e,this.lastChar)}}}l*=a/1e3;const[h,C,Q,E]=t;let u=Q-h,d=E-C;i%180!=0&&([u,d]=[d,u]);let f=1;l>u&&(f=u/l);let p=1;const m=s*a,y=n*a,w=m*c.length;w>d&&(p=d/w);const b=a*Math.min(f,p),D=["q",`0 0 ${numberToString(u)} ${numberToString(d)} re W n`,"BT",`1 0 0 1 0 ${numberToString(d+y)} Tm 0 Tc ${getPdfColor(r,!0)}`,`/${this.fontName.name} ${numberToString(b)} Tf`],{resources:S}=this;if(1!==(o="number"==typeof o&&o>=0&&o<=1?o:1)){D.push("/R0 gs");const e=new Dict(this.xref),t=new Dict(this.xref);t.set("ca",o);t.set("CA",o);t.set("Type",Name.get("ExtGState"));e.set("R0",t);S.set("ExtGState",e)}const k=numberToString(m);for(const e of c)D.push(`0 -${k} Td <${stringToUTF16HexString(e)}> Tj`);D.push("ET","Q");const R=D.join("\n"),N=new Dict(this.xref);N.set("Subtype",Name.get("Form"));N.set("Type",Name.get("XObject"));N.set("BBox",[0,0,u,d]);N.set("Length",R.length);N.set("Resources",S);if(i){const e=getRotationMatrix(i,u,d);N.set("Matrix",e)}const G=new StringStream(R);G.dict=N;return G}}class NameOrNumberTree{constructor(e,t,i){this.root=e;this.xref=t;this._type=i}getAll(){const e=new Map;if(!this.root)return e;const t=this.xref,i=new RefSet;i.put(this.root);const a=[this.root];for(;a.length>0;){const r=t.fetchIfRef(a.shift());if(!(r instanceof Dict))continue;if(r.has("Kids")){const e=r.get("Kids");if(!Array.isArray(e))continue;for(const t of e){if(i.has(t))throw new FormatError(`Duplicate entry in "${this._type}" tree.`);a.push(t);i.put(t)}continue}const s=r.get(this._type);if(Array.isArray(s))for(let i=0,a=s.length;i10){warn(`Search depth limit reached for "${this._type}" tree.`);return null}const r=i.get("Kids");if(!Array.isArray(r))return null;let s=0,n=r.length-1;for(;s<=n;){const a=s+n>>1,o=t.fetchIfRef(r[a]),g=o.get("Limits");if(et.fetchIfRef(g[1]))){i=o;break}s=a+1}}if(s>n)return null}const r=i.get(this._type);if(Array.isArray(r)){let i=0,a=r.length-2;for(;i<=a;){const s=i+a>>1,n=s+(1&s),o=t.fetchIfRef(r[n]);if(eo))return r[n+1];i=n+2}}}return null}get(e){return this.xref.fetchIfRef(this.getRaw(e))}}class NameTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Names")}}class NumberTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Nums")}}function clearGlobalCaches(){!function clearPatternCaches(){ua=Object.create(null)}();!function clearPrimitiveCaches(){ut=Object.create(null);dt=Object.create(null);ft=Object.create(null)}();!function clearUnicodeCaches(){Ni.clear()}();JpxImage.cleanup()}function pickPlatformItem(e){return e instanceof Dict?e.has("UF")?e.get("UF"):e.has("F")?e.get("F"):e.has("Unix")?e.get("Unix"):e.has("Mac")?e.get("Mac"):e.has("DOS")?e.get("DOS"):null:null}class FileSpec{#U=!1;constructor(e,t,i=!1){if(e instanceof Dict){this.xref=t;this.root=e;e.has("FS")&&(this.fs=e.get("FS"));e.has("RF")&&warn("Related file specifications are not supported");i||(e.has("EF")?this.#U=!0:warn("Non-embedded file specifications are not supported"))}}get filename(){let e="";const t=pickPlatformItem(this.root);t&&"string"==typeof t&&(e=stringToPDFString(t).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/"));return shadow(this,"filename",e||"unnamed")}get content(){if(!this.#U)return null;this._contentRef||=pickPlatformItem(this.root?.get("EF"));let e=null;if(this._contentRef){const t=this.xref.fetchIfRef(this._contentRef);t instanceof BaseStream?e=t.getBytes():warn("Embedded file specification points to non-existing/invalid content")}else warn("Embedded file specification does not have any content");return e}get description(){let e="";const t=this.root?.get("Desc");t&&"string"==typeof t&&(e=stringToPDFString(t));return shadow(this,"description",e)}get serializable(){return{rawFilename:this.filename,filename:(e=this.filename,e.substring(e.lastIndexOf("/")+1)),content:this.content,description:this.description};var e}}const Dr=0,Fr=-2,Sr=-3,kr=-4,Rr=-5,Nr=-6,Gr=-9;function isWhitespace(e,t){const i=e[t];return" "===i||"\n"===i||"\r"===i||"\t"===i}class XMLParserBase{_resolveEntities(e){return e.replaceAll(/&([^;]+);/g,((e,t)=>{if("#x"===t.substring(0,2))return String.fromCodePoint(parseInt(t.substring(2),16));if("#"===t.substring(0,1))return String.fromCodePoint(parseInt(t.substring(1),10));switch(t){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(t)}))}_parseContent(e,t){const i=[];let a=t;function skipWs(){for(;a"!==e[a]&&"/"!==e[a];)++a;const r=e.substring(t,a);skipWs();for(;a"!==e[a]&&"/"!==e[a]&&"?"!==e[a];){skipWs();let t="",r="";for(;a"!==e[i]&&"?"!==e[i]&&"/"!==e[i];)++i;const a=e.substring(t,i);!function skipWs(){for(;i"!==e[i+1]);)++i;return{name:a,value:e.substring(r,i),parsed:i-t}}parseXml(e){let t=0;for(;t",i);if(t<0){this.onError(Gr);return}this.onEndElement(e.substring(i,t));i=t+1;break;case"?":++i;const a=this._parseProcessingInstruction(e,i);if("?>"!==e.substring(i+a.parsed,i+a.parsed+2)){this.onError(Sr);return}this.onPi(a.name,a.value);i+=a.parsed+2;break;case"!":if("--"===e.substring(i+1,i+3)){t=e.indexOf("--\x3e",i+3);if(t<0){this.onError(Rr);return}this.onComment(e.substring(i+3,t));i=t+3}else if("[CDATA["===e.substring(i+1,i+8)){t=e.indexOf("]]>",i+8);if(t<0){this.onError(Fr);return}this.onCdata(e.substring(i+8,t));i=t+3}else{if("DOCTYPE"!==e.substring(i+1,i+8)){this.onError(Nr);return}{const a=e.indexOf("[",i+8);let r=!1;t=e.indexOf(">",i+8);if(t<0){this.onError(kr);return}if(a>0&&t>a){t=e.indexOf("]>",i+8);if(t<0){this.onError(kr);return}r=!0}const s=e.substring(i+8,t+(r?1:0));this.onDoctype(s);i=t+(r?2:1)}}break;default:const r=this._parseContent(e,i);if(null===r){this.onError(Nr);return}let s=!1;if("/>"===e.substring(i+r.parsed,i+r.parsed+2))s=!0;else if(">"!==e.substring(i+r.parsed,i+r.parsed+1)){this.onError(Gr);return}this.onBeginElement(r.name,r.attributes,s);i+=r.parsed+(s?2:1)}}else{for(;i0}searchNode(e,t){if(t>=e.length)return this;const i=e[t];if(i.name.startsWith("#")&&t0){a.push([r,0]);r=r.childNodes[0]}else{if(0===a.length)return null;for(;0!==a.length;){const[e,t]=a.pop(),i=t+1;if(i");for(const t of this.childNodes)t.dump(e);e.push(``)}else this.nodeValue?e.push(`>${encodeToXmlString(this.nodeValue)}`):e.push("/>")}else e.push(encodeToXmlString(this.nodeValue))}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes:e=!1,lowerCaseName:t=!1}){super();this._currentFragment=null;this._stack=null;this._errorCode=Dr;this._hasAttributes=e;this._lowerCaseName=t}parseFromString(e){this._currentFragment=[];this._stack=[];this._errorCode=Dr;this.parseXml(e);if(this._errorCode!==Dr)return;const[t]=this._currentFragment;return t?{documentElement:t}:void 0}onText(e){if(function isWhitespaceString(e){for(let t=0,i=e.length;t\\376\\377([^<]+)/g,(function(e,t){const i=t.replaceAll(/\\([0-3])([0-7])([0-7])/g,(function(e,t,i,a){return String.fromCharCode(64*t+8*i+1*a)})).replaceAll(/&(amp|apos|gt|lt|quot);/g,(function(e,t){switch(t){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${t} isn't defined.`)})),a=[">"];for(let e=0,t=i.length;e=32&&t<127&&60!==t&&62!==t&&38!==t?a.push(String.fromCharCode(t)):a.push("&#x"+(65536+t).toString(16).substring(1)+";")}return a.join("")}))}_getSequence(e){const t=e.nodeName;return"rdf:bag"!==t&&"rdf:seq"!==t&&"rdf:alt"!==t?null:e.childNodes.filter((e=>"rdf:li"===e.nodeName))}_parseArray(e){if(!e.hasChildNodes())return;const[t]=e.childNodes,i=this._getSequence(t)||[];this._metadataMap.set(e.nodeName,i.map((e=>e.textContent.trim())))}_parse(e){let t=e.documentElement;if("rdf:rdf"!==t.nodeName){t=t.firstChild;for(;t&&"rdf:rdf"!==t.nodeName;)t=t.nextSibling}if(t&&"rdf:rdf"===t.nodeName&&t.hasChildNodes())for(const e of t.childNodes)if("rdf:description"===e.nodeName)for(const t of e.childNodes){const e=t.nodeName;switch(e){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(t);continue}this._metadataMap.set(e,t.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}const Mr=1,Ur=2,xr=3,Lr=4,Hr=5;class StructTreeRoot{constructor(e,t){this.dict=e;this.ref=t instanceof Ref?t:null;this.roleMap=new Map;this.structParentIds=null}init(){this.readRoleMap()}#x(e,t,i){if(!(e instanceof Ref)||t<0)return;this.structParentIds||=new RefSetCache;let a=this.structParentIds.get(e);if(!a){a=[];this.structParentIds.put(e,a)}a.push([t,i])}addAnnotationIdToPage(e,t){this.#x(e,t,Lr)}readRoleMap(){const e=this.dict.get("RoleMap");if(e instanceof Dict)for(const[t,i]of e)i instanceof Name&&this.roleMap.set(t,i.name)}static async canCreateStructureTree({catalogRef:e,pdfManager:t,newAnnotationsByPage:i}){if(!(e instanceof Ref)){warn("Cannot save the struct tree: no catalog reference.");return!1}let a=0,r=!0;for(const[e,s]of i){const{ref:i}=await t.getPage(e);if(!(i instanceof Ref)){warn(`Cannot save the struct tree: page ${e} has no ref.`);r=!0;break}for(const e of s)if(e.accessibilityData?.type){e.parentTreeId=a++;r=!1}}if(r){for(const e of i.values())for(const t of e)delete t.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage:e,xref:t,catalogRef:i,pdfManager:a,changes:r}){const s=a.catalog.cloneDict(),n=new RefSetCache;n.put(i,s);const o=t.getNewTemporaryRef();s.set("StructTreeRoot",o);const g=new Dict(t);g.set("Type",Name.get("StructTreeRoot"));const c=t.getNewTemporaryRef();g.set("ParentTree",c);const l=[];g.set("K",l);n.put(o,g);const h=new Dict(t),C=[];h.set("Nums",C);const Q=await this.#L({newAnnotationsByPage:e,structTreeRootRef:o,structTreeRoot:null,kids:l,nums:C,xref:t,pdfManager:a,changes:r,cache:n});g.set("ParentTreeNextKey",Q);n.put(c,h);for(const[e,t]of n.items())r.put(e,{data:t})}async canUpdateStructTree({pdfManager:e,xref:t,newAnnotationsByPage:i}){if(!this.ref){warn("Cannot update the struct tree: no root reference.");return!1}let a=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(a)||a<0){warn("Cannot update the struct tree: invalid next key.");return!1}const r=this.dict.get("ParentTree");if(!(r instanceof Dict)){warn("Cannot update the struct tree: ParentTree isn't a dict.");return!1}const s=r.get("Nums");if(!Array.isArray(s)){warn("Cannot update the struct tree: nums isn't an array.");return!1}const n=new NumberTree(r,t);for(const t of i.keys()){const{pageDict:i}=await e.getPage(t);if(!i.has("StructParents"))continue;const a=i.get("StructParents");if(!Number.isInteger(a)||!Array.isArray(n.get(a))){warn(`Cannot save the struct tree: page ${t} has a wrong id.`);return!1}}let o=!0;for(const[t,r]of i){const{pageDict:i}=await e.getPage(t);StructTreeRoot.#H({elements:r,xref:this.dict.xref,pageDict:i,numberTree:n});for(const e of r)if(e.accessibilityData?.type){e.accessibilityData.structParent>=0||(e.parentTreeId=a++);o=!1}}if(o){for(const e of i.values())for(const t of e){delete t.parentTreeId;delete t.structTreeParent}return!1}return!0}async updateStructureTree({newAnnotationsByPage:e,pdfManager:t,changes:i}){const a=this.dict.xref,r=this.dict.clone(),s=this.ref,n=new RefSetCache;n.put(s,r);let o,g=r.getRaw("ParentTree");if(g instanceof Ref)o=a.fetch(g);else{o=g;g=a.getNewTemporaryRef();r.set("ParentTree",g)}o=o.clone();n.put(g,o);let c=o.getRaw("Nums"),l=null;if(c instanceof Ref){l=c;c=a.fetch(l)}c=c.slice();l||o.set("Nums",c);const h=await StructTreeRoot.#L({newAnnotationsByPage:e,structTreeRootRef:s,structTreeRoot:this,kids:null,nums:c,xref:a,pdfManager:t,changes:i,cache:n});if(-1!==h){r.set("ParentTreeNextKey",h);l&&n.put(l,c);for(const[e,t]of n.items())i.put(e,{data:t})}}static async#L({newAnnotationsByPage:e,structTreeRootRef:t,structTreeRoot:i,kids:a,nums:r,xref:s,pdfManager:n,changes:o,cache:g}){const c=Name.get("OBJR");let l,h=-1;for(const[C,Q]of e){const e=await n.getPage(C),{ref:E}=e,u=E instanceof Ref;for(const{accessibilityData:n,ref:d,parentTreeId:f,structTreeParent:p}of Q){if(!n?.type)continue;const{structParent:Q}=n;if(i&&Number.isInteger(Q)&&Q>=0){let t=(l||=new Map).get(C);if(void 0===t){t=new StructTreePage(i,e.pageDict).collectObjects(E);l.set(C,t)}const a=t?.get(Q);if(a){const e=s.fetch(a).clone();StructTreeRoot.#J(e,n);o.put(a,{data:e});continue}}h=Math.max(h,f);const m=s.getNewTemporaryRef(),y=new Dict(s);StructTreeRoot.#J(y,n);await this.#v({structTreeParent:p,tagDict:y,newTagRef:m,structTreeRootRef:t,fallbackKids:a,xref:s,cache:g});const w=new Dict(s);y.set("K",w);w.set("Type",c);u&&w.set("Pg",E);w.set("Obj",d);g.put(m,y);r.push(f,m)}}return h+1}static#J(e,{type:t,title:i,lang:a,alt:r,expanded:s,actualText:n}){e.set("S",Name.get(t));i&&e.set("T",stringToAsciiOrUTF16BE(i));a&&e.set("Lang",stringToAsciiOrUTF16BE(a));r&&e.set("Alt",stringToAsciiOrUTF16BE(r));s&&e.set("E",stringToAsciiOrUTF16BE(s));n&&e.set("ActualText",stringToAsciiOrUTF16BE(n))}static#H({elements:e,xref:t,pageDict:i,numberTree:a}){const r=new Map;for(const t of e)if(t.structTreeParentId){const e=parseInt(t.structTreeParentId.split("_mc")[1],10);let i=r.get(e);if(!i){i=[];r.set(e,i)}i.push(t)}const s=i.get("StructParents");if(!Number.isInteger(s))return;const n=a.get(s),updateElement=(e,i,a)=>{const s=r.get(e);if(s){const e=i.getRaw("P"),r=t.fetchIfRef(e);if(e instanceof Ref&&r instanceof Dict){const e={ref:a,dict:i};for(const t of s)t.structTreeParent=e}return!0}return!1};for(const e of n){if(!(e instanceof Ref))continue;const i=t.fetch(e),a=i.get("K");if(Number.isInteger(a))updateElement(a,i,e);else if(Array.isArray(a))for(let r of a){r=t.fetchIfRef(r);if(Number.isInteger(r)&&updateElement(r,i,e))break;if(!(r instanceof Dict))continue;if(!isName(r.get("Type"),"MCR"))break;const a=r.get("MCID");if(Number.isInteger(a)&&updateElement(a,i,e))break}}}static async#v({structTreeParent:e,tagDict:t,newTagRef:i,structTreeRootRef:a,fallbackKids:r,xref:s,cache:n}){let o,g=null;if(e){({ref:g}=e);o=e.dict.getRaw("P")||a}else o=a;t.set("P",o);const c=s.fetchIfRef(o);if(!c){r.push(i);return}let l=n.get(o);if(!l){l=c.clone();n.put(o,l)}const h=l.getRaw("K");let C=h instanceof Ref?n.get(h):null;if(!C){C=s.fetchIfRef(h);C=Array.isArray(C)?C.slice():[h];const e=s.getNewTemporaryRef();l.set("K",e);n.put(e,C)}const Q=C.indexOf(g);C.splice(Q>=0?Q+1:C.length,0,i)}}class StructElementNode{constructor(e,t){this.tree=e;this.dict=t;this.kids=[];this.parseKids()}get role(){const e=this.dict.get("S"),t=e instanceof Name?e.name:"",{root:i}=this.tree;return i.roleMap.has(t)?i.roleMap.get(t):t}parseKids(){let e=null;const t=this.dict.getRaw("Pg");t instanceof Ref&&(e=t.toString());const i=this.dict.get("K");if(Array.isArray(i))for(const t of i){const i=this.parseKid(e,t);i&&this.kids.push(i)}else{const t=this.parseKid(e,i);t&&this.kids.push(t)}}parseKid(e,t){if(Number.isInteger(t))return this.tree.pageDict.objId!==e?null:new StructElement({type:Mr,mcid:t,pageObjId:e});let i=null;t instanceof Ref?i=this.dict.xref.fetch(t):t instanceof Dict&&(i=t);if(!i)return null;const a=i.getRaw("Pg");a instanceof Ref&&(e=a.toString());const r=i.get("Type")instanceof Name?i.get("Type").name:null;if("MCR"===r){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Stm");return new StructElement({type:Ur,refObjId:t instanceof Ref?t.toString():null,pageObjId:e,mcid:i.get("MCID")})}if("OBJR"===r){if(this.tree.pageDict.objId!==e)return null;const t=i.getRaw("Obj");return new StructElement({type:xr,refObjId:t instanceof Ref?t.toString():null,pageObjId:e})}return new StructElement({type:Hr,dict:i})}}class StructElement{constructor({type:e,dict:t=null,mcid:i=null,pageObjId:a=null,refObjId:r=null}){this.type=e;this.dict=t;this.mcid=i;this.pageObjId=a;this.refObjId=r;this.parentNode=null}}class StructTreePage{constructor(e,t){this.root=e;this.rootDict=e?e.dict:null;this.pageDict=t;this.nodes=[]}collectObjects(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return null;const t=this.rootDict.get("ParentTree");if(!t)return null;const i=this.root.structParentIds?.get(e);if(!i)return null;const a=new Map,r=new NumberTree(t,this.rootDict.xref);for(const[e]of i){const t=r.getRaw(e);t instanceof Ref&&a.set(e,t)}return a}parse(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return;const t=this.rootDict.get("ParentTree");if(!t)return;const i=this.pageDict.get("StructParents"),a=this.root.structParentIds?.get(e);if(!Number.isInteger(i)&&!a)return;const r=new Map,s=new NumberTree(t,this.rootDict.xref);if(Number.isInteger(i)){const e=s.get(i);if(Array.isArray(e))for(const t of e)t instanceof Ref&&this.addNode(this.rootDict.xref.fetch(t),r)}if(a)for(const[e,t]of a){const i=s.get(e);if(i){const e=this.addNode(this.rootDict.xref.fetchIfRef(i),r);1===e?.kids?.length&&e.kids[0].type===xr&&(e.kids[0].type=t)}}}addNode(e,t,i=0){if(i>40){warn("StructTree MAX_DEPTH reached.");return null}if(!(e instanceof Dict))return null;if(t.has(e))return t.get(e);const a=new StructElementNode(this,e);t.set(e,a);const r=e.get("P");if(!r||isName(r.get("Type"),"StructTreeRoot")){this.addTopLevelNode(e,a)||t.delete(e);return a}const s=this.addNode(r,t,i+1);if(!s)return a;let n=!1;for(const t of s.kids)if(t.type===Hr&&t.dict===e){t.parentNode=a;n=!0}n||t.delete(e);return a}addTopLevelNode(e,t){const i=this.rootDict.get("K");if(!i)return!1;if(i instanceof Dict){if(i.objId!==e.objId)return!1;this.nodes[0]=t;return!0}if(!Array.isArray(i))return!0;let a=!1;for(let r=0;r40){warn("StructTree too deep to be fully serialized.");return}const a=Object.create(null);a.role=e.role;a.children=[];t.children.push(a);let r=e.dict.get("Alt");"string"!=typeof r&&(r=e.dict.get("ActualText"));"string"==typeof r&&(a.alt=stringToPDFString(r));const s=e.dict.get("A");if(s instanceof Dict){const e=lookupNormalRect(s.getArray("BBox"),null);if(e)a.bbox=e;else{const e=s.get("Width"),t=s.get("Height");"number"==typeof e&&e>0&&"number"==typeof t&&t>0&&(a.bbox=[0,0,e,t])}}const n=e.dict.get("Lang");"string"==typeof n&&(a.lang=stringToPDFString(n));for(const t of e.kids){const e=t.type===Hr?t.parentNode:null;e?nodeToSerializable(e,a,i+1):t.type===Mr||t.type===Ur?a.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):t.type===xr?a.children.push({type:"object",id:t.refObjId}):t.type===Lr&&a.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[];e.role="Root";for(const t of this.nodes)t&&nodeToSerializable(t,e);return e}}function isValidExplicitDest(e){if(!Array.isArray(e)||e.length<2)return!1;const[t,i,...a]=e;if(!(t instanceof Ref||Number.isInteger(t)))return!1;if(!(i instanceof Name))return!1;const r=a.length;let s=!0;switch(i.name){case"XYZ":if(r<2||r>3)return!1;break;case"Fit":case"FitB":return 0===r;case"FitH":case"FitBH":case"FitV":case"FitBV":if(r>1)return!1;break;case"FitR":if(4!==r)return!1;s=!1;break;default:return!1}for(const e of a)if(!("number"==typeof e||s&&null===e))return!1;return!0}function fetchDest(e){e instanceof Dict&&(e=e.get("D"));return isValidExplicitDest(e)?e:null}function fetchRemoteDest(e){let t=e.get("D");if(t){t instanceof Name&&(t=t.name);if("string"==typeof t)return stringToPDFString(t);if(isValidExplicitDest(t))return JSON.stringify(t)}return null}class Catalog{constructor(e,t){this.pdfManager=e;this.xref=t;this._catDict=t.getCatalogObj();if(!(this._catDict instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict;this._actualNumPages=null;this.fontCache=new RefSetCache;this.builtInCMapCache=new Map;this.standardFontDataCache=new Map;this.globalImageCache=new GlobalImageCache;this.pageKidsCountCache=new RefSetCache;this.pageIndexCache=new RefSetCache;this.pageDictCache=new RefSetCache;this.nonBlendModesSet=new RefSet;this.systemFontCache=new Map}cloneDict(){return this._catDict.clone()}get version(){const e=this._catDict.get("Version");if(e instanceof Name){if(mt.test(e.name))return shadow(this,"version",e.name);warn(`Invalid PDF catalog version: ${e.name}`)}return shadow(this,"version",null)}get lang(){const e=this._catDict.get("Lang");return shadow(this,"lang",e&&"string"==typeof e?stringToPDFString(e):null)}get needsRendering(){const e=this._catDict.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof e&&e)}get collection(){let e=null;try{const t=this._catDict.get("Collection");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch Collection entry; assuming no collection is present.")}return shadow(this,"collection",e)}get acroForm(){let e=null;try{const t=this._catDict.get("AcroForm");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch AcroForm entry; assuming no forms are present.")}return shadow(this,"acroForm",e)}get acroFormRef(){const e=this._catDict.getRaw("AcroForm");return shadow(this,"acroFormRef",e instanceof Ref?e:null)}get metadata(){const e=this._catDict.getRaw("Metadata");if(!(e instanceof Ref))return shadow(this,"metadata",null);let t=null;try{const i=this.xref.fetch(e,!this.xref.encrypt?.encryptMetadata);if(i instanceof BaseStream&&i.dict instanceof Dict){const e=i.dict.get("Type"),a=i.dict.get("Subtype");if(isName(e,"Metadata")&&isName(a,"XML")){const e=stringToUTF8String(i.getString());e&&(t=new MetadataParser(e).serializable)}}}catch(e){if(e instanceof MissingDataException)throw e;info(`Skipping invalid Metadata: "${e}".`)}return shadow(this,"metadata",t)}get markInfo(){let e=null;try{e=this._readMarkInfo()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read mark info.")}return shadow(this,"markInfo",e)}_readMarkInfo(){const e=this._catDict.get("MarkInfo");if(!(e instanceof Dict))return null;const t={Marked:!1,UserProperties:!1,Suspects:!1};for(const i in t){const a=e.get(i);"boolean"==typeof a&&(t[i]=a)}return t}get structTreeRoot(){let e=null;try{e=this._readStructTreeRoot()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable read to structTreeRoot info.")}return shadow(this,"structTreeRoot",e)}_readStructTreeRoot(){const e=this._catDict.getRaw("StructTreeRoot"),t=this.xref.fetchIfRef(e);if(!(t instanceof Dict))return null;const i=new StructTreeRoot(t,e);i.init();return i}get toplevelPagesDict(){const e=this._catDict.get("Pages");if(!(e instanceof Dict))throw new FormatError("Invalid top-level pages dictionary.");return shadow(this,"toplevelPagesDict",e)}get documentOutline(){let e=null;try{e=this._readDocumentOutline()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read document outline.")}return shadow(this,"documentOutline",e)}_readDocumentOutline(){let e=this._catDict.get("Outlines");if(!(e instanceof Dict))return null;e=e.getRaw("First");if(!(e instanceof Ref))return null;const t={items:[]},i=[{obj:e,parent:t}],a=new RefSet;a.put(e);const r=this.xref,s=new Uint8ClampedArray(3);for(;i.length>0;){const t=i.shift(),n=r.fetchIfRef(t.obj);if(null===n)continue;n.has("Title")||warn("Invalid outline item encountered.");const o={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:n,resultObj:o,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const g=n.get("Title"),c=n.get("F")||0,l=n.getArray("C"),h=n.get("Count");let C=s;!isNumberArray(l,3)||0===l[0]&&0===l[1]&&0===l[2]||(C=ColorSpace.singletons.rgb.getRgb(l,0));const Q={action:o.action,attachment:o.attachment,dest:o.dest,url:o.url,unsafeUrl:o.unsafeUrl,newWindow:o.newWindow,setOCGState:o.setOCGState,title:"string"==typeof g?stringToPDFString(g):"",color:C,count:Number.isInteger(h)?h:void 0,bold:!!(2&c),italic:!!(1&c),items:[]};t.parent.items.push(Q);e=n.getRaw("First");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:Q});a.put(e)}e=n.getRaw("Next");if(e instanceof Ref&&!a.has(e)){i.push({obj:e,parent:t.parent});a.put(e)}}return t.items.length>0?t.items:null}get permissions(){let e=null;try{e=this._readPermissions()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read permissions.")}return shadow(this,"permissions",e)}_readPermissions(){const e=this.xref.trailer.get("Encrypt");if(!(e instanceof Dict))return null;let t=e.get("P");if("number"!=typeof t)return null;t+=2**32;const i=[];for(const e in w){const a=w[e];t&a&&i.push(a)}return i}get optionalContentConfig(){let e=null;try{const t=this._catDict.get("OCProperties");if(!t)return shadow(this,"optionalContentConfig",null);const i=t.get("D");if(!i)return shadow(this,"optionalContentConfig",null);const a=t.get("OCGs");if(!Array.isArray(a))return shadow(this,"optionalContentConfig",null);const r=new RefSetCache;for(const e of a)e instanceof Ref&&!r.has(e)&&r.put(e,this.#Y(e));e=this.#K(i,r)}catch(e){if(e instanceof MissingDataException)throw e;warn(`Unable to read optional content config: ${e}`)}return shadow(this,"optionalContentConfig",e)}#Y(e){const t=this.xref.fetch(e),i={id:e.toString(),name:null,intent:null,usage:{print:null,view:null},rbGroups:[]},a=t.get("Name");"string"==typeof a&&(i.name=stringToPDFString(a));let r=t.getArray("Intent");Array.isArray(r)||(r=[r]);r.every((e=>e instanceof Name))&&(i.intent=r.map((e=>e.name)));const s=t.get("Usage");if(!(s instanceof Dict))return i;const n=i.usage,o=s.get("Print");if(o instanceof Dict){const e=o.get("PrintState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.print={printState:e.name}}}const g=s.get("View");if(g instanceof Dict){const e=g.get("ViewState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":n.view={viewState:e.name}}}return i}#K(e,t){function parseOnOff(e){const i=[];if(Array.isArray(e))for(const a of e)a instanceof Ref&&t.has(a)&&i.push(a.toString());return i}function parseOrder(e,i=0){if(!Array.isArray(e))return null;const r=[];for(const s of e){if(s instanceof Ref&&t.has(s)){a.put(s);r.push(s.toString());continue}const e=parseNestedOrder(s,i);e&&r.push(e)}if(i>0)return r;const s=[];for(const[e]of t.items())a.has(e)||s.push(e.toString());s.length&&r.push({name:null,order:s});return r}function parseNestedOrder(e,t){if(++t>r){warn("parseNestedOrder - reached MAX_NESTED_LEVELS.");return null}const a=i.fetchIfRef(e);if(!Array.isArray(a))return null;const s=i.fetchIfRef(a[0]);if("string"!=typeof s)return null;const n=parseOrder(a.slice(1),t);return n?.length?{name:stringToPDFString(s),order:n}:null}const i=this.xref,a=new RefSet,r=10;!function parseRBGroups(e){if(Array.isArray(e))for(const a of e){const e=i.fetchIfRef(a);if(!Array.isArray(e)||!e.length)continue;const r=new Set;for(const i of e)if(i instanceof Ref&&t.has(i)&&!r.has(i.toString())){r.add(i.toString());t.get(i).rbGroups.push(r)}}}(e.get("RBGroups"));return{name:"string"==typeof e.get("Name")?stringToPDFString(e.get("Name")):null,creator:"string"==typeof e.get("Creator")?stringToPDFString(e.get("Creator")):null,baseState:e.get("BaseState")instanceof Name?e.get("BaseState").name:null,on:parseOnOff(e.get("ON")),off:parseOnOff(e.get("OFF")),order:parseOrder(e.get("Order")),groups:[...t]}}setActualNumPages(e=null){this._actualNumPages=e}get hasActualNumPages(){return null!==this._actualNumPages}get _pagesCount(){const e=this.toplevelPagesDict.get("Count");if(!Number.isInteger(e))throw new FormatError("Page count in top-level pages dictionary is not an integer.");return shadow(this,"_pagesCount",e)}get numPages(){return this.hasActualNumPages?this._actualNumPages:this._pagesCount}get destinations(){const e=this._readDests(),t=Object.create(null);if(e instanceof NameTree)for(const[i,a]of e.getAll()){const e=fetchDest(a);e&&(t[stringToPDFString(i)]=e)}else if(e instanceof Dict)for(const[i,a]of e){const e=fetchDest(a);e&&(t[i]=e)}return shadow(this,"destinations",t)}getDestination(e){const t=this._readDests();if(t instanceof NameTree){const i=fetchDest(t.get(e));if(i)return i;const a=this.destinations[e];if(a){warn(`Found "${e}" at an incorrect position in the NameTree.`);return a}}else if(t instanceof Dict){const i=fetchDest(t.get(e));if(i)return i}return null}_readDests(){const e=this._catDict.get("Names");return e?.has("Dests")?new NameTree(e.getRaw("Dests"),this.xref):this._catDict.has("Dests")?this._catDict.get("Dests"):void 0}get pageLabels(){let e=null;try{e=this._readPageLabels()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read page labels.")}return shadow(this,"pageLabels",e)}_readPageLabels(){const e=this._catDict.getRaw("PageLabels");if(!e)return null;const t=new Array(this.numPages);let i=null,a="";const r=new NumberTree(e,this.xref).getAll();let s="",n=1;for(let e=0,o=this.numPages;e=1))throw new FormatError("Invalid start in PageLabel dictionary.");n=e}else n=1}switch(i){case"D":s=n;break;case"R":case"r":s=toRomanNumerals(n,"r"===i);break;case"A":case"a":const e=26,t="a"===i?97:65,a=n-1;s=String.fromCharCode(t+a%e).repeat(Math.floor(a/e)+1);break;default:if(i)throw new FormatError(`Invalid style "${i}" in PageLabel dictionary.`);s=""}t[e]=a+s;n++}return t}get pageLayout(){const e=this._catDict.get("PageLayout");let t="";if(e instanceof Name)switch(e.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":t=e.name}return shadow(this,"pageLayout",t)}get pageMode(){const e=this._catDict.get("PageMode");let t="UseNone";if(e instanceof Name)switch(e.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":t=e.name}return shadow(this,"pageMode",t)}get viewerPreferences(){const e=this._catDict.get("ViewerPreferences");if(!(e instanceof Dict))return shadow(this,"viewerPreferences",null);let t=null;for(const i of e.getKeys()){const a=e.get(i);let r;switch(i){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof a&&(r=a);break;case"NonFullScreenPageMode":if(a instanceof Name)switch(a.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":r=a.name;break;default:r="UseNone"}break;case"Direction":if(a instanceof Name)switch(a.name){case"L2R":case"R2L":r=a.name;break;default:r="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(a instanceof Name)switch(a.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":r=a.name;break;default:r="CropBox"}break;case"PrintScaling":if(a instanceof Name)switch(a.name){case"None":case"AppDefault":r=a.name;break;default:r="AppDefault"}break;case"Duplex":if(a instanceof Name)switch(a.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":r=a.name;break;default:r="None"}break;case"PrintPageRange":if(Array.isArray(a)&&a.length%2==0){a.every(((e,t,i)=>Number.isInteger(e)&&e>0&&(0===t||e>=i[t-1])&&e<=this.numPages))&&(r=a)}break;case"NumCopies":Number.isInteger(a)&&a>0&&(r=a);break;default:warn(`Ignoring non-standard key in ViewerPreferences: ${i}.`);continue}if(void 0!==r){t||(t=Object.create(null));t[i]=r}else warn(`Bad value, for key "${i}", in ViewerPreferences: ${a}.`)}return shadow(this,"viewerPreferences",t)}get openAction(){const e=this._catDict.get("OpenAction"),t=Object.create(null);if(e instanceof Dict){const i=new Dict(this.xref);i.set("A",e);const a={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:i,resultObj:a});Array.isArray(a.dest)?t.dest=a.dest:a.action&&(t.action=a.action)}else Array.isArray(e)&&(t.dest=e);return shadow(this,"openAction",objectSize(t)>0?t:null)}get attachments(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("EmbeddedFiles")){const i=new NameTree(e.getRaw("EmbeddedFiles"),this.xref);for(const[e,a]of i.getAll()){const i=new FileSpec(a,this.xref);t||(t=Object.create(null));t[stringToPDFString(e)]=i.serializable}}return shadow(this,"attachments",t)}get xfaImages(){const e=this._catDict.get("Names");let t=null;if(e instanceof Dict&&e.has("XFAImages")){const i=new NameTree(e.getRaw("XFAImages"),this.xref);for(const[e,a]of i.getAll()){t||(t=new Dict(this.xref));t.set(stringToPDFString(e),a)}}return shadow(this,"xfaImages",t)}_collectJavaScript(){const e=this._catDict.get("Names");let t=null;function appendIfJavaScriptDict(e,i){if(!(i instanceof Dict))return;if(!isName(i.get("S"),"JavaScript"))return;let a=i.get("JS");if(a instanceof BaseStream)a=a.getString();else if("string"!=typeof a)return;a=stringToPDFString(a).replaceAll("\0","");a&&(t||=new Map).set(e,a)}if(e instanceof Dict&&e.has("JavaScript")){const t=new NameTree(e.getRaw("JavaScript"),this.xref);for(const[e,i]of t.getAll())appendIfJavaScriptDict(stringToPDFString(e),i)}const i=this._catDict.get("OpenAction");i&&appendIfJavaScriptDict("OpenAction",i);return t}get jsActions(){const e=this._collectJavaScript();let t=collectActions(this.xref,this._catDict,mA);if(e){t||=Object.create(null);for(const[i,a]of e)i in t?t[i].push(a):t[i]=[a]}return shadow(this,"jsActions",t)}async fontFallback(e,t){const i=await Promise.all(this.fontCache);for(const a of i)if(a.loadedName===e){a.fallback(t);return}}async cleanup(e=!1){clearGlobalCaches();this.globalImageCache.clear(e);this.pageKidsCountCache.clear();this.pageIndexCache.clear();this.pageDictCache.clear();this.nonBlendModesSet.clear();const t=await Promise.all(this.fontCache);for(const{dict:e}of t)delete e.cacheKey;this.fontCache.clear();this.builtInCMapCache.clear();this.standardFontDataCache.clear();this.systemFontCache.clear()}async getPageDict(e){const t=[this.toplevelPagesDict],i=new RefSet,a=this._catDict.getRaw("Pages");a instanceof Ref&&i.put(a);const r=this.xref,s=this.pageKidsCountCache,n=this.pageIndexCache,o=this.pageDictCache;let g=0;for(;t.length;){const a=t.pop();if(a instanceof Ref){const c=s.get(a);if(c>=0&&g+c<=e){g+=c;continue}if(i.has(a))throw new FormatError("Pages tree contains circular reference.");i.put(a);const l=await(o.get(a)||r.fetchAsync(a));if(l instanceof Dict){let t=l.getRaw("Type");t instanceof Ref&&(t=await r.fetchAsync(t));if(isName(t,"Page")||!l.has("Kids")){s.has(a)||s.put(a,1);n.has(a)||n.put(a,g);if(g===e)return[l,a];g++;continue}}t.push(l);continue}if(!(a instanceof Dict))throw new FormatError("Page dictionary kid reference points to wrong type of object.");const{objId:c}=a;let l=a.getRaw("Count");l instanceof Ref&&(l=await r.fetchAsync(l));if(Number.isInteger(l)&&l>=0){c&&!s.has(c)&&s.put(c,l);if(g+l<=e){g+=l;continue}}let h=a.getRaw("Kids");h instanceof Ref&&(h=await r.fetchAsync(h));if(!Array.isArray(h)){let t=a.getRaw("Type");t instanceof Ref&&(t=await r.fetchAsync(t));if(isName(t,"Page")||!a.has("Kids")){if(g===e)return[a,null];g++;continue}throw new FormatError("Page dictionary kids object is not an array.")}for(let e=h.length-1;e>=0;e--){const i=h[e];t.push(i);a===this.toplevelPagesDict&&i instanceof Ref&&!o.has(i)&&o.put(i,r.fetchAsync(i))}}throw new Error(`Page index ${e} not found.`)}async getAllPageDicts(e=!1){const{ignoreErrors:t}=this.pdfManager.evaluatorOptions,i=[{currentNode:this.toplevelPagesDict,posInKids:0}],a=new RefSet,r=this._catDict.getRaw("Pages");r instanceof Ref&&a.put(r);const s=new Map,n=this.xref,o=this.pageIndexCache;let g=0;function addPageDict(e,t){t&&!o.has(t)&&o.put(t,g);s.set(g++,[e,t])}function addPageError(i){if(i instanceof XRefEntryException&&!e)throw i;if(e&&t&&0===g){warn(`getAllPageDicts - Skipping invalid first page: "${i}".`);i=Dict.empty}s.set(g++,[i,null])}for(;i.length>0;){const e=i.at(-1),{currentNode:t,posInKids:r}=e;let s=t.getRaw("Kids");if(s instanceof Ref)try{s=await n.fetchAsync(s)}catch(e){addPageError(e);break}if(!Array.isArray(s)){addPageError(new FormatError("Page dictionary kids object is not an array."));break}if(r>=s.length){i.pop();continue}const o=s[r];let g;if(o instanceof Ref){if(a.has(o)){addPageError(new FormatError("Pages tree contains circular reference."));break}a.put(o);try{g=await n.fetchAsync(o)}catch(e){addPageError(e);break}}else g=o;if(!(g instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let c=g.getRaw("Type");if(c instanceof Ref)try{c=await n.fetchAsync(c)}catch(e){addPageError(e);break}isName(c,"Page")||!g.has("Kids")?addPageDict(g,o instanceof Ref?o:null):i.push({currentNode:g,posInKids:0});e.posInKids++}return s}getPageIndex(e){const t=this.pageIndexCache.get(e);if(void 0!==t)return Promise.resolve(t);const i=this.xref;let a=0;const next=t=>function pagesBeforeRef(t){let a,r=0;return i.fetchAsync(t).then((function(i){if(isRefsEqual(t,e)&&!isDict(i,"Page")&&!(i instanceof Dict&&!i.has("Type")&&i.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!i)return null;if(!(i instanceof Dict))throw new FormatError("Node must be a dictionary.");a=i.getRaw("Parent");return i.getAsync("Parent")})).then((function(e){if(!e)return null;if(!(e instanceof Dict))throw new FormatError("Parent must be a dictionary.");return e.getAsync("Kids")})).then((function(e){if(!e)return null;const s=[];let n=!1;for(const a of e){if(!(a instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(a,t)){n=!0;break}s.push(i.fetchAsync(a).then((function(e){if(!(e instanceof Dict))throw new FormatError("Kid node must be a dictionary.");e.has("Count")?r+=e.get("Count"):r++})))}if(!n)throw new FormatError("Kid reference not found in parent's kids.");return Promise.all(s).then((function(){return[r,a]}))}))}(t).then((t=>{if(!t){this.pageIndexCache.put(e,a);return a}const[i,r]=t;a+=i;return next(r)}));return next(e)}get baseUrl(){const e=this._catDict.get("URI");if(e instanceof Dict){const t=e.get("Base");if("string"==typeof t){const e=createValidAbsoluteUrl(t,null,{tryConvertEncoding:!0});if(e)return shadow(this,"baseUrl",e.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:e,resultObj:t,docBaseUrl:i=null,docAttachments:a=null}){if(!(e instanceof Dict)){warn("parseDestDictionary: `destDict` must be a dictionary.");return}let r,s,n=e.get("A");if(!(n instanceof Dict))if(e.has("Dest"))n=e.get("Dest");else{n=e.get("AA");n instanceof Dict&&(n.has("D")?n=n.get("D"):n.has("U")&&(n=n.get("U")))}if(n instanceof Dict){const e=n.get("S");if(!(e instanceof Name)){warn("parseDestDictionary: Invalid type in Action dictionary.");return}const i=e.name;switch(i){case"ResetForm":const e=n.get("Flags"),o=!(1&("number"==typeof e?e:0)),g=[],c=[];for(const e of n.get("Fields")||[])e instanceof Ref?c.push(e.toString()):"string"==typeof e&&g.push(stringToPDFString(e));t.resetForm={fields:g,refs:c,include:o};break;case"URI":r=n.get("URI");r instanceof Name&&(r="/"+r.name);break;case"GoTo":s=n.get("D");break;case"Launch":case"GoToR":const l=n.get("F");if(l instanceof Dict){const e=new FileSpec(l,null,!0),{rawFilename:t}=e.serializable;r=t}else"string"==typeof l&&(r=l);const h=fetchRemoteDest(n);h&&"string"==typeof r&&(r=r.split("#",1)[0]+"#"+h);const C=n.get("NewWindow");"boolean"==typeof C&&(t.newWindow=C);break;case"GoToE":const Q=n.get("T");let E;if(a&&Q instanceof Dict){const e=Q.get("R"),t=Q.get("N");isName(e,"C")&&"string"==typeof t&&(E=a[stringToPDFString(t)])}if(E){t.attachment=E;const e=fetchRemoteDest(n);e&&(t.attachmentDest=e)}else warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const u=n.get("N");u instanceof Name&&(t.action=u.name);break;case"SetOCGState":const d=n.get("State"),f=n.get("PreserveRB");if(!Array.isArray(d)||0===d.length)break;const p=[];for(const e of d)if(e instanceof Name)switch(e.name){case"ON":case"OFF":case"Toggle":p.push(e.name)}else e instanceof Ref&&p.push(e.toString());if(p.length!==d.length)break;t.setOCGState={state:p,preserveRB:"boolean"!=typeof f||f};break;case"JavaScript":const m=n.get("JS");let y;m instanceof BaseStream?y=m.getString():"string"==typeof m&&(y=m);const w=y&&recoverJsURL(stringToPDFString(y));if(w){r=w.url;t.newWindow=w.newWindow;break}default:if("JavaScript"===i||"SubmitForm"===i)break;warn(`parseDestDictionary - unsupported action: "${i}".`)}}else e.has("Dest")&&(s=e.get("Dest"));if("string"==typeof r){const e=createValidAbsoluteUrl(r,i,{addDefaultProtocol:!0,tryConvertEncoding:!0});e&&(t.url=e.href);t.unsafeUrl=r}if(s){s instanceof Name&&(s=s.name);"string"==typeof s?t.dest=stringToPDFString(s):isValidExplicitDest(s)&&(t.dest=s)}}}function addChildren(e,t){if(e instanceof Dict)e=e.getRawValues();else if(e instanceof BaseStream)e=e.dict.getRawValues();else if(!Array.isArray(e))return;for(const a of e)((i=a)instanceof Ref||i instanceof Dict||i instanceof BaseStream||Array.isArray(i))&&t.push(a);var i}class ObjectLoader{constructor(e,t,i){this.dict=e;this.keys=t;this.xref=i;this.refSet=null}async load(){if(this.xref.stream.isDataLoaded)return;const{keys:e,dict:t}=this;this.refSet=new RefSet;const i=[];for(const a of e){const e=t.getRaw(a);void 0!==e&&i.push(e)}return this._walk(i)}async _walk(e){const t=[],i=[];for(;e.length;){let a=e.pop();if(a instanceof Ref){if(this.refSet.has(a))continue;try{this.refSet.put(a);a=this.xref.fetch(a)}catch(e){if(!(e instanceof MissingDataException)){warn(`ObjectLoader._walk - requesting all data: "${e}".`);this.refSet=null;const{manager:t}=this.xref.stream;return t.requestAllChunks()}t.push(a);i.push({begin:e.begin,end:e.end})}}if(a instanceof BaseStream){const e=a.getBaseStreams();if(e){let r=!1;for(const t of e)if(!t.isDataLoaded){r=!0;i.push({begin:t.start,end:t.end})}r&&t.push(a)}}addChildren(a,e)}if(i.length){await this.xref.stream.manager.requestRanges(i);for(const e of t)e instanceof Ref&&this.refSet.remove(e);return this._walk(t)}this.refSet=null}}const Jr=Symbol(),vr=Symbol(),Yr=Symbol(),Kr=Symbol(),Tr=Symbol(),qr=Symbol(),Or=Symbol(),Pr=Symbol(),Wr=Symbol(),jr=Symbol("content"),Xr=Symbol("data"),Vr=Symbol(),Zr=Symbol("extra"),_r=Symbol(),zr=Symbol(),$r=Symbol(),As=Symbol(),es=Symbol(),ts=Symbol(),is=Symbol(),as=Symbol(),rs=Symbol(),ss=Symbol(),ns=Symbol(),os=Symbol(),gs=Symbol(),Is=Symbol(),cs=Symbol(),ls=Symbol(),hs=Symbol(),Cs=Symbol(),Bs=Symbol(),Qs=Symbol(),Es=Symbol(),us=Symbol(),ds=Symbol(),fs=Symbol(),ps=Symbol(),ms=Symbol(),ys=Symbol(),ws=Symbol(),bs=Symbol(),Ds=Symbol(),Fs=Symbol(),Ss=Symbol(),ks=Symbol("namespaceId"),Rs=Symbol("nodeName"),Ns=Symbol(),Gs=Symbol(),Ms=Symbol(),Us=Symbol(),xs=Symbol(),Ls=Symbol(),Hs=Symbol(),Js=Symbol(),vs=Symbol("root"),Ys=Symbol(),Ks=Symbol(),Ts=Symbol(),qs=Symbol(),Os=Symbol(),Ws=Symbol(),js=Symbol(),Xs=Symbol(),Vs=Symbol(),Zs=Symbol(),_s=Symbol(),zs=Symbol("uid"),$s=Symbol(),An={config:{id:0,check:e=>e.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:e=>"http://ns.adobe.com/xdp/pdf/"===e},signature:{id:6,check:e=>"http://www.w3.org/2000/09/xmldsig#"===e},sourceSet:{id:7,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:e=>"http://www.w3.org/1999/XSL/Transform"===e},template:{id:9,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:e=>e.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:e=>"http://ns.adobe.com/xdp/"===e},xfdf:{id:12,check:e=>"http://ns.adobe.com/xfdf/"===e},xhtml:{id:13,check:e=>"http://www.w3.org/1999/xhtml"===e},xmpmeta:{id:14,check:e=>"http://ns.adobe.com/xmpmeta/"===e}},en={pt:e=>e,cm:e=>e/2.54*72,mm:e=>e/25.4*72,in:e=>72*e,px:e=>e},tn=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(e){return e.startsWith("'")||e.startsWith('"')?e.slice(1,-1):e}function getInteger({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseInt(e,10);return!isNaN(a)&&i(a)?a:t}function getFloat({data:e,defaultValue:t,validate:i}){if(!e)return t;e=e.trim();const a=parseFloat(e);return!isNaN(a)&&i(a)?a:t}function getKeyword({data:e,defaultValue:t,validate:i}){return e&&i(e=e.trim())?e:t}function getStringOption(e,t){return getKeyword({data:e,defaultValue:t[0],validate:e=>t.includes(e)})}function getMeasurement(e,t="0"){t||="0";if(!e)return getMeasurement(t);const i=e.trim().match(tn);if(!i)return getMeasurement(t);const[,a,r]=i,s=parseFloat(a);if(isNaN(s))return getMeasurement(t);if(0===s)return 0;const n=en[r];return n?n(s):s}function getRatio(e){if(!e)return{num:1,den:1};const t=e.trim().split(/\s*:\s*/).map((e=>parseFloat(e))).filter((e=>!isNaN(e)));1===t.length&&t.push(1);if(0===t.length)return{num:1,den:1};const[i,a]=t;return{num:i,den:a}}function getRelevant(e){return e?e.trim().split(/\s+/).map((e=>({excluded:"-"===e[0],viewname:e.substring(1)}))):[]}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(e,t,i,a){this.success=e;this.html=t;this.bbox=i;this.breakNode=a}isBreak(){return!!this.breakNode}static breakNode(e){return new HTMLResult(!1,null,null,e)}static success(e,t=null){return new HTMLResult(!0,e,t,null)}}class FontFinder{constructor(e){this.fonts=new Map;this.cache=new Map;this.warned=new Set;this.defaultFont=null;this.add(e)}add(e,t=null){for(const t of e)this.addPdfFont(t);for(const e of this.fonts.values())e.regular||(e.regular=e.italic||e.bold||e.bolditalic);if(!t||0===t.size)return;const i=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const e of t)this.fonts.set(e,i)}addPdfFont(e){const t=e.cssFontInfo,i=t.fontFamily;let a=this.fonts.get(i);if(!a){a=Object.create(null);this.fonts.set(i,a);this.defaultFont||(this.defaultFont=a)}let r="";const s=parseFloat(t.fontWeight);0!==parseFloat(t.italicAngle)?r=s>=700?"bolditalic":"italic":s>=700&&(r="bold");if(!r){(e.name.includes("Bold")||e.psName?.includes("Bold"))&&(r="bold");(e.name.includes("Italic")||e.name.endsWith("It")||e.psName?.includes("Italic")||e.psName?.endsWith("It"))&&(r+="italic")}r||(r="regular");a[r]=e}getDefault(){return this.defaultFont}find(e,t=!0){let i=this.fonts.get(e)||this.cache.get(e);if(i)return i;const a=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let r=e.replaceAll(a,"");i=this.fonts.get(r);if(i){this.cache.set(e,i);return i}r=r.toLowerCase();const s=[];for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(r)&&s.push(t);if(0===s.length)for(const[,e]of this.fonts.entries())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(r)&&s.push(e);if(0===s.length){r=r.replaceAll(/psmt|mt/gi,"");for(const[e,t]of this.fonts.entries())e.replaceAll(a,"").toLowerCase().startsWith(r)&&s.push(t)}if(0===s.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(a,"").toLowerCase().startsWith(r)&&s.push(e);if(s.length>=1){1!==s.length&&t&&warn(`XFA - Too many choices to guess the correct font: ${e}`);this.cache.set(e,s[0]);return s[0]}if(t&&!this.warned.has(e)){this.warned.add(e);warn(`XFA - Cannot find the font: ${e}`)}return null}}function selectFont(e,t){return"italic"===e.posture?"bold"===e.weight?t.bolditalic:t.italic:"bold"===e.weight?t.bold:t.regular}class FontInfo{constructor(e,t,i,a){this.lineHeight=i;this.paraMargin=t||{top:0,bottom:0,left:0,right:0};if(!e){[this.pdfFont,this.xfaFont]=this.defaultFont(a);return}this.xfaFont={typeface:e.typeface,posture:e.posture,weight:e.weight,size:e.size,letterSpacing:e.letterSpacing};const r=a.find(e.typeface);if(r){this.pdfFont=selectFont(e,r);this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(a))}else[this.pdfFont,this.xfaFont]=this.defaultFont(a)}defaultFont(e){const t=e.find("Helvetica",!1)||e.find("Myriad Pro",!1)||e.find("Arial",!1)||e.getDefault();if(t?.regular){const e=t.regular;return[e,{typeface:e.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class FontSelector{constructor(e,t,i,a){this.fontFinder=a;this.stack=[new FontInfo(e,t,i,a)]}pushData(e,t,i){const a=this.stack.at(-1);for(const t of["typeface","posture","weight","size","letterSpacing"])e[t]||(e[t]=a.xfaFont[t]);for(const e of["top","bottom","left","right"])isNaN(t[e])&&(t[e]=a.paraMargin[e]);const r=new FontInfo(e,t,i||a.lineHeight,this.fontFinder);r.pdfFont||(r.pdfFont=a.pdfFont);this.stack.push(r)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(e,t,i,a){this.glyphs=[];this.fontSelector=new FontSelector(e,t,i,a);this.extraHeight=0}pushData(e,t,i){this.fontSelector.pushData(e,t,i)}popFont(e){return this.fontSelector.popFont()}addPara(){const e=this.fontSelector.topFont();this.extraHeight+=e.paraMargin.top+e.paraMargin.bottom}addString(e){if(!e)return;const t=this.fontSelector.topFont(),i=t.xfaFont.size;if(t.pdfFont){const a=t.xfaFont.letterSpacing,r=t.pdfFont,s=r.lineHeight||1.2,n=t.lineHeight||Math.max(1.2,s)*i,o=s-(void 0===r.lineGap?.2:r.lineGap),g=Math.max(1,o)*i,c=i/1e3,l=r.defaultWidth||r.charsToGlyphs(" ")[0].width;for(const t of e.split(/[\u2029\n]/)){const e=r.encodeString(t).join(""),i=r.charsToGlyphs(e);for(const e of i){const t=e.width||l;this.glyphs.push([t*c+a,n,g,e.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}else{for(const t of e.split(/[\u2029\n]/)){for(const e of t.split(""))this.glyphs.push([i,1.2*i,i,e,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}}compute(e){let t=-1,i=0,a=0,r=0,s=0,n=0,o=!1,g=!0;for(let c=0,l=this.glyphs.length;ce){a=Math.max(a,s);s=0;r+=n;n=d;t=-1;i=0;o=!0;g=!1}else{n=Math.max(d,n);i=s;s+=l;t=c}else if(s+l>e){r+=n;n=d;if(-1!==t){c=t;a=Math.max(a,i);s=0;t=-1;i=0}else{a=Math.max(a,s);s=l}o=!0;g=!1}else{s+=l;n=Math.max(d,n)}}a=Math.max(a,s);r+=n+this.extraHeight;return{width:1.02*a,height:r,isBroken:o}}}const an=/^[^.[]+/,rn=/^[^\]]+/,sn=0,nn=1,on=2,gn=3,In=4,cn=new Map([["$data",(e,t)=>e.datasets?e.datasets.data:e],["$record",(e,t)=>(e.datasets?e.datasets.data:e)[os]()[0]],["$template",(e,t)=>e.template],["$connectionSet",(e,t)=>e.connectionSet],["$form",(e,t)=>e.form],["$layout",(e,t)=>e.layout],["$host",(e,t)=>e.host],["$dataWindow",(e,t)=>e.dataWindow],["$event",(e,t)=>e.event],["!",(e,t)=>e.datasets],["$xfa",(e,t)=>e],["xfa",(e,t)=>e],["$",(e,t)=>t]]),ln=new WeakMap;function parseExpression(e,t,i=!0){let a=e.match(an);if(!a)return null;let[r]=a;const s=[{name:r,cacheName:"."+r,index:0,js:null,formCalc:null,operator:sn}];let n=r.length;for(;n0&&l.push(e)}if(0!==l.length||o||0!==g)e=isFinite(c)?l.filter((e=>ce[c])):l.flat();else{const i=t[ls]();if(!(t=i))return null;g=-1;e=[t]}}return 0===e.length?null:e}function createDataNode(e,t,i){const a=parseExpression(i);if(!a)return null;if(a.some((e=>e.operator===nn)))return null;const r=cn.get(a[0].name);let s=0;if(r){e=r(e,t);s=1}else e=t||e;for(let t=a.length;se[js]())).join("")}get[Bn](){const e=Object.getPrototypeOf(this);if(!e._attributes){const t=e._attributes=new Set;for(const e of Object.getOwnPropertyNames(this)){if(null===this[e]||this[e]instanceof XFAObject||this[e]instanceof XFAObjectArray)break;t.add(e)}}return shadow(this,Bn,e._attributes)}[ms](e){let t=this;for(;t;){if(t===e)return!0;t=t[ls]()}return!1}[ls](){return this[Dn]}[cs](){return this[ls]()}[os](e=null){return e?this[e]:this[Qn]}[Vr](){const e=Object.create(null);this[jr]&&(e.$content=this[jr]);for(const t of Object.getOwnPropertyNames(this)){const i=this[t];null!==i&&(i instanceof XFAObject?e[t]=i[Vr]():i instanceof XFAObjectArray?i.isEmpty()||(e[t]=i.dump()):e[t]=i)}return e}[_s](){return null}[Vs](){return HTMLResult.EMPTY}*[gs](){for(const e of this[os]())yield e}*[fn](e,t){for(const i of this[gs]())if(!e||t===e.has(i[Rs])){const e=this[es](),t=i[Vs](e);t.success||(this[Zr].failingNode=i);yield t}}[zr](){return null}[vr](e,t){this[Zr].children.push(e)}[es](){}[Kr]({filter:e=null,include:t=!0}){if(this[Zr].generator){const e=this[es](),t=this[Zr].failingNode[Vs](e);if(!t.success)return t;t.html&&this[vr](t.html,t.bbox);delete this[Zr].failingNode}else this[Zr].generator=this[fn](e,t);for(;;){const e=this[Zr].generator.next();if(e.done)break;const t=e.value;if(!t.success)return t;t.html&&this[vr](t.html,t.bbox)}this[Zr].generator=null;return HTMLResult.EMPTY}[qs](e){this[Sn]=new Set(Object.keys(e))}[mn](e){const t=this[Bn],i=this[Sn];return[...e].filter((e=>t.has(e)&&!i.has(e)))}[Ys](e,t=new Set){for(const i of this[Qn])i[Fn](e,t)}[Fn](e,t){const i=this[pn](e,t);i?this[hn](i,e,t):this[Ys](e,t)}[pn](e,t){const{use:i,usehref:a}=this;if(!i&&!a)return null;let r=null,s=null,n=null,o=i;if(a){o=a;a.startsWith("#som(")&&a.endsWith(")")?s=a.slice(5,-1):a.startsWith(".#som(")&&a.endsWith(")")?s=a.slice(6,-1):a.startsWith("#")?n=a.slice(1):a.startsWith(".#")&&(n=a.slice(2))}else i.startsWith("#")?n=i.slice(1):s=i;this.use=this.usehref="";if(n)r=e.get(n);else{r=searchNode(e.get(vs),this,s,!0,!1);r&&(r=r[0])}if(!r){warn(`XFA - Invalid prototype reference: ${o}.`);return null}if(r[Rs]!==this[Rs]){warn(`XFA - Incompatible prototype: ${r[Rs]} !== ${this[Rs]}.`);return null}if(t.has(r)){warn("XFA - Cycle detected in prototypes use.");return null}t.add(r);const g=r[pn](e,t);g&&r[hn](g,e,t);r[Ys](e,t);t.delete(r);return r}[hn](e,t,i){if(i.has(e)){warn("XFA - Cycle detected in prototypes use.");return}!this[jr]&&e[jr]&&(this[jr]=e[jr]);new Set(i).add(e);for(const t of this[mn](e[Sn])){this[t]=e[t];this[Sn]&&this[Sn].add(t)}for(const a of Object.getOwnPropertyNames(this)){if(this[Bn].has(a))continue;const r=this[a],s=e[a];if(r instanceof XFAObjectArray){for(const e of r[Qn])e[Fn](t,i);for(let a=r[Qn].length,n=s[Qn].length;aXFAObject[En](e))):"object"==typeof e&&null!==e?Object.assign({},e):e}[Pr](){const e=Object.create(Object.getPrototypeOf(this));for(const t of Object.getOwnPropertySymbols(this))try{e[t]=this[t]}catch{shadow(e,t,this[t])}e[zs]=`${e[Rs]}${Rn++}`;e[Qn]=[];for(const t of Object.getOwnPropertyNames(this)){if(this[Bn].has(t)){e[t]=XFAObject[En](this[t]);continue}const i=this[t];e[t]=i instanceof XFAObjectArray?new XFAObjectArray(i[wn]):null}for(const t of this[Qn]){const i=t[Rs],a=t[Pr]();e[Qn].push(a);a[Dn]=e;null===e[i]?e[i]=a:e[i][Qn].push(a)}return e}[os](e=null){return e?this[Qn].filter((t=>t[Rs]===e)):this[Qn]}[ts](e){return this[e]}[is](e,t,i=!0){return Array.from(this[as](e,t,i))}*[as](e,t,i=!0){if("parent"!==e){for(const i of this[Qn]){i[Rs]===e&&(yield i);i.name===e&&(yield i);(t||i[Ds]())&&(yield*i[as](e,t,!1))}i&&this[Bn].has(e)&&(yield new XFAAttribute(this,e,this[e]))}else yield this[Dn]}}class XFAObjectArray{constructor(e=1/0){this[wn]=e;this[Qn]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(e){if(this[Qn].length<=this[wn]){this[Qn].push(e);return!0}warn(`XFA - node "${e[Rs]}" accepts no more than ${this[wn]} children`);return!1}isEmpty(){return 0===this[Qn].length}dump(){return 1===this[Qn].length?this[Qn][0][Vr]():this[Qn].map((e=>e[Vr]()))}[Pr](){const e=new XFAObjectArray(this[wn]);e[Qn]=this[Qn].map((e=>e[Pr]()));return e}get children(){return this[Qn]}clear(){this[Qn].length=0}}class XFAAttribute{constructor(e,t,i){this[Dn]=e;this[Rs]=t;this[jr]=i;this[Wr]=!1;this[zs]="attribute"+Rn++}[ls](){return this[Dn]}[ps](){return!0}[rs](){return this[jr].trim()}[Os](e){e=e.value||"";this[jr]=e.toString()}[js](){return this[jr]}[ms](e){return this[Dn]===e||this[Dn][ms](e)}}class XmlObject extends XFAObject{constructor(e,t,i={}){super(e,t);this[jr]="";this[un]=null;if("#text"!==t){const e=new Map;this[Cn]=e;for(const[t,a]of Object.entries(i))e.set(t,new XFAAttribute(this,t,a));if(i.hasOwnProperty(Ns)){const e=i[Ns].xfa.dataNode;void 0!==e&&("dataGroup"===e?this[un]=!1:"dataValue"===e&&(this[un]=!0))}}this[Wr]=!1}[Zs](e){const t=this[Rs];if("#text"===t){e.push(encodeToXmlString(this[jr]));return}const i=utf8StringToString(t),a=this[ks]===Nn?"xfa:":"";e.push(`<${a}${i}`);for(const[t,i]of this[Cn].entries()){const a=utf8StringToString(t);e.push(` ${a}="${encodeToXmlString(i[jr])}"`)}null!==this[un]&&(this[un]?e.push(' xfa:dataNode="dataValue"'):e.push(' xfa:dataNode="dataGroup"'));if(this[jr]||0!==this[Qn].length){e.push(">");if(this[jr])"string"==typeof this[jr]?e.push(encodeToXmlString(this[jr])):this[jr][Zs](e);else for(const t of this[Qn])t[Zs](e);e.push(``)}else e.push("/>")}[Gs](e){if(this[jr]){const e=new XmlObject(this[ks],"#text");this[Yr](e);e[jr]=this[jr];this[jr]=""}this[Yr](e);return!0}[Us](e){this[jr]+=e}[_r](){if(this[jr]&&this[Qn].length>0){const e=new XmlObject(this[ks],"#text");this[Yr](e);e[jr]=this[jr];delete this[jr]}}[Vs](){return"#text"===this[Rs]?HTMLResult.success({name:"#text",value:this[jr]}):HTMLResult.EMPTY}[os](e=null){return e?this[Qn].filter((t=>t[Rs]===e)):this[Qn]}[As](){return this[Cn]}[ts](e){const t=this[Cn].get(e);return void 0!==t?t:this[os](e)}*[as](e,t){const i=this[Cn].get(e);i&&(yield i);for(const i of this[Qn]){i[Rs]===e&&(yield i);t&&(yield*i[as](e,t))}}*[$r](e,t){const i=this[Cn].get(e);!i||t&&i[Wr]||(yield i);for(const i of this[Qn])yield*i[$r](e,t)}*[ns](e,t,i){for(const a of this[Qn]){a[Rs]!==e||i&&a[Wr]||(yield a);t&&(yield*a[ns](e,t,i))}}[ps](){return null===this[un]?0===this[Qn].length||this[Qn][0][ks]===An.xhtml.id:this[un]}[rs](){return null===this[un]?0===this[Qn].length?this[jr].trim():this[Qn][0][ks]===An.xhtml.id?this[Qn][0][js]().trim():null:this[jr].trim()}[Os](e){e=e.value||"";this[jr]=e.toString()}[Vr](e=!1){const t=Object.create(null);e&&(t.$ns=this[ks]);this[jr]&&(t.$content=this[jr]);t.$name=this[Rs];t.children=[];for(const i of this[Qn])t.children.push(i[Vr](e));t.attributes=Object.create(null);for(const[e,i]of this[Cn])t.attributes[e]=i[jr];return t}}class ContentObject extends XFAObject{constructor(e,t){super(e,t);this[jr]=""}[Us](e){this[jr]+=e}[_r](){}}class OptionObject extends ContentObject{constructor(e,t,i){super(e,t);this[bn]=i}[_r](){this[jr]=getKeyword({data:this[jr],defaultValue:this[bn][0],validate:e=>this[bn].includes(e)})}[Tr](e){super[Tr](e);delete this[bn]}}class StringObject extends ContentObject{[_r](){this[jr]=this[jr].trim()}}class IntegerObject extends ContentObject{constructor(e,t,i,a){super(e,t);this[dn]=i;this[kn]=a}[_r](){this[jr]=getInteger({data:this[jr],defaultValue:this[dn],validate:this[kn]})}[Tr](e){super[Tr](e);delete this[dn];delete this[kn]}}class Option01 extends IntegerObject{constructor(e,t){super(e,t,0,(e=>1===e))}}class Option10 extends IntegerObject{constructor(e,t){super(e,t,1,(e=>0===e))}}function measureToString(e){return"string"==typeof e?"0px":Number.isInteger(e)?`${e}px`:`${e.toFixed(2)}px`}const Gn={anchorType(e,t){const i=e[cs]();if(i&&(!i.layout||"position"===i.layout)){"transform"in t||(t.transform="");switch(e.anchorType){case"bottomCenter":t.transform+="translate(-50%, -100%)";break;case"bottomLeft":t.transform+="translate(0,-100%)";break;case"bottomRight":t.transform+="translate(-100%,-100%)";break;case"middleCenter":t.transform+="translate(-50%,-50%)";break;case"middleLeft":t.transform+="translate(0,-50%)";break;case"middleRight":t.transform+="translate(-100%,-50%)";break;case"topCenter":t.transform+="translate(-50%,0)";break;case"topRight":t.transform+="translate(-100%,0)"}}},dimensions(e,t){const i=e[cs]();let a=e.w;const r=e.h;if(i.layout?.includes("row")){const t=i[Zr],r=e.colSpan;let s;if(-1===r){s=t.columnWidths.slice(t.currentColumn).reduce(((e,t)=>e+t),0);t.currentColumn=0}else{s=t.columnWidths.slice(t.currentColumn,t.currentColumn+r).reduce(((e,t)=>e+t),0);t.currentColumn=(t.currentColumn+e.colSpan)%t.columnWidths.length}isNaN(s)||(a=e.w=s)}t.width=""!==a?measureToString(a):"auto";t.height=""!==r?measureToString(r):"auto"},position(e,t){const i=e[cs]();if(!i?.layout||"position"===i.layout){t.position="absolute";t.left=measureToString(e.x);t.top=measureToString(e.y)}},rotate(e,t){if(e.rotate){"transform"in t||(t.transform="");t.transform+=`rotate(-${e.rotate}deg)`;t.transformOrigin="top left"}},presence(e,t){switch(e.presence){case"invisible":t.visibility="hidden";break;case"hidden":case"inactive":t.display="none"}},hAlign(e,t){if("para"===e[Rs])switch(e.hAlign){case"justifyAll":t.textAlign="justify-all";break;case"radix":t.textAlign="left";break;default:t.textAlign=e.hAlign}else switch(e.hAlign){case"left":t.alignSelf="start";break;case"center":t.alignSelf="center";break;case"right":t.alignSelf="end"}},margin(e,t){e.margin&&(t.margin=e.margin[_s]().margin)}};function setMinMaxDimensions(e,t){if("position"===e[cs]().layout){e.minW>0&&(t.minWidth=measureToString(e.minW));e.maxW>0&&(t.maxWidth=measureToString(e.maxW));e.minH>0&&(t.minHeight=measureToString(e.minH));e.maxH>0&&(t.maxHeight=measureToString(e.maxH))}}function layoutText(e,t,i,a,r,s){const n=new TextMeasure(t,i,a,r);"string"==typeof e?n.addString(e):e[xs](n);return n.compute(s)}function layoutNode(e,t){let i=null,a=null,r=!1;if((!e.w||!e.h)&&e.value){let s=0,n=0;if(e.margin){s=e.margin.leftInset+e.margin.rightInset;n=e.margin.topInset+e.margin.bottomInset}let o=null,g=null;if(e.para){g=Object.create(null);o=""===e.para.lineHeight?null:e.para.lineHeight;g.top=""===e.para.spaceAbove?0:e.para.spaceAbove;g.bottom=""===e.para.spaceBelow?0:e.para.spaceBelow;g.left=""===e.para.marginLeft?0:e.para.marginLeft;g.right=""===e.para.marginRight?0:e.para.marginRight}let c=e.font;if(!c){const t=e[hs]();let i=e[ls]();for(;i&&i!==t;){if(i.font){c=i.font;break}i=i[ls]()}}const l=(e.w||t.width)-s,h=e[Cs].fontFinder;if(e.value.exData&&e.value.exData[jr]&&"text/html"===e.value.exData.contentType){const t=layoutText(e.value.exData[jr],c,g,o,h,l);a=t.width;i=t.height;r=t.isBroken}else{const t=e.value[js]();if(t){const e=layoutText(t,c,g,o,h,l);a=e.width;i=e.height;r=e.isBroken}}null===a||e.w||(a+=s);null===i||e.h||(i+=n)}return{w:a,h:i,isBroken:r}}function computeBbox(e,t,i){let a;if(""!==e.w&&""!==e.h)a=[e.x,e.y,e.w,e.h];else{if(!i)return null;let r=e.w;if(""===r){if(0===e.maxW){const t=e[cs]();r="position"===t.layout&&""!==t.w?0:e.minW}else r=Math.min(e.maxW,i.width);t.attributes.style.width=measureToString(r)}let s=e.h;if(""===s){if(0===e.maxH){const t=e[cs]();s="position"===t.layout&&""!==t.h?0:e.minH}else s=Math.min(e.maxH,i.height);t.attributes.style.height=measureToString(s)}a=[e.x,e.y,r,s]}return a}function fixDimensions(e){const t=e[cs]();if(t.layout?.includes("row")){const i=t[Zr],a=e.colSpan;let r;r=-1===a?i.columnWidths.slice(i.currentColumn).reduce(((e,t)=>e+t),0):i.columnWidths.slice(i.currentColumn,i.currentColumn+a).reduce(((e,t)=>e+t),0);isNaN(r)||(e.w=r)}t.layout&&"position"!==t.layout&&(e.x=e.y=0);"table"===e.layout&&""===e.w&&Array.isArray(e.columnWidths)&&(e.w=e.columnWidths.reduce(((e,t)=>e+t),0))}function layoutClass(e){switch(e.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function toStyle(e,...t){const i=Object.create(null);for(const a of t){const t=e[a];if(null!==t)if(Gn.hasOwnProperty(a))Gn[a](e,i);else if(t instanceof XFAObject){const e=t[_s]();e?Object.assign(i,e):warn(`(DEBUG) - XFA - style for ${a} not implemented yet`)}}return i}function createWrapper(e,t){const{attributes:i}=t,{style:a}=i,r={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};i.class.push("xfaWrapped");if(e.border){const{widths:i,insets:s}=e.border[Zr];let n,o,g=s[0],c=s[3];const l=s[0]+s[2],h=s[1]+s[3];switch(e.border.hand){case"even":g-=i[0]/2;c-=i[3]/2;n=`calc(100% + ${(i[1]+i[3])/2-h}px)`;o=`calc(100% + ${(i[0]+i[2])/2-l}px)`;break;case"left":g-=i[0];c-=i[3];n=`calc(100% + ${i[1]+i[3]-h}px)`;o=`calc(100% + ${i[0]+i[2]-l}px)`;break;case"right":n=h?`calc(100% - ${h}px)`:"100%";o=l?`calc(100% - ${l}px)`:"100%"}const C=["xfaBorder"];isPrintOnly(e.border)&&C.push("xfaPrintOnly");const Q={name:"div",attributes:{class:C,style:{top:`${g}px`,left:`${c}px`,width:n,height:o}},children:[]};for(const e of["border","borderWidth","borderColor","borderRadius","borderStyle"])if(void 0!==a[e]){Q.attributes.style[e]=a[e];delete a[e]}r.children.push(Q,t)}else r.children.push(t);for(const e of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])if(void 0!==a[e]){r.attributes.style[e]=a[e];delete a[e]}r.attributes.style.position="absolute"===a.position?"absolute":"relative";delete a.position;if(a.alignSelf){r.attributes.style.alignSelf=a.alignSelf;delete a.alignSelf}return r}function fixTextIndent(e){const t=getMeasurement(e.textIndent,"0px");if(t>=0)return;const i="padding"+("left"===("right"===e.textAlign?"right":"left")?"Left":"Right"),a=getMeasurement(e[i],"0px");e[i]=a-t+"px"}function setAccess(e,t){switch(e.access){case"nonInteractive":t.push("xfaNonInteractive");break;case"readOnly":t.push("xfaReadOnly");break;case"protected":t.push("xfaDisabled")}}function isPrintOnly(e){return e.relevant.length>0&&!e.relevant[0].excluded&&"print"===e.relevant[0].viewname}function getCurrentPara(e){const t=e[hs]()[Zr].paraStack;return t.length?t.at(-1):null}function setPara(e,t,i){if(i.attributes.class?.includes("xfaRich")){if(t){""===e.h&&(t.height="auto");""===e.w&&(t.width="auto")}const a=getCurrentPara(e);if(a){const e=i.attributes.style;e.display="flex";e.flexDirection="column";switch(a.vAlign){case"top":e.justifyContent="start";break;case"bottom":e.justifyContent="end";break;case"middle":e.justifyContent="center"}const t=a[_s]();for(const[i,a]of Object.entries(t))i in e||(e[i]=a)}}}function setFontFamily(e,t,i,a){if(!i){delete a.fontFamily;return}const r=stripQuotes(e.typeface);a.fontFamily=`"${r}"`;const s=i.find(r);if(s){const{fontFamily:i}=s.regular.cssFontInfo;i!==r&&(a.fontFamily=`"${i}"`);const n=getCurrentPara(t);if(n&&""!==n.lineHeight)return;if(a.lineHeight)return;const o=selectFont(e,s);o&&(a.lineHeight=Math.max(1.2,o.lineHeight))}}function fixURL(e){const t=createValidAbsoluteUrl(e,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return t?t.href:null}function createLine(e,t){return{name:"div",attributes:{class:["lr-tb"===e.layout?"xfaLr":"xfaRl"]},children:t}}function flushHTML(e){if(!e[Zr])return null;const t={name:"div",attributes:e[Zr].attributes,children:e[Zr].children};if(e[Zr].failingNode){const i=e[Zr].failingNode[zr]();i&&(e.layout.endsWith("-tb")?t.children.push(createLine(e,[i])):t.children.push(i))}return 0===t.children.length?null:t}function addHTML(e,t,i){const a=e[Zr],r=a.availableSpace,[s,n,o,g]=i;switch(e.layout){case"position":a.width=Math.max(a.width,s+o);a.height=Math.max(a.height,n+g);a.children.push(t);break;case"lr-tb":case"rl-tb":if(!a.line||1===a.attempt){a.line=createLine(e,[]);a.children.push(a.line);a.numberInLine=0}a.numberInLine+=1;a.line.children.push(t);if(0===a.attempt){a.currentWidth+=o;a.height=Math.max(a.height,a.prevHeight+g)}else{a.currentWidth=o;a.prevHeight=a.height;a.height+=g;a.attempt=0}a.width=Math.max(a.width,a.currentWidth);break;case"rl-row":case"row":{a.children.push(t);a.width+=o;a.height=Math.max(a.height,g);const e=measureToString(a.height);for(const t of a.children)t.attributes.style.height=e;break}case"table":case"tb":a.width=Math.min(r.width,Math.max(a.width,o));a.height+=g;a.children.push(t)}}function getAvailableSpace(e){const t=e[Zr].availableSpace,i=e.margin?e.margin.topInset+e.margin.bottomInset:0,a=e.margin?e.margin.leftInset+e.margin.rightInset:0;switch(e.layout){case"lr-tb":case"rl-tb":return 0===e[Zr].attempt?{width:t.width-a-e[Zr].currentWidth,height:t.height-i-e[Zr].prevHeight}:{width:t.width-a,height:t.height-i-e[Zr].height};case"rl-row":case"row":return{width:e[Zr].columnWidths.slice(e[Zr].currentColumn).reduce(((e,t)=>e+t)),height:t.height-a};case"table":case"tb":return{width:t.width-a,height:t.height-i-e[Zr].height};default:return t}}function checkDimensions(e,t){if(null===e[hs]()[Zr].firstUnsplittable)return!0;if(0===e.w||0===e.h)return!0;const i=e[cs](),a=i[Zr]?.attempt||0,[,r,s,n]=function getTransformedBBox(e){let t,i,a=""===e.w?NaN:e.w,r=""===e.h?NaN:e.h,[s,n]=[0,0];switch(e.anchorType||""){case"bottomCenter":[s,n]=[a/2,r];break;case"bottomLeft":[s,n]=[0,r];break;case"bottomRight":[s,n]=[a,r];break;case"middleCenter":[s,n]=[a/2,r/2];break;case"middleLeft":[s,n]=[0,r/2];break;case"middleRight":[s,n]=[a,r/2];break;case"topCenter":[s,n]=[a/2,0];break;case"topRight":[s,n]=[a,0]}switch(e.rotate||0){case 0:[t,i]=[-s,-n];break;case 90:[t,i]=[-n,s];[a,r]=[r,-a];break;case 180:[t,i]=[s,n];[a,r]=[-a,-r];break;case 270:[t,i]=[n,-s];[a,r]=[-r,a]}return[e.x+t+Math.min(0,a),e.y+i+Math.min(0,r),Math.abs(a),Math.abs(r)]}(e);switch(i.layout){case"lr-tb":case"rl-tb":return 0===a?e[hs]()[Zr].noLayoutFailure?""!==e.w?Math.round(s-t.width)<=2:t.width>2:!(""!==e.h&&Math.round(n-t.height)>2)&&(""!==e.w?Math.round(s-t.width)<=2||0===i[Zr].numberInLine&&t.height>2:t.width>2):!!e[hs]()[Zr].noLayoutFailure||!(""!==e.h&&Math.round(n-t.height)>2)&&((""===e.w||Math.round(s-t.width)<=2||!i[bs]())&&t.height>2);case"table":case"tb":return!!e[hs]()[Zr].noLayoutFailure||(""===e.h||e[ws]()?(""===e.w||Math.round(s-t.width)<=2||!i[bs]())&&t.height>2:Math.round(n-t.height)<=2);case"position":if(e[hs]()[Zr].noLayoutFailure)return!0;if(""===e.h||Math.round(n+r-t.height)<=2)return!0;return n+r>e[hs]()[Zr].currentContentArea.h;case"rl-row":case"row":return!!e[hs]()[Zr].noLayoutFailure||(""===e.h||Math.round(n-t.height)<=2);default:return!0}}const Mn=An.template.id,Un="http://www.w3.org/2000/svg",xn=/^H(\d+)$/,Ln=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),Hn=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(e){if(!e||!e.border)return{w:0,h:0};const t=e.border[ss]();return t?{w:t.widths[0]+t.widths[2]+t.insets[0]+t.insets[2],h:t.widths[1]+t.widths[3]+t.insets[1]+t.insets[3]}:{w:0,h:0}}function hasMargin(e){return e.margin&&(e.margin.topInset||e.margin.rightInset||e.margin.bottomInset||e.margin.leftInset)}function _setValue(e,t){if(!e.value){const t=new Value({});e[Yr](t);e.value=t}e.value[Os](t)}function*getContainedChildren(e){for(const t of e[os]())t instanceof SubformSet?yield*t[gs]():yield t}function isRequired(e){return"error"===e.validate?.nullTest}function setTabIndex(e){for(;e;){if(!e.traversal){e[Ws]=e[ls]()[Ws];return}if(e[Ws])return;let t=null;for(const i of e.traversal[os]())if("next"===i.operation){t=i;break}if(!t||!t.ref){e[Ws]=e[ls]()[Ws];return}const i=e[hs]();e[Ws]=++i[Ws];const a=i[Ks](t.ref,e);if(!a)return;e=a[0]}}function applyAssist(e,t){const i=e.assist;if(i){const e=i[Vs]();e&&(t.title=e);const a=i.role.match(xn);if(a){const e="heading",i=a[1];t.role=e;t["aria-level"]=i}}if("table"===e.layout)t.role="table";else if("row"===e.layout)t.role="row";else{const i=e[ls]();"row"===i.layout&&(t.role="TH"===i.assist?.role?"columnheader":"cell")}}function ariaLabel(e){if(!e.assist)return null;const t=e.assist;return t.speak&&""!==t.speak[jr]?t.speak[jr]:t.toolTip?t.toolTip[jr]:null}function valueToHtml(e){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:e}]})}function setFirstUnsplittable(e){const t=e[hs]();if(null===t[Zr].firstUnsplittable){t[Zr].firstUnsplittable=e;t[Zr].noLayoutFailure=!0}}function unsetFirstUnsplittable(e){const t=e[hs]();t[Zr].firstUnsplittable===e&&(t[Zr].noLayoutFailure=!1)}function handleBreak(e){if(e[Zr])return!1;e[Zr]=Object.create(null);if("auto"===e.targetType)return!1;const t=e[hs]();let i=null;if(e.target){i=t[Ks](e.target,e[ls]());if(!i)return!1;i=i[0]}const{currentPageArea:a,currentContentArea:r}=t[Zr];if("pageArea"===e.targetType){i instanceof PageArea||(i=null);if(e.startNew){e[Zr].target=i||a;return!0}if(i&&i!==a){e[Zr].target=i;return!0}return!1}i instanceof ContentArea||(i=null);const s=i&&i[ls]();let n,o=s;if(e.startNew)if(i){const e=s.contentArea.children,t=e.indexOf(r),a=e.indexOf(i);-1!==t&&te;a[Zr].noLayoutFailure=!0;const n=t[Vs](i);e[vr](n.html,n.bbox);a[Zr].noLayoutFailure=r;t[cs]=s}class AppearanceFilter extends StringObject{constructor(e){super(Mn,"appearanceFilter");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Arc extends XFAObject{constructor(e){super(Mn,"arc",!0);this.circular=getInteger({data:e.circular,defaultValue:0,validate:e=>1===e});this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.startAngle=getFloat({data:e.startAngle,defaultValue:0,validate:e=>!0});this.sweepAngle=getFloat({data:e.sweepAngle,defaultValue:360,validate:e=>!0});this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null;this.fill=null}[Vs](){const e=this.edge||new Edge({}),t=e[_s](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[_s]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;let a;const r={xmlns:Un,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)a={name:"ellipse",attributes:{xmlns:Un,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:i}};else{const e=this.startAngle*Math.PI/180,t=this.sweepAngle*Math.PI/180,s=this.sweepAngle>180?1:0,[n,o,g,c]=[50*(1+Math.cos(e)),50*(1-Math.sin(e)),50*(1+Math.cos(e+t)),50*(1-Math.sin(e+t))];a={name:"path",attributes:{xmlns:Un,d:`M ${n} ${o} A 50 50 0 ${s} 0 ${g} ${c}`,vectorEffect:"non-scaling-stroke",style:i}};Object.assign(r,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const s={name:"svg",children:[a],attributes:r};if(hasMargin(this[ls]()[ls]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[s]});s.attributes.style.position="absolute";return HTMLResult.success(s)}}class Area extends XFAObject{constructor(e){super(Mn,"area",!0);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null;this.area=new XFAObjectArray;this.draw=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[gs](){yield*getContainedChildren(this)}[Ds](){return!0}[fs](){return!0}[vr](e,t){const[i,a,r,s]=t;this[Zr].width=Math.max(this[Zr].width,i+r);this[Zr].height=Math.max(this[Zr].height,a+s);this[Zr].children.push(e)}[es](){return this[Zr].availableSpace}[Vs](e){const t=toStyle(this,"position"),i={style:t,id:this[zs],class:["xfaArea"]};isPrintOnly(this)&&i.class.push("xfaPrintOnly");this.name&&(i.xfaName=this.name);const a=[];this[Zr]={children:a,width:0,height:0,availableSpace:e};const r=this[Kr]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!r.success){if(r.isBreak())return r;delete this[Zr];return HTMLResult.FAILURE}t.width=measureToString(this[Zr].width);t.height=measureToString(this[Zr].height);const s={name:"div",attributes:i,children:a},n=[this.x,this.y,this[Zr].width,this[Zr].height];delete this[Zr];return HTMLResult.success(s,n)}}class Assist extends XFAObject{constructor(e){super(Mn,"assist",!0);this.id=e.id||"";this.role=e.role||"";this.use=e.use||"";this.usehref=e.usehref||"";this.speak=null;this.toolTip=null}[Vs](){return this.toolTip?.[jr]||null}}class Barcode extends XFAObject{constructor(e){super(Mn,"barcode",!0);this.charEncoding=getKeyword({data:e.charEncoding?e.charEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.checksum=getStringOption(e.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]);this.dataColumnCount=getInteger({data:e.dataColumnCount,defaultValue:-1,validate:e=>e>=0});this.dataLength=getInteger({data:e.dataLength,defaultValue:-1,validate:e=>e>=0});this.dataPrep=getStringOption(e.dataPrep,["none","flateCompress"]);this.dataRowCount=getInteger({data:e.dataRowCount,defaultValue:-1,validate:e=>e>=0});this.endChar=e.endChar||"";this.errorCorrectionLevel=getInteger({data:e.errorCorrectionLevel,defaultValue:-1,validate:e=>e>=0&&e<=8});this.id=e.id||"";this.moduleHeight=getMeasurement(e.moduleHeight,"5mm");this.moduleWidth=getMeasurement(e.moduleWidth,"0.25mm");this.printCheckDigit=getInteger({data:e.printCheckDigit,defaultValue:0,validate:e=>1===e});this.rowColumnRatio=getRatio(e.rowColumnRatio);this.startChar=e.startChar||"";this.textLocation=getStringOption(e.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]);this.truncate=getInteger({data:e.truncate,defaultValue:0,validate:e=>1===e});this.type=getStringOption(e.type?e.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]);this.upsMode=getStringOption(e.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]);this.use=e.use||"";this.usehref=e.usehref||"";this.wideNarrowRatio=getRatio(e.wideNarrowRatio);this.encrypt=null;this.extras=null}}class Bind extends XFAObject{constructor(e){super(Mn,"bind",!0);this.match=getStringOption(e.match,["once","dataRef","global","none"]);this.ref=e.ref||"";this.picture=null}}class BindItems extends XFAObject{constructor(e){super(Mn,"bindItems");this.connection=e.connection||"";this.labelRef=e.labelRef||"";this.ref=e.ref||"";this.valueRef=e.valueRef||""}}class Bookend extends XFAObject{constructor(e){super(Mn,"bookend");this.id=e.id||"";this.leader=e.leader||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}}class BooleanElement extends Option01{constructor(e){super(Mn,"boolean");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Vs](e){return valueToHtml(1===this[jr]?"1":"0")}}class Border extends XFAObject{constructor(e){super(Mn,"border",!0);this.break=getStringOption(e.break,["close","open"]);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.extras=null;this.fill=null;this.margin=null}[ss](){if(!this[Zr]){const e=this.edge.children.slice();if(e.length<4){const t=e.at(-1)||new Edge({});for(let i=e.length;i<4;i++)e.push(t)}const t=e.map((e=>e.thickness)),i=[0,0,0,0];if(this.margin){i[0]=this.margin.topInset;i[1]=this.margin.rightInset;i[2]=this.margin.bottomInset;i[3]=this.margin.leftInset}this[Zr]={widths:t,insets:i,edges:e}}return this[Zr]}[_s](){const{edges:e}=this[ss](),t=e.map((e=>{const t=e[_s]();t.color||="#000000";return t})),i=Object.create(null);this.margin&&Object.assign(i,this.margin[_s]());"visible"===this.fill?.presence&&Object.assign(i,this.fill[_s]());if(this.corner.children.some((e=>0!==e.radius))){const e=this.corner.children.map((e=>e[_s]()));if(2===e.length||3===e.length){const t=e.at(-1);for(let i=e.length;i<4;i++)e.push(t)}i.borderRadius=e.map((e=>e.radius)).join(" ")}switch(this.presence){case"invisible":case"hidden":i.borderStyle="";break;case"inactive":i.borderStyle="none";break;default:i.borderStyle=t.map((e=>e.style)).join(" ")}i.borderWidth=t.map((e=>e.width)).join(" ");i.borderColor=t.map((e=>e.color)).join(" ");return i}}class Break extends XFAObject{constructor(e){super(Mn,"break",!0);this.after=getStringOption(e.after,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.afterTarget=e.afterTarget||"";this.before=getStringOption(e.before,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.beforeTarget=e.beforeTarget||"";this.bookendLeader=e.bookendLeader||"";this.bookendTrailer=e.bookendTrailer||"";this.id=e.id||"";this.overflowLeader=e.overflowLeader||"";this.overflowTarget=e.overflowTarget||"";this.overflowTrailer=e.overflowTrailer||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class BreakAfter extends XFAObject{constructor(e){super(Mn,"breakAfter",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}}class BreakBefore extends XFAObject{constructor(e){super(Mn,"breakBefore",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}[Vs](e){this[Zr]={};return HTMLResult.FAILURE}}class Button extends XFAObject{constructor(e){super(Mn,"button",!0);this.highlight=getStringOption(e.highlight,["inverted","none","outline","push"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Vs](e){const t=this[ls]()[ls](),i={name:"button",attributes:{id:this[zs],class:["xfaButton"],style:{}},children:[]};for(const e of t.event.children){if("click"!==e.activity||!e.script)continue;const t=recoverJsURL(e.script[jr]);if(!t)continue;const a=fixURL(t.url);a&&i.children.push({name:"a",attributes:{id:"link"+this[zs],href:a,newWindow:t.newWindow,class:["xfaLink"],style:{}},children:[]})}return HTMLResult.success(i)}}class Calculate extends XFAObject{constructor(e){super(Mn,"calculate",!0);this.id=e.id||"";this.override=getStringOption(e.override,["disabled","error","ignore","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.script=null}}class Caption extends XFAObject{constructor(e){super(Mn,"caption",!0);this.id=e.id||"";this.placement=getStringOption(e.placement,["left","bottom","inline","right","top"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.reserve=Math.ceil(getMeasurement(e.reserve));this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.font=null;this.margin=null;this.para=null;this.value=null}[Os](e){_setValue(this,e)}[ss](e){if(!this[Zr]){let{width:t,height:i}=e;switch(this.placement){case"left":case"right":case"inline":t=this.reserve<=0?t:this.reserve;break;case"top":case"bottom":i=this.reserve<=0?i:this.reserve}this[Zr]=layoutNode(this,{width:t,height:i})}return this[Zr]}[Vs](e){if(!this.value)return HTMLResult.EMPTY;this[Hs]();const t=this.value[Vs](e).html;if(!t){this[Ls]();return HTMLResult.EMPTY}const i=this.reserve;if(this.reserve<=0){const{w:t,h:i}=this[ss](e);switch(this.placement){case"left":case"right":case"inline":this.reserve=t;break;case"top":case"bottom":this.reserve=i}}const a=[];"string"==typeof t?a.push({name:"#text",value:t}):a.push(t);const r=toStyle(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(r.width=measureToString(this.reserve));break;case"top":case"bottom":this.reserve>0&&(r.height=measureToString(this.reserve))}setPara(this,null,t);this[Ls]();this.reserve=i;return HTMLResult.success({name:"div",attributes:{style:r,class:["xfaCaption"]},children:a})}}class Certificate extends StringObject{constructor(e){super(Mn,"certificate");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Certificates extends XFAObject{constructor(e){super(Mn,"certificates",!0);this.credentialServerPolicy=getStringOption(e.credentialServerPolicy,["optional","required"]);this.id=e.id||"";this.url=e.url||"";this.urlPolicy=e.urlPolicy||"";this.use=e.use||"";this.usehref=e.usehref||"";this.encryption=null;this.issuers=null;this.keyUsage=null;this.oids=null;this.signing=null;this.subjectDNs=null}}class CheckButton extends XFAObject{constructor(e){super(Mn,"checkButton",!0);this.id=e.id||"";this.mark=getStringOption(e.mark,["default","check","circle","cross","diamond","square","star"]);this.shape=getStringOption(e.shape,["square","round"]);this.size=getMeasurement(e.size,"10pt");this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Vs](e){const t=toStyle("margin"),i=measureToString(this.size);t.width=t.height=i;let a,r,s;const n=this[ls]()[ls](),o=n.items.children.length&&n.items.children[0][Vs]().html||[],g={on:(void 0!==o[0]?o[0]:"on").toString(),off:(void 0!==o[1]?o[1]:"off").toString()},c=(n.value?.[js]()||"off")===g.on||void 0,l=n[cs](),h=n[zs];let C;if(l instanceof ExclGroup){s=l[zs];a="radio";r="xfaRadio";C=l[Xr]?.[zs]||l[zs]}else{a="checkbox";r="xfaCheckbox";C=n[Xr]?.[zs]||n[zs]}const Q={name:"input",attributes:{class:[r],style:t,fieldId:h,dataId:C,type:a,checked:c,xfaOn:g.on,xfaOff:g.off,"aria-label":ariaLabel(n),"aria-required":!1}};s&&(Q.attributes.name=s);if(isRequired(n)){Q.attributes["aria-required"]=!0;Q.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[Q]})}}class ChoiceList extends XFAObject{constructor(e){super(Mn,"choiceList",!0);this.commitOn=getStringOption(e.commitOn,["select","exit"]);this.id=e.id||"";this.open=getStringOption(e.open,["userControl","always","multiSelect","onEntry"]);this.textEntry=getInteger({data:e.textEntry,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Vs](e){const t=toStyle(this,"border","margin"),i=this[ls]()[ls](),a={fontSize:`calc(${i.font?.size||10}px * var(--scale-factor))`},r=[];if(i.items.children.length>0){const e=i.items;let t=0,s=0;if(2===e.children.length){t=e.children[0].save;s=1-t}const n=e.children[t][Vs]().html,o=e.children[s][Vs]().html;let g=!1;const c=i.value?.[js]()||"";for(let e=0,t=n.length;eMath.min(Math.max(0,parseInt(e.trim(),10)),255))).map((e=>isNaN(e)?0:e));if(s.length<3)return{r:i,g:a,b:r};[i,a,r]=s;return{r:i,g:a,b:r}}(e.value):"";this.extras=null}[Bs](){return!1}[_s](){return this.value?Util.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class Comb extends XFAObject{constructor(e){super(Mn,"comb");this.id=e.id||"";this.numberOfCells=getInteger({data:e.numberOfCells,defaultValue:0,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||""}}class Connect extends XFAObject{constructor(e){super(Mn,"connect",!0);this.connection=e.connection||"";this.id=e.id||"";this.ref=e.ref||"";this.usage=getStringOption(e.usage,["exportAndImport","exportOnly","importOnly"]);this.use=e.use||"";this.usehref=e.usehref||"";this.picture=null}}class ContentArea extends XFAObject{constructor(e){super(Mn,"contentArea",!0);this.h=getMeasurement(e.h);this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=getMeasurement(e.w);this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null}[Vs](e){const t={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},i=["xfaContentarea"];isPrintOnly(this)&&i.push("xfaPrintOnly");return HTMLResult.success({name:"div",children:[],attributes:{style:t,class:i,id:this[zs]}})}}class Corner extends XFAObject{constructor(e){super(Mn,"corner",!0);this.id=e.id||"";this.inverted=getInteger({data:e.inverted,defaultValue:0,validate:e=>1===e});this.join=getStringOption(e.join,["square","round"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.radius=getMeasurement(e.radius);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[_s](){const e=toStyle(this,"visibility");e.radius=measureToString("square"===this.join?0:this.radius);return e}}class DateElement extends ContentObject{constructor(e){super(Mn,"date");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[_r](){const e=this[jr].trim();this[jr]=e?new Date(e):null}[Vs](e){return valueToHtml(this[jr]?this[jr].toString():"")}}class DateTime extends ContentObject{constructor(e){super(Mn,"dateTime");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[_r](){const e=this[jr].trim();this[jr]=e?new Date(e):null}[Vs](e){return valueToHtml(this[jr]?this[jr].toString():"")}}class DateTimeEdit extends XFAObject{constructor(e){super(Mn,"dateTimeEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.picker=getStringOption(e.picker,["host","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[Vs](e){const t=toStyle(this,"border","font","margin"),i=this[ls]()[ls](),a={name:"input",attributes:{type:"text",fieldId:i[zs],dataId:i[Xr]?.[zs]||i[zs],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Decimal extends ContentObject{constructor(e){super(Mn,"decimal");this.fracDigits=getInteger({data:e.fracDigits,defaultValue:2,validate:e=>!0});this.id=e.id||"";this.leadDigits=getInteger({data:e.leadDigits,defaultValue:-1,validate:e=>!0});this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[_r](){const e=parseFloat(this[jr].trim());this[jr]=isNaN(e)?null:e}[Vs](e){return valueToHtml(null!==this[jr]?this[jr].toString():"")}}class DefaultUi extends XFAObject{constructor(e){super(Mn,"defaultUi",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class Desc extends XFAObject{constructor(e){super(Mn,"desc",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(e){super(Mn,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class DigestMethods extends XFAObject{constructor(e){super(Mn,"digestMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(e){super(Mn,"draw",!0);this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.border=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.value=null;this.setProperty=new XFAObjectArray}[Os](e){_setValue(this,e)}[Vs](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this);this[Hs]();const t=this.w,i=this.h,{w:a,h:r,isBroken:s}=layoutNode(this,e);if(a&&""===this.w){if(s&&this[cs]()[bs]()){this[Ls]();return HTMLResult.FAILURE}this.w=a}r&&""===this.h&&(this.h=r);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=t;this.h=i;this[Ls]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const n=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");setMinMaxDimensions(this,n);if(n.margin){n.padding=n.margin;delete n.margin}const o=["xfaDraw"];this.font&&o.push("xfaFont");isPrintOnly(this)&&o.push("xfaPrintOnly");const g={style:n,id:this[zs],class:o};this.name&&(g.xfaName=this.name);const c={name:"div",attributes:g,children:[]};applyAssist(this,g);const l=computeBbox(this,c,e),h=this.value?this.value[Vs](e).html:null;if(null===h){this.w=t;this.h=i;this[Ls]();return HTMLResult.success(createWrapper(this,c),l)}c.children.push(h);setPara(this,n,h);this.w=t;this.h=i;this[Ls]();return HTMLResult.success(createWrapper(this,c),l)}}class Edge extends XFAObject{constructor(e){super(Mn,"edge",!0);this.cap=getStringOption(e.cap,["square","butt","round"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[_s](){const e=toStyle(this,"visibility");Object.assign(e,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[_s]():"#000000",style:""});if("visible"!==this.presence)e.style="none";else switch(this.stroke){case"solid":e.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":e.style="dashed";break;case"dotted":e.style="dotted";break;case"embossed":e.style="ridge";break;case"etched":e.style="groove";break;case"lowered":e.style="inset";break;case"raised":e.style="outset"}return e}}class Encoding extends OptionObject{constructor(e){super(Mn,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Encodings extends XFAObject{constructor(e){super(Mn,"encodings",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(e){super(Mn,"encrypt",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=null}}class EncryptData extends XFAObject{constructor(e){super(Mn,"encryptData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["encrypt","decrypt"]);this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Encryption extends XFAObject{constructor(e){super(Mn,"encryption",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(e){super(Mn,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EncryptionMethods extends XFAObject{constructor(e){super(Mn,"encryptionMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(e){super(Mn,"event",!0);this.activity=getStringOption(e.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]);this.id=e.id||"";this.listen=getStringOption(e.listen,["refOnly","refAndDescendents"]);this.name=e.name||"";this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.encryptData=null;this.execute=null;this.script=null;this.signData=null;this.submit=null}}class ExData extends ContentObject{constructor(e){super(Mn,"exData");this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.maxLength=getInteger({data:e.maxLength,defaultValue:-1,validate:e=>e>=-1});this.name=e.name||"";this.rid=e.rid||"";this.transferEncoding=getStringOption(e.transferEncoding,["none","base64","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[ds](){return"text/html"===this.contentType}[Gs](e){if("text/html"===this.contentType&&e[ks]===An.xhtml.id){this[jr]=e;return!0}if("text/xml"===this.contentType){this[jr]=e;return!0}return!1}[Vs](e){return"text/html"===this.contentType&&this[jr]?this[jr][Vs](e):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(e){super(Mn,"exObject",!0);this.archive=e.archive||"";this.classId=e.classId||"";this.codeBase=e.codeBase||"";this.codeType=e.codeType||"";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(e){super(Mn,"exclGroup",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.margin=null;this.para=null;this.traversal=null;this.validate=null;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.field=new XFAObjectArray;this.setProperty=new XFAObjectArray}[fs](){return!0}[Bs](){return!0}[Os](e){for(const t of this.field.children){if(!t.value){const e=new Value({});t[Yr](e);t.value=e}t.value[Os](e)}}[bs](){return this.layout.endsWith("-tb")&&0===this[Zr].attempt&&this[Zr].numberInLine>0||this[ls]()[bs]()}[ws](){const e=this[cs]();if(!e[ws]())return!1;if(void 0!==this[Zr]._isSplittable)return this[Zr]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Zr]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Zr].numberInLine)return!1;this[Zr]._isSplittable=!0;return!0}[zr](){return flushHTML(this)}[vr](e,t){addHTML(this,e,t)}[es](){return getAvailableSpace(this)}[Vs](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[zs],class:[]};setAccess(this,i.class);this[Zr]||(this[Zr]=Object.create(null));Object.assign(this[Zr],{children:t,attributes:i,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[ws]();a||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const r=new Set(["field"]);if(this.layout.includes("row")){const e=this[cs]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Zr].columnWidths=e;this[Zr].currentColumn=0}}const s=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),n=["xfaExclgroup"],o=layoutClass(this);o&&n.push(o);isPrintOnly(this)&&n.push("xfaPrintOnly");i.style=s;i.class=n;this.name&&(i.xfaName=this.name);this[Hs]();const g="lr-tb"===this.layout||"rl-tb"===this.layout,c=g?2:1;for(;this[Zr].attempte>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.format=null;this.items=new XFAObjectArray(2);this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.validate=null;this.value=null;this.bindItems=new XFAObjectArray;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.setProperty=new XFAObjectArray}[fs](){return!0}[Os](e){_setValue(this,e)}[Vs](e){setTabIndex(this);if(!this.ui){this.ui=new Ui({});this.ui[Cs]=this[Cs];this[Yr](this.ui);let e;switch(this.items.children.length){case 0:e=new TextEdit({});this.ui.textEdit=e;break;case 1:e=new CheckButton({});this.ui.checkButton=e;break;case 2:e=new ChoiceList({});this.ui.choiceList=e}this.ui[Yr](e)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[Zr];this[Hs]();const t=this.caption?this.caption[Vs](e).html:null,i=this.w,a=this.h;let r=0,s=0;if(this.margin){r=this.margin.leftInset+this.margin.rightInset;s=this.margin.topInset+this.margin.bottomInset}let n=null;if(""===this.w||""===this.h){let t=null,i=null,a=0,o=0;if(this.ui.checkButton)a=o=this.ui.checkButton.size;else{const{w:t,h:i}=layoutNode(this,e);if(null!==t){a=t;o=i}else o=function fonts_getMetrics(e,t=!1){let i=null;if(e){const t=stripQuotes(e.typeface),a=e[Cs].fontFinder.find(t);i=selectFont(e,a)}if(!i)return{lineHeight:12,lineGap:2,lineNoGap:10};const a=e.size||10,r=i.lineHeight?Math.max(t?0:1.2,i.lineHeight):1.2,s=void 0===i.lineGap?.2:i.lineGap;return{lineHeight:r*a,lineGap:s*a,lineNoGap:Math.max(1,r-s)*a}}(this.font,!0).lineNoGap}n=getBorderDims(this.ui[ss]());a+=n.w;o+=n.h;if(this.caption){const{w:r,h:s,isBroken:n}=this.caption[ss](e);if(n&&this[cs]()[bs]()){this[Ls]();return HTMLResult.FAILURE}t=r;i=s;switch(this.caption.placement){case"left":case"right":case"inline":t+=a;break;case"top":case"bottom":i+=o}}else{t=a;i=o}if(t&&""===this.w){t+=r;this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1e>=1&&e<=5});this.appearanceFilter=null;this.certificates=null;this.digestMethods=null;this.encodings=null;this.encryptionMethods=null;this.handler=null;this.lockDocument=null;this.mdp=null;this.reasons=null;this.timeStamp=null}}class Float extends ContentObject{constructor(e){super(Mn,"float");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[_r](){const e=parseFloat(this[jr].trim());this[jr]=isNaN(e)?null:e}[Vs](e){return valueToHtml(null!==this[jr]?this[jr].toString():"")}}class template_Font extends XFAObject{constructor(e){super(Mn,"font",!0);this.baselineShift=getMeasurement(e.baselineShift);this.fontHorizontalScale=getFloat({data:e.fontHorizontalScale,defaultValue:100,validate:e=>e>=0});this.fontVerticalScale=getFloat({data:e.fontVerticalScale,defaultValue:100,validate:e=>e>=0});this.id=e.id||"";this.kerningMode=getStringOption(e.kerningMode,["none","pair"]);this.letterSpacing=getMeasurement(e.letterSpacing,"0");this.lineThrough=getInteger({data:e.lineThrough,defaultValue:0,validate:e=>1===e||2===e});this.lineThroughPeriod=getStringOption(e.lineThroughPeriod,["all","word"]);this.overline=getInteger({data:e.overline,defaultValue:0,validate:e=>1===e||2===e});this.overlinePeriod=getStringOption(e.overlinePeriod,["all","word"]);this.posture=getStringOption(e.posture,["normal","italic"]);this.size=getMeasurement(e.size,"10pt");this.typeface=e.typeface||"Courier";this.underline=getInteger({data:e.underline,defaultValue:0,validate:e=>1===e||2===e});this.underlinePeriod=getStringOption(e.underlinePeriod,["all","word"]);this.use=e.use||"";this.usehref=e.usehref||"";this.weight=getStringOption(e.weight,["normal","bold"]);this.extras=null;this.fill=null}[Tr](e){super[Tr](e);this[Cs].usedTypefaces.add(this.typeface)}[_s](){const e=toStyle(this,"fill"),t=e.color;if(t)if("#000000"===t)delete e.color;else if(!t.startsWith("#")){e.background=t;e.backgroundClip="text";e.color="transparent"}this.baselineShift&&(e.verticalAlign=measureToString(this.baselineShift));e.fontKerning="none"===this.kerningMode?"none":"normal";e.letterSpacing=measureToString(this.letterSpacing);if(0!==this.lineThrough){e.textDecoration="line-through";2===this.lineThrough&&(e.textDecorationStyle="double")}if(0!==this.overline){e.textDecoration="overline";2===this.overline&&(e.textDecorationStyle="double")}e.fontStyle=this.posture;e.fontSize=measureToString(.99*this.size);setFontFamily(this,this,this[Cs].fontFinder,e);if(0!==this.underline){e.textDecoration="underline";2===this.underline&&(e.textDecorationStyle="double")}e.fontWeight=this.weight;return e}}class Format extends XFAObject{constructor(e){super(Mn,"format",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null}}class Handler extends StringObject{constructor(e){super(Mn,"handler");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Hyphenation extends XFAObject{constructor(e){super(Mn,"hyphenation");this.excludeAllCaps=getInteger({data:e.excludeAllCaps,defaultValue:0,validate:e=>1===e});this.excludeInitialCap=getInteger({data:e.excludeInitialCap,defaultValue:0,validate:e=>1===e});this.hyphenate=getInteger({data:e.hyphenate,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.pushCharacterCount=getInteger({data:e.pushCharacterCount,defaultValue:3,validate:e=>e>=0});this.remainCharacterCount=getInteger({data:e.remainCharacterCount,defaultValue:3,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||"";this.wordCharacterCount=getInteger({data:e.wordCharacterCount,defaultValue:7,validate:e=>e>=0})}}class Image extends StringObject{constructor(e){super(Mn,"image");this.aspect=getStringOption(e.aspect,["fit","actual","height","none","width"]);this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.name=e.name||"";this.transferEncoding=getStringOption(e.transferEncoding,["base64","none","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[Vs](){if(this.contentType&&!Ln.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let e=this[Cs].images&&this[Cs].images.get(this.href);if(!e&&(this.href||!this[jr]))return HTMLResult.EMPTY;e||"base64"!==this.transferEncoding||(e=function fromBase64Util(e){return Uint8Array.fromBase64?Uint8Array.fromBase64(e):stringToBytes(atob(e))}(this[jr]));if(!e)return HTMLResult.EMPTY;if(!this.contentType){for(const[t,i]of Hn)if(e.length>t.length&&t.every(((t,i)=>t===e[i]))){this.contentType=i;break}if(!this.contentType)return HTMLResult.EMPTY}const t=new Blob([e],{type:this.contentType});let i;switch(this.aspect){case"fit":case"actual":break;case"height":i={height:"100%",objectFit:"fill"};break;case"none":i={width:"100%",height:"100%",objectFit:"fill"};break;case"width":i={width:"100%",objectFit:"fill"}}const a=this[ls]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:i,src:URL.createObjectURL(t),alt:a?ariaLabel(a[ls]()):null}})}}class ImageEdit extends XFAObject{constructor(e){super(Mn,"imageEdit",!0);this.data=getStringOption(e.data,["link","embed"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Vs](e){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(e){super(Mn,"integer");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[_r](){const e=parseInt(this[jr].trim(),10);this[jr]=isNaN(e)?null:e}[Vs](e){return valueToHtml(null!==this[jr]?this[jr].toString():"")}}class Issuers extends XFAObject{constructor(e){super(Mn,"issuers",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(e){super(Mn,"items",!0);this.id=e.id||"";this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.ref=e.ref||"";this.save=getInteger({data:e.save,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Vs](){const e=[];for(const t of this[os]())e.push(t[js]());return HTMLResult.success(e)}}class Keep extends XFAObject{constructor(e){super(Mn,"keep",!0);this.id=e.id||"";const t=["none","contentArea","pageArea"];this.intact=getStringOption(e.intact,t);this.next=getStringOption(e.next,t);this.previous=getStringOption(e.previous,t);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class KeyUsage extends XFAObject{constructor(e){super(Mn,"keyUsage");const t=["","yes","no"];this.crlSign=getStringOption(e.crlSign,t);this.dataEncipherment=getStringOption(e.dataEncipherment,t);this.decipherOnly=getStringOption(e.decipherOnly,t);this.digitalSignature=getStringOption(e.digitalSignature,t);this.encipherOnly=getStringOption(e.encipherOnly,t);this.id=e.id||"";this.keyAgreement=getStringOption(e.keyAgreement,t);this.keyCertSign=getStringOption(e.keyCertSign,t);this.keyEncipherment=getStringOption(e.keyEncipherment,t);this.nonRepudiation=getStringOption(e.nonRepudiation,t);this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Line extends XFAObject{constructor(e){super(Mn,"line",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.slope=getStringOption(e.slope,["\\","/"]);this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null}[Vs](){const e=this[ls]()[ls](),t=this.edge||new Edge({}),i=t[_s](),a=Object.create(null),r="visible"===t.presence?t.thickness:0;a.strokeWidth=measureToString(r);a.stroke=i.color;let s,n,o,g,c="100%",l="100%";if(e.w<=r){[s,n,o,g]=["50%",0,"50%","100%"];c=a.strokeWidth}else if(e.h<=r){[s,n,o,g]=[0,"50%","100%","50%"];l=a.strokeWidth}else"\\"===this.slope?[s,n,o,g]=[0,0,"100%","100%"]:[s,n,o,g]=[0,"100%","100%",0];const h={name:"svg",children:[{name:"line",attributes:{xmlns:Un,x1:s,y1:n,x2:o,y2:g,style:a}}],attributes:{xmlns:Un,width:c,height:l,style:{overflow:"visible"}}};if(hasMargin(e))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[h]});h.attributes.style.position="absolute";return HTMLResult.success(h)}}class Linear extends XFAObject{constructor(e){super(Mn,"linear",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toRight","toBottom","toLeft","toTop"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[_s](e){e=e?e[_s]():"#FFFFFF";return`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${e}, ${this.color?this.color[_s]():"#000000"})`}}class LockDocument extends ContentObject{constructor(e){super(Mn,"lockDocument");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}[_r](){this[jr]=getStringOption(this[jr],["auto","0","1"])}}class Manifest extends XFAObject{constructor(e){super(Mn,"manifest",!0);this.action=getStringOption(e.action,["include","all","exclude"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(e){super(Mn,"margin",!0);this.bottomInset=getMeasurement(e.bottomInset,"0");this.id=e.id||"";this.leftInset=getMeasurement(e.leftInset,"0");this.rightInset=getMeasurement(e.rightInset,"0");this.topInset=getMeasurement(e.topInset,"0");this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[_s](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(e){super(Mn,"mdp");this.id=e.id||"";this.permissions=getInteger({data:e.permissions,defaultValue:2,validate:e=>1===e||3===e});this.signatureType=getStringOption(e.signatureType,["filler","author"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Medium extends XFAObject{constructor(e){super(Mn,"medium");this.id=e.id||"";this.imagingBBox=function getBBox(e){const t=-1;if(!e)return{x:t,y:t,width:t,height:t};const i=e.trim().split(/\s*,\s*/).map((e=>getMeasurement(e,"-1")));if(i.length<4||i[2]<0||i[3]<0)return{x:t,y:t,width:t,height:t};const[a,r,s,n]=i;return{x:a,y:r,width:s,height:n}}(e.imagingBBox);this.long=getMeasurement(e.long);this.orientation=getStringOption(e.orientation,["portrait","landscape"]);this.short=getMeasurement(e.short);this.stock=e.stock||"";this.trayIn=getStringOption(e.trayIn,["auto","delegate","pageFront"]);this.trayOut=getStringOption(e.trayOut,["auto","delegate"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Message extends XFAObject{constructor(e){super(Mn,"message",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(e){super(Mn,"numericEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[Vs](e){const t=toStyle(this,"border","font","margin"),i=this[ls]()[ls](),a={name:"input",attributes:{type:"text",fieldId:i[zs],dataId:i[Xr]?.[zs]||i[zs],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(i),"aria-required":!1}};if(isRequired(i)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Occur extends XFAObject{constructor(e){super(Mn,"occur",!0);this.id=e.id||"";this.initial=""!==e.initial?getInteger({data:e.initial,defaultValue:"",validate:e=>!0}):"";this.max=""!==e.max?getInteger({data:e.max,defaultValue:1,validate:e=>!0}):"";this.min=""!==e.min?getInteger({data:e.min,defaultValue:1,validate:e=>!0}):"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Tr](){const e=this[ls](),t=this.min;""===this.min&&(this.min=e instanceof PageArea||e instanceof PageSet?0:1);""===this.max&&(this.max=""===t?e instanceof PageArea||e instanceof PageSet?-1:1:this.min);-1!==this.max&&this.max!0});this.name=e.name||"";this.numbered=getInteger({data:e.numbered,defaultValue:1,validate:e=>!0});this.oddOrEven=getStringOption(e.oddOrEven,["any","even","odd"]);this.pagePosition=getStringOption(e.pagePosition,["any","first","last","only","rest"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.desc=null;this.extras=null;this.medium=null;this.occur=null;this.area=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.draw=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray}[Fs](){if(!this[Zr]){this[Zr]={numberOfUse:0};return!0}return!this.occur||-1===this.occur.max||this[Zr].numberOfUsee.oddOrEven===t&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&e.pagePosition===i));if(a)return a;a=this.pageArea.children.find((e=>"any"===e.oddOrEven&&"any"===e.pagePosition));return a||this.pageArea.children[0]}}class Para extends XFAObject{constructor(e){super(Mn,"para",!0);this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.lineHeight=e.lineHeight?getMeasurement(e.lineHeight,"0pt"):"";this.marginLeft=e.marginLeft?getMeasurement(e.marginLeft,"0pt"):"";this.marginRight=e.marginRight?getMeasurement(e.marginRight,"0pt"):"";this.orphans=getInteger({data:e.orphans,defaultValue:0,validate:e=>e>=0});this.preserve=e.preserve||"";this.radixOffset=e.radixOffset?getMeasurement(e.radixOffset,"0pt"):"";this.spaceAbove=e.spaceAbove?getMeasurement(e.spaceAbove,"0pt"):"";this.spaceBelow=e.spaceBelow?getMeasurement(e.spaceBelow,"0pt"):"";this.tabDefault=e.tabDefault?getMeasurement(this.tabDefault):"";this.tabStops=(e.tabStops||"").trim().split(/\s+/).map(((e,t)=>t%2==1?getMeasurement(e):e));this.textIndent=e.textIndent?getMeasurement(e.textIndent,"0pt"):"";this.use=e.use||"";this.usehref=e.usehref||"";this.vAlign=getStringOption(e.vAlign,["top","bottom","middle"]);this.widows=getInteger({data:e.widows,defaultValue:0,validate:e=>e>=0});this.hyphenation=null}[_s](){const e=toStyle(this,"hAlign");""!==this.marginLeft&&(e.paddingLeft=measureToString(this.marginLeft));""!==this.marginRight&&(e.paddingRight=measureToString(this.marginRight));""!==this.spaceAbove&&(e.paddingTop=measureToString(this.spaceAbove));""!==this.spaceBelow&&(e.paddingBottom=measureToString(this.spaceBelow));if(""!==this.textIndent){e.textIndent=measureToString(this.textIndent);fixTextIndent(e)}this.lineHeight>0&&(e.lineHeight=measureToString(this.lineHeight));""!==this.tabDefault&&(e.tabSize=measureToString(this.tabDefault));this.tabStops.length;this.hyphenatation&&Object.assign(e,this.hyphenatation[_s]());return e}}class PasswordEdit extends XFAObject{constructor(e){super(Mn,"passwordEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.passwordChar=e.passwordChar||"*";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}}class template_Pattern extends XFAObject{constructor(e){super(Mn,"pattern",!0);this.id=e.id||"";this.type=getStringOption(e.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[_s](e){e=e?e[_s]():"#FFFFFF";const t=this.color?this.color[_s]():"#000000",i="repeating-linear-gradient",a=`${e},${e} 5px,${t} 5px,${t} 10px`;switch(this.type){case"crossHatch":return`${i}(to top,${a}) ${i}(to right,${a})`;case"crossDiagonal":return`${i}(45deg,${a}) ${i}(-45deg,${a})`;case"diagonalLeft":return`${i}(45deg,${a})`;case"diagonalRight":return`${i}(-45deg,${a})`;case"horizontal":return`${i}(to top,${a})`;case"vertical":return`${i}(to right,${a})`}return""}}class Picture extends StringObject{constructor(e){super(Mn,"picture");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Proto extends XFAObject{constructor(e){super(Mn,"proto",!0);this.appearanceFilter=new XFAObjectArray;this.arc=new XFAObjectArray;this.area=new XFAObjectArray;this.assist=new XFAObjectArray;this.barcode=new XFAObjectArray;this.bindItems=new XFAObjectArray;this.bookend=new XFAObjectArray;this.boolean=new XFAObjectArray;this.border=new XFAObjectArray;this.break=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.button=new XFAObjectArray;this.calculate=new XFAObjectArray;this.caption=new XFAObjectArray;this.certificate=new XFAObjectArray;this.certificates=new XFAObjectArray;this.checkButton=new XFAObjectArray;this.choiceList=new XFAObjectArray;this.color=new XFAObjectArray;this.comb=new XFAObjectArray;this.connect=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.corner=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.dateTimeEdit=new XFAObjectArray;this.decimal=new XFAObjectArray;this.defaultUi=new XFAObjectArray;this.desc=new XFAObjectArray;this.digestMethod=new XFAObjectArray;this.digestMethods=new XFAObjectArray;this.draw=new XFAObjectArray;this.edge=new XFAObjectArray;this.encoding=new XFAObjectArray;this.encodings=new XFAObjectArray;this.encrypt=new XFAObjectArray;this.encryptData=new XFAObjectArray;this.encryption=new XFAObjectArray;this.encryptionMethod=new XFAObjectArray;this.encryptionMethods=new XFAObjectArray;this.event=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.execute=new XFAObjectArray;this.extras=new XFAObjectArray;this.field=new XFAObjectArray;this.fill=new XFAObjectArray;this.filter=new XFAObjectArray;this.float=new XFAObjectArray;this.font=new XFAObjectArray;this.format=new XFAObjectArray;this.handler=new XFAObjectArray;this.hyphenation=new XFAObjectArray;this.image=new XFAObjectArray;this.imageEdit=new XFAObjectArray;this.integer=new XFAObjectArray;this.issuers=new XFAObjectArray;this.items=new XFAObjectArray;this.keep=new XFAObjectArray;this.keyUsage=new XFAObjectArray;this.line=new XFAObjectArray;this.linear=new XFAObjectArray;this.lockDocument=new XFAObjectArray;this.manifest=new XFAObjectArray;this.margin=new XFAObjectArray;this.mdp=new XFAObjectArray;this.medium=new XFAObjectArray;this.message=new XFAObjectArray;this.numericEdit=new XFAObjectArray;this.occur=new XFAObjectArray;this.oid=new XFAObjectArray;this.oids=new XFAObjectArray;this.overflow=new XFAObjectArray;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray;this.para=new XFAObjectArray;this.passwordEdit=new XFAObjectArray;this.pattern=new XFAObjectArray;this.picture=new XFAObjectArray;this.radial=new XFAObjectArray;this.reason=new XFAObjectArray;this.reasons=new XFAObjectArray;this.rectangle=new XFAObjectArray;this.ref=new XFAObjectArray;this.script=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.signData=new XFAObjectArray;this.signature=new XFAObjectArray;this.signing=new XFAObjectArray;this.solid=new XFAObjectArray;this.speak=new XFAObjectArray;this.stipple=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray;this.subjectDN=new XFAObjectArray;this.subjectDNs=new XFAObjectArray;this.submit=new XFAObjectArray;this.text=new XFAObjectArray;this.textEdit=new XFAObjectArray;this.time=new XFAObjectArray;this.timeStamp=new XFAObjectArray;this.toolTip=new XFAObjectArray;this.traversal=new XFAObjectArray;this.traverse=new XFAObjectArray;this.ui=new XFAObjectArray;this.validate=new XFAObjectArray;this.value=new XFAObjectArray;this.variables=new XFAObjectArray}}class Radial extends XFAObject{constructor(e){super(Mn,"radial",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toEdge","toCenter"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[_s](e){e=e?e[_s]():"#FFFFFF";const t=this.color?this.color[_s]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${e},${t}`:`${t},${e}`})`}}class Reason extends StringObject{constructor(e){super(Mn,"reason");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Reasons extends XFAObject{constructor(e){super(Mn,"reasons",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.reason=new XFAObjectArray}}class Rectangle extends XFAObject{constructor(e){super(Mn,"rectangle",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.fill=null}[Vs](){const e=this.edge.children.length?this.edge.children[0]:new Edge({}),t=e[_s](),i=Object.create(null);"visible"===this.fill?.presence?Object.assign(i,this.fill[_s]()):i.fill="transparent";i.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);i.stroke=t.color;const a=(this.corner.children.length?this.corner.children[0]:new Corner({}))[_s](),r={name:"svg",children:[{name:"rect",attributes:{xmlns:Un,width:"100%",height:"100%",x:0,y:0,rx:a.radius,ry:a.radius,style:i}}],attributes:{xmlns:Un,style:{overflow:"visible"},width:"100%",height:"100%"}};if(hasMargin(this[ls]()[ls]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[r]});r.attributes.style.position="absolute";return HTMLResult.success(r)}}class RefElement extends StringObject{constructor(e){super(Mn,"ref");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Script extends StringObject{constructor(e){super(Mn,"script");this.binding=e.binding||"";this.contentType=e.contentType||"";this.id=e.id||"";this.name=e.name||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class SetProperty extends XFAObject{constructor(e){super(Mn,"setProperty");this.connection=e.connection||"";this.ref=e.ref||"";this.target=e.target||""}}class SignData extends XFAObject{constructor(e){super(Mn,"signData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["sign","clear","verify"]);this.ref=e.ref||"";this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Signature extends XFAObject{constructor(e){super(Mn,"signature",!0);this.id=e.id||"";this.type=getStringOption(e.type,["PDF1.3","PDF1.6"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.filter=null;this.manifest=null;this.margin=null}}class Signing extends XFAObject{constructor(e){super(Mn,"signing",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Solid extends XFAObject{constructor(e){super(Mn,"solid",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[_s](e){return e?e[_s]():"#FFFFFF"}}class Speak extends StringObject{constructor(e){super(Mn,"speak");this.disable=getInteger({data:e.disable,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.priority=getStringOption(e.priority,["custom","caption","name","toolTip"]);this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Stipple extends XFAObject{constructor(e){super(Mn,"stipple",!0);this.id=e.id||"";this.rate=getInteger({data:e.rate,defaultValue:50,validate:e=>e>=0&&e<=100});this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[_s](e){const t=this.rate/100;return Util.makeHexColor(Math.round(e.value.r*(1-t)+this.value.r*t),Math.round(e.value.g*(1-t)+this.value.g*t),Math.round(e.value.b*(1-t)+this.value.b*t))}}class Subform extends XFAObject{constructor(e){super(Mn,"subform",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.allowMacro=getInteger({data:e.allowMacro,defaultValue:0,validate:e=>1===e});this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.columnWidths=(e.columnWidths||"").trim().split(/\s+/).map((e=>"-1"===e?-1:getMeasurement(e)));this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.mergeMode=getStringOption(e.mergeMode,["consumeData","matchTemplate"]);this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.restoreState=getStringOption(e.restoreState,["manual","auto"]);this.scope=getStringOption(e.scope,["name","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.bookend=null;this.border=null;this.break=null;this.calculate=null;this.desc=null;this.extras=null;this.keep=null;this.margin=null;this.occur=null;this.overflow=null;this.pageSet=null;this.para=null;this.traversal=null;this.validate=null;this.variables=null;this.area=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.connect=new XFAObjectArray;this.draw=new XFAObjectArray;this.event=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.proto=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}[cs](){const e=this[ls]();return e instanceof SubformSet?e[cs]():e}[fs](){return!0}[bs](){return this.layout.endsWith("-tb")&&0===this[Zr].attempt&&this[Zr].numberInLine>0||this[ls]()[bs]()}*[gs](){yield*getContainedChildren(this)}[zr](){return flushHTML(this)}[vr](e,t){addHTML(this,e,t)}[es](){return getAvailableSpace(this)}[ws](){const e=this[cs]();if(!e[ws]())return!1;if(void 0!==this[Zr]._isSplittable)return this[Zr]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Zr]._isSplittable=!1;return!1}if(this.keep&&"none"!==this.keep.intact){this[Zr]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Zr].numberInLine)return!1;this[Zr]._isSplittable=!0;return!0}[Vs](e){setTabIndex(this);if(this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const e=new BreakAfter({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});e[Cs]=this[Cs];this[Yr](e);this.breakAfter.push(e)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const e=new BreakBefore({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});e[Cs]=this[Cs];this[Yr](e);this.breakBefore.push(e)}if(""!==this.break.overflowTarget){const e=new Overflow({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});e[Cs]=this[Cs];this[Yr](e);this.overflow.push(e)}this[Js](this.break);this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;(this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&warn("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");if(this.breakBefore.children.length>=1){const e=this.breakBefore.children[0];if(handleBreak(e))return HTMLResult.breakNode(e)}if(this[Zr]?.afterBreakAfter)return HTMLResult.EMPTY;fixDimensions(this);const t=[],i={id:this[zs],class:[]};setAccess(this,i.class);this[Zr]||(this[Zr]=Object.create(null));Object.assign(this[Zr],{children:t,line:null,attributes:i,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const a=this[hs](),r=a[Zr].noLayoutFailure,s=this[ws]();s||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const n=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const e=this[cs]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Zr].columnWidths=e;this[Zr].currentColumn=0}}const o=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),g=["xfaSubform"],c=layoutClass(this);c&&g.push(c);i.style=o;i.class=g;this.name&&(i.xfaName=this.name);if(this.overflow){const t=this.overflow[ss]();if(t.addLeader){t.addLeader=!1;handleOverflow(this,t.leader,e)}}this[Hs]();const l="lr-tb"===this.layout||"rl-tb"===this.layout,h=l?2:1;for(;this[Zr].attempt=1){const e=this.breakAfter.children[0];if(handleBreak(e)){this[Zr].afterBreakAfter=p;return HTMLResult.breakNode(e)}}delete this[Zr];return p}}class SubformSet extends XFAObject{constructor(e){super(Mn,"subformSet",!0);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["ordered","choice","unordered"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.bookend=null;this.break=null;this.desc=null;this.extras=null;this.occur=null;this.overflow=null;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[gs](){yield*getContainedChildren(this)}[cs](){let e=this[ls]();for(;!(e instanceof Subform);)e=e[ls]();return e}[fs](){return!0}}class SubjectDN extends ContentObject{constructor(e){super(Mn,"subjectDN");this.delimiter=e.delimiter||",";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[_r](){this[jr]=new Map(this[jr].split(this.delimiter).map((e=>{(e=e.split("=",2))[0]=e[0].trim();return e})))}}class SubjectDNs extends XFAObject{constructor(e){super(Mn,"subjectDNs",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(e){super(Mn,"submit",!0);this.embedPDF=getInteger({data:e.embedPDF,defaultValue:0,validate:e=>1===e});this.format=getStringOption(e.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]);this.id=e.id||"";this.target=e.target||"";this.textEncoding=getKeyword({data:e.textEncoding?e.textEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.use=e.use||"";this.usehref=e.usehref||"";this.xdpContent=e.xdpContent||"";this.encrypt=null;this.encryptData=new XFAObjectArray;this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(e){super(Mn,"template",!0);this.baseProfile=getStringOption(e.baseProfile,["full","interactiveForms"]);this.extras=null;this.subform=new XFAObjectArray}[_r](){0===this.subform.children.length&&warn("XFA - No subforms in template node.");this.subform.children.length>=2&&warn("XFA - Several subforms in template node: please file a bug.");this[Ws]=5e3}[ws](){return!0}[Ks](e,t){return e.startsWith("#")?[this[Qs].get(e.slice(1))]:searchNode(this,t,e,!0,!0)}*[Xs](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[Zr]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const e=this.subform.children[0];e.pageSet[qr]();const t=e.pageSet.pageArea.children,i={name:"div",children:[]};let a=null,r=null,s=null;if(e.breakBefore.children.length>=1){r=e.breakBefore.children[0];s=r.target}else if(e.subform.children.length>=1&&e.subform.children[0].breakBefore.children.length>=1){r=e.subform.children[0].breakBefore.children[0];s=r.target}else if(e.break?.beforeTarget){r=e.break;s=r.beforeTarget}else if(e.subform.children.length>=1&&e.subform.children[0].break?.beforeTarget){r=e.subform.children[0].break;s=r.beforeTarget}if(r){const e=this[Ks](s,r[ls]());if(e instanceof PageArea){a=e;r[Zr]={}}}a||(a=t[0]);a[Zr]={numberOfUse:1};const n=a[ls]();n[Zr]={numberOfUse:1,pageIndex:n.pageArea.children.indexOf(a),pageSetIndex:0};let o,g=null,c=null,l=!0,h=0,C=0;for(;;){if(l)h=0;else{i.children.pop();if(3==++h){warn("XFA - Something goes wrong: please file a bug.");return i}}o=null;this[Zr].currentPageArea=a;const t=a[Vs]().html;i.children.push(t);if(g){this[Zr].noLayoutFailure=!0;t.children.push(g[Vs](a[Zr].space).html);g=null}if(c){this[Zr].noLayoutFailure=!0;t.children.push(c[Vs](a[Zr].space).html);c=null}const r=a.contentArea.children,s=t.children.filter((e=>e.attributes.class.includes("xfaContentarea")));l=!1;this[Zr].firstUnsplittable=null;this[Zr].noLayoutFailure=!1;const flush=t=>{const i=e[zr]();if(i){l||=i.children?.length>0;s[t].children.push(i)}};for(let t=C,a=r.length;t0;s[t].children.push(h.html)}else!l&&i.children.length>1&&i.children.pop();return i}if(h.isBreak()){const e=h.breakNode;flush(t);if("auto"===e.targetType)continue;if(e.leader){g=this[Ks](e.leader,e[ls]());g=g?g[0]:null}if(e.trailer){c=this[Ks](e.trailer,e[ls]());c=c?c[0]:null}if("pageArea"===e.targetType){o=e[Zr].target;t=1/0}else if(e[Zr].target){o=e[Zr].target;C=e[Zr].index+1;t=1/0}else t=e[Zr].index}else if(this[Zr].overflowNode){const e=this[Zr].overflowNode;this[Zr].overflowNode=null;const i=e[ss](),a=i.target;i.addLeader=null!==i.leader;i.addTrailer=null!==i.trailer;flush(t);const s=t;t=1/0;if(a instanceof PageArea)o=a;else if(a instanceof ContentArea){const e=r.indexOf(a);if(-1!==e)e>s?t=e-1:C=e;else{o=a[ls]();C=o.contentArea.children.indexOf(a)}}}else flush(t)}this[Zr].pageNumber+=1;o&&(o[Fs]()?o[Zr].numberOfUse+=1:o=null);a=o||a[Is]();yield null}}}class Text extends ContentObject{constructor(e){super(Mn,"text");this.id=e.id||"";this.maxChars=getInteger({data:e.maxChars,defaultValue:0,validate:e=>e>=0});this.name=e.name||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}[Jr](){return!0}[Gs](e){if(e[ks]===An.xhtml.id){this[jr]=e;return!0}warn(`XFA - Invalid content in Text: ${e[Rs]}.`);return!1}[Us](e){this[jr]instanceof XFAObject||super[Us](e)}[_r](){"string"==typeof this[jr]&&(this[jr]=this[jr].replaceAll("\r\n","\n"))}[ss](){return"string"==typeof this[jr]?this[jr].split(/[\u2029\u2028\n]/).reduce(((e,t)=>{t&&e.push(t);return e}),[]).join("\n"):this[jr][js]()}[Vs](e){if("string"==typeof this[jr]){const e=valueToHtml(this[jr]).html;if(this[jr].includes("\u2029")){e.name="div";e.children=[];this[jr].split("\u2029").map((e=>e.split(/[\u2028\n]/).reduce(((e,t)=>{e.push({name:"span",value:t},{name:"br"});return e}),[]))).forEach((t=>{e.children.push({name:"p",children:t})}))}else if(/[\u2028\n]/.test(this[jr])){e.name="div";e.children=[];this[jr].split(/[\u2028\n]/).forEach((t=>{e.children.push({name:"span",value:t},{name:"br"})}))}return HTMLResult.success(e)}return this[jr][Vs](e)}}class TextEdit extends XFAObject{constructor(e){super(Mn,"textEdit",!0);this.allowRichText=getInteger({data:e.allowRichText,defaultValue:0,validate:e=>1===e});this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.multiLine=getInteger({data:e.multiLine,defaultValue:"",validate:e=>0===e||1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.vScrollPolicy=getStringOption(e.vScrollPolicy,["auto","off","on"]);this.border=null;this.comb=null;this.extras=null;this.margin=null}[Vs](e){const t=toStyle(this,"border","font","margin");let i;const a=this[ls]()[ls]();""===this.multiLine&&(this.multiLine=a instanceof Draw?1:0);i=1===this.multiLine?{name:"textarea",attributes:{dataId:a[Xr]?.[zs]||a[zs],fieldId:a[zs],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:a[Xr]?.[zs]||a[zs],fieldId:a[zs],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){i.attributes["aria-required"]=!0;i.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[i]})}}class Time extends StringObject{constructor(e){super(Mn,"time");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[_r](){const e=this[jr].trim();this[jr]=e?new Date(e):null}[Vs](e){return valueToHtml(this[jr]?this[jr].toString():"")}}class TimeStamp extends XFAObject{constructor(e){super(Mn,"timeStamp");this.id=e.id||"";this.server=e.server||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class ToolTip extends StringObject{constructor(e){super(Mn,"toolTip");this.id=e.id||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Traversal extends XFAObject{constructor(e){super(Mn,"traversal",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(e){super(Mn,"traverse",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["next","back","down","first","left","right","up"]);this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.script=null}get name(){return this.operation}[Ds](){return!1}}class Ui extends XFAObject{constructor(e){super(Mn,"ui",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null;this.barcode=null;this.button=null;this.checkButton=null;this.choiceList=null;this.dateTimeEdit=null;this.defaultUi=null;this.imageEdit=null;this.numericEdit=null;this.passwordEdit=null;this.signature=null;this.textEdit=null}[ss](){if(void 0===this[Zr]){for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"picture"===e)continue;const t=this[e];if(t instanceof XFAObject){this[Zr]=t;return t}}this[Zr]=null}return this[Zr]}[Vs](e){const t=this[ss]();return t?t[Vs](e):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(e){super(Mn,"validate",!0);this.formatTest=getStringOption(e.formatTest,["warning","disabled","error"]);this.id=e.id||"";this.nullTest=getStringOption(e.nullTest,["disabled","error","warning"]);this.scriptTest=getStringOption(e.scriptTest,["error","disabled","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.picture=null;this.script=null}}class Value extends XFAObject{constructor(e){super(Mn,"value",!0);this.id=e.id||"";this.override=getInteger({data:e.override,defaultValue:0,validate:e=>1===e});this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.arc=null;this.boolean=null;this.date=null;this.dateTime=null;this.decimal=null;this.exData=null;this.float=null;this.image=null;this.integer=null;this.line=null;this.rectangle=null;this.text=null;this.time=null}[Os](e){const t=this[ls]();if(t instanceof Field&&t.ui?.imageEdit){if(!this.image){this.image=new Image({});this[Yr](this.image)}this.image[jr]=e[jr];return}const i=e[Rs];if(null===this[i]){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof XFAObject){this[e]=null;this[Js](t)}}this[e[Rs]]=e;this[Yr](e)}else this[i][jr]=e[jr]}[js](){if(this.exData)return"string"==typeof this.exData[jr]?this.exData[jr].trim():this.exData[jr][js]().trim();for(const e of Object.getOwnPropertyNames(this)){if("image"===e)continue;const t=this[e];if(t instanceof XFAObject)return(t[jr]||"").toString().trim()}return null}[Vs](e){for(const t of Object.getOwnPropertyNames(this)){const i=this[t];if(i instanceof XFAObject)return i[Vs](e)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(e){super(Mn,"variables",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.manifest=new XFAObjectArray;this.script=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Ds](){return!0}}class TemplateNamespace{static[$s](e,t){if(TemplateNamespace.hasOwnProperty(e)){const i=TemplateNamespace[e](t);i[qs](t);return i}}static appearanceFilter(e){return new AppearanceFilter(e)}static arc(e){return new Arc(e)}static area(e){return new Area(e)}static assist(e){return new Assist(e)}static barcode(e){return new Barcode(e)}static bind(e){return new Bind(e)}static bindItems(e){return new BindItems(e)}static bookend(e){return new Bookend(e)}static boolean(e){return new BooleanElement(e)}static border(e){return new Border(e)}static break(e){return new Break(e)}static breakAfter(e){return new BreakAfter(e)}static breakBefore(e){return new BreakBefore(e)}static button(e){return new Button(e)}static calculate(e){return new Calculate(e)}static caption(e){return new Caption(e)}static certificate(e){return new Certificate(e)}static certificates(e){return new Certificates(e)}static checkButton(e){return new CheckButton(e)}static choiceList(e){return new ChoiceList(e)}static color(e){return new Color(e)}static comb(e){return new Comb(e)}static connect(e){return new Connect(e)}static contentArea(e){return new ContentArea(e)}static corner(e){return new Corner(e)}static date(e){return new DateElement(e)}static dateTime(e){return new DateTime(e)}static dateTimeEdit(e){return new DateTimeEdit(e)}static decimal(e){return new Decimal(e)}static defaultUi(e){return new DefaultUi(e)}static desc(e){return new Desc(e)}static digestMethod(e){return new DigestMethod(e)}static digestMethods(e){return new DigestMethods(e)}static draw(e){return new Draw(e)}static edge(e){return new Edge(e)}static encoding(e){return new Encoding(e)}static encodings(e){return new Encodings(e)}static encrypt(e){return new Encrypt(e)}static encryptData(e){return new EncryptData(e)}static encryption(e){return new Encryption(e)}static encryptionMethod(e){return new EncryptionMethod(e)}static encryptionMethods(e){return new EncryptionMethods(e)}static event(e){return new Event(e)}static exData(e){return new ExData(e)}static exObject(e){return new ExObject(e)}static exclGroup(e){return new ExclGroup(e)}static execute(e){return new Execute(e)}static extras(e){return new Extras(e)}static field(e){return new Field(e)}static fill(e){return new Fill(e)}static filter(e){return new Filter(e)}static float(e){return new Float(e)}static font(e){return new template_Font(e)}static format(e){return new Format(e)}static handler(e){return new Handler(e)}static hyphenation(e){return new Hyphenation(e)}static image(e){return new Image(e)}static imageEdit(e){return new ImageEdit(e)}static integer(e){return new Integer(e)}static issuers(e){return new Issuers(e)}static items(e){return new Items(e)}static keep(e){return new Keep(e)}static keyUsage(e){return new KeyUsage(e)}static line(e){return new Line(e)}static linear(e){return new Linear(e)}static lockDocument(e){return new LockDocument(e)}static manifest(e){return new Manifest(e)}static margin(e){return new Margin(e)}static mdp(e){return new Mdp(e)}static medium(e){return new Medium(e)}static message(e){return new Message(e)}static numericEdit(e){return new NumericEdit(e)}static occur(e){return new Occur(e)}static oid(e){return new Oid(e)}static oids(e){return new Oids(e)}static overflow(e){return new Overflow(e)}static pageArea(e){return new PageArea(e)}static pageSet(e){return new PageSet(e)}static para(e){return new Para(e)}static passwordEdit(e){return new PasswordEdit(e)}static pattern(e){return new template_Pattern(e)}static picture(e){return new Picture(e)}static proto(e){return new Proto(e)}static radial(e){return new Radial(e)}static reason(e){return new Reason(e)}static reasons(e){return new Reasons(e)}static rectangle(e){return new Rectangle(e)}static ref(e){return new RefElement(e)}static script(e){return new Script(e)}static setProperty(e){return new SetProperty(e)}static signData(e){return new SignData(e)}static signature(e){return new Signature(e)}static signing(e){return new Signing(e)}static solid(e){return new Solid(e)}static speak(e){return new Speak(e)}static stipple(e){return new Stipple(e)}static subform(e){return new Subform(e)}static subformSet(e){return new SubformSet(e)}static subjectDN(e){return new SubjectDN(e)}static subjectDNs(e){return new SubjectDNs(e)}static submit(e){return new Submit(e)}static template(e){return new Template(e)}static text(e){return new Text(e)}static textEdit(e){return new TextEdit(e)}static time(e){return new Time(e)}static timeStamp(e){return new TimeStamp(e)}static toolTip(e){return new ToolTip(e)}static traversal(e){return new Traversal(e)}static traverse(e){return new Traverse(e)}static ui(e){return new Ui(e)}static validate(e){return new Validate(e)}static value(e){return new Value(e)}static variables(e){return new Variables(e)}}const Jn=An.datasets.id;function createText(e){const t=new Text({});t[jr]=e;return t}class Binder{constructor(e){this.root=e;this.datasets=e.datasets;this.data=e.datasets?.data||new XmlObject(An.datasets.id,"data");this.emptyMerge=0===this.data[os]().length;this.root.form=this.form=e.template[Pr]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){this._bindElement(this.form,this.data);return this.form}getData(){return this.data}_bindValue(e,t,i){e[Xr]=t;if(e[Bs]())if(t[ps]()){const i=t[rs]();e[Os](createText(i))}else if(e instanceof Field&&"multiSelect"===e.ui?.choiceList?.open){const i=t[os]().map((e=>e[jr].trim())).join("\n");e[Os](createText(i))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!t[ps]()||this._isMatchTemplate()?this._bindElement(e,t):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(e,t,i,a){if(!e)return null;let r,s;for(let a=0;a<3;a++){r=i[ns](e,!1,!0);for(;;){s=r.next().value;if(!s)break;if(t===s[ps]())return s}if(i[ks]===An.datasets.id&&"data"===i[Rs])break;i=i[ls]()}if(!a)return null;r=this.data[ns](e,!0,!1);s=r.next().value;if(s)return s;r=this.data[$r](e,!0);s=r.next().value;return s?.[ps]()?s:null}_setProperties(e,t){if(e.hasOwnProperty("setProperty"))for(const{ref:i,target:a,connection:r}of e.setProperty.children){if(r)continue;if(!i)continue;const s=searchNode(this.root,t,i,!1,!1);if(!s){warn(`XFA - Invalid reference: ${i}.`);continue}const[n]=s;if(!n[ms](this.data)){warn("XFA - Invalid node: must be a data node.");continue}const o=searchNode(this.root,e,a,!1,!1);if(!o){warn(`XFA - Invalid target: ${a}.`);continue}const[g]=o;if(!g[ms](e)){warn("XFA - Invalid target: must be a property or subproperty.");continue}const c=g[ls]();if(g instanceof SetProperty||c instanceof SetProperty){warn("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(g instanceof BindItems||c instanceof BindItems){warn("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const l=n[js](),h=g[Rs];if(g instanceof XFAAttribute){const e=Object.create(null);e[h]=l;const t=Reflect.construct(Object.getPrototypeOf(c).constructor,[e]);c[h]=t[h]}else if(g.hasOwnProperty(jr)){g[Xr]=n;g[jr]=l;g[_r]()}else warn("XFA - Invalid node to use in setProperty")}}_bindItems(e,t){if(!e.hasOwnProperty("items")||!e.hasOwnProperty("bindItems")||e.bindItems.isEmpty())return;for(const t of e.items.children)e[Js](t);e.items.clear();const i=new Items({}),a=new Items({});e[Yr](i);e.items.push(i);e[Yr](a);e.items.push(a);for(const{ref:r,labelRef:s,valueRef:n,connection:o}of e.bindItems.children){if(o)continue;if(!r)continue;const e=searchNode(this.root,t,r,!1,!1);if(e)for(const t of e){if(!t[ms](this.datasets)){warn(`XFA - Invalid ref (${r}): must be a datasets child.`);continue}const e=searchNode(this.root,t,s,!0,!1);if(!e){warn(`XFA - Invalid label: ${s}.`);continue}const[o]=e;if(!o[ms](this.datasets)){warn("XFA - Invalid label: must be a datasets child.");continue}const g=searchNode(this.root,t,n,!0,!1);if(!g){warn(`XFA - Invalid value: ${n}.`);continue}const[c]=g;if(!c[ms](this.datasets)){warn("XFA - Invalid value: must be a datasets child.");continue}const l=createText(o[js]()),h=createText(c[js]());i[Yr](l);i.text.push(l);a[Yr](h);a.text.push(h)}else warn(`XFA - Invalid reference: ${r}.`)}}_bindOccurrences(e,t,i){let a;if(t.length>1){a=e[Pr]();a[Js](a.occur);a.occur=null}this._bindValue(e,t[0],i);this._setProperties(e,t[0]);this._bindItems(e,t[0]);if(1===t.length)return;const r=e[ls](),s=e[Rs],n=r[Es](e);for(let e=1,o=t.length;et.name===e.name)).length:i[a].children.length;const s=i[Es](e)+1,n=t.initial-r;if(n){const t=e[Pr]();t[Js](t.occur);t.occur=null;i[a].push(t);i[us](s,t);for(let e=1;e0)this._bindOccurrences(a,[e[0]],null);else if(this.emptyMerge){const e=t[ks]===Jn?-1:t[ks],i=a[Xr]=new XmlObject(e,a.name||"root");t[Yr](i);this._bindElement(a,i)}continue}if(!a[fs]())continue;let e=!1,r=null,s=null,n=null;if(a.bind){switch(a.bind.match){case"none":this._setAndBind(a,t);continue;case"global":e=!0;break;case"dataRef":if(!a.bind.ref){warn(`XFA - ref is empty in node ${a[Rs]}.`);this._setAndBind(a,t);continue}s=a.bind.ref}a.bind.picture&&(r=a.bind.picture[jr])}const[o,g]=this._getOccurInfo(a);if(s){n=searchNode(this.root,t,s,!0,!1);if(null===n){n=createDataNode(this.data,t,s);if(!n)continue;this._isConsumeData()&&(n[Wr]=!0);this._setAndBind(a,n);continue}this._isConsumeData()&&(n=n.filter((e=>!e[Wr])));n.length>g?n=n.slice(0,g):0===n.length&&(n=null);n&&this._isConsumeData()&&n.forEach((e=>{e[Wr]=!0}))}else{if(!a.name){this._setAndBind(a,t);continue}if(this._isConsumeData()){const i=[];for(;i.length0?i:null}else{n=t[ns](a.name,!1,this.emptyMerge).next().value;if(!n){if(0===o){i.push(a);continue}const e=t[ks]===Jn?-1:t[ks];n=a[Xr]=new XmlObject(e,a.name);this.emptyMerge&&(n[Wr]=!0);t[Yr](n);this._setAndBind(a,n);continue}this.emptyMerge&&(n[Wr]=!0);n=[n]}}n?this._bindOccurrences(a,n,r):o>0?this._setAndBind(a,t):i.push(a)}i.forEach((e=>e[ls]()[Js](e)))}}class DataHandler{constructor(e,t){this.data=t;this.dataset=e.datasets||null}serialize(e){const t=[[-1,this.data[os]()]];for(;t.length>0;){const i=t.at(-1),[a,r]=i;if(a+1===r.length){t.pop();continue}const s=r[++i[0]],n=e.get(s[zs]);if(n)s[Os](n);else{const t=s[As]();for(const i of t.values()){const t=e.get(i[zs]);if(t){i[Os](t);break}}}const o=s[os]();o.length>0&&t.push([-1,o])}const i=[''];if(this.dataset)for(const e of this.dataset[os]())"data"!==e[Rs]&&e[Zs](i);this.data[Zs](i);i.push("");return i.join("")}}const vn=An.config.id;class Acrobat extends XFAObject{constructor(e){super(vn,"acrobat",!0);this.acrobat7=null;this.autoSave=null;this.common=null;this.validate=null;this.validateApprovalSignatures=null;this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(e){super(vn,"acrobat7",!0);this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(e){super(vn,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(e){super(vn,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(e){super(vn,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(e){super(vn,"addViewerPreferences")}}class AdjustData extends Option10{constructor(e){super(vn,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(e){super(vn,"adobeExtensionLevel",0,(e=>e>=1&&e<=8))}}class Agent extends XFAObject{constructor(e){super(vn,"agent",!0);this.name=e.name?e.name.trim():"";this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(e){super(vn,"alwaysEmbed")}}class Amd extends StringObject{constructor(e){super(vn,"amd")}}class config_Area extends XFAObject{constructor(e){super(vn,"area");this.level=getInteger({data:e.level,defaultValue:0,validate:e=>e>=1&&e<=3});this.name=getStringOption(e.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(e){super(vn,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(e){super(vn,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(e){super(vn,"base")}}class BatchOutput extends XFAObject{constructor(e){super(vn,"batchOutput");this.format=getStringOption(e.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(e){super(vn,"behaviorOverride")}[_r](){this[jr]=new Map(this[jr].trim().split(/\s+/).filter((e=>e.includes(":"))).map((e=>e.split(":",2))))}}class Cache extends XFAObject{constructor(e){super(vn,"cache",!0);this.templateCache=null}}class Change extends Option01{constructor(e){super(vn,"change")}}class Common extends XFAObject{constructor(e){super(vn,"common",!0);this.data=null;this.locale=null;this.localeSet=null;this.messaging=null;this.suppressBanner=null;this.template=null;this.validationMessaging=null;this.versionControl=null;this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(e){super(vn,"compress");this.scope=getStringOption(e.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(e){super(vn,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(e){super(vn,"compressObjectStream")}}class Compression extends XFAObject{constructor(e){super(vn,"compression",!0);this.compressLogicalStructure=null;this.compressObjectStream=null;this.level=null;this.type=null}}class Config extends XFAObject{constructor(e){super(vn,"config",!0);this.acrobat=null;this.present=null;this.trace=null;this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(e){super(vn,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(e){super(vn,"contentCopy")}}class Copies extends IntegerObject{constructor(e){super(vn,"copies",1,(e=>e>=1))}}class Creator extends StringObject{constructor(e){super(vn,"creator")}}class CurrentPage extends IntegerObject{constructor(e){super(vn,"currentPage",0,(e=>e>=0))}}class Data extends XFAObject{constructor(e){super(vn,"data",!0);this.adjustData=null;this.attributes=null;this.incrementalLoad=null;this.outputXSL=null;this.range=null;this.record=null;this.startNode=null;this.uri=null;this.window=null;this.xsl=null;this.excludeNS=new XFAObjectArray;this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(e){super(vn,"debug",!0);this.uri=null}}class DefaultTypeface extends ContentObject{constructor(e){super(vn,"defaultTypeface");this.writingScript=getStringOption(e.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(e){super(vn,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(e){super(vn,"documentAssembly")}}class Driver extends XFAObject{constructor(e){super(vn,"driver",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class DuplexOption extends OptionObject{constructor(e){super(vn,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(e){super(vn,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(e){super(vn,"embed")}}class config_Encrypt extends Option01{constructor(e){super(vn,"encrypt")}}class config_Encryption extends XFAObject{constructor(e){super(vn,"encryption",!0);this.encrypt=null;this.encryptionLevel=null;this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(e){super(vn,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(e){super(vn,"enforce")}}class Equate extends XFAObject{constructor(e){super(vn,"equate");this.force=getInteger({data:e.force,defaultValue:1,validate:e=>0===e});this.from=e.from||"";this.to=e.to||""}}class EquateRange extends XFAObject{constructor(e){super(vn,"equateRange");this.from=e.from||"";this.to=e.to||"";this._unicodeRange=e.unicodeRange||""}get unicodeRange(){const e=[],t=/U\+([0-9a-fA-F]+)/,i=this._unicodeRange;for(let a of i.split(",").map((e=>e.trim())).filter((e=>!!e))){a=a.split("-",2).map((e=>{const i=e.match(t);return i?parseInt(i[1],16):0}));1===a.length&&a.push(a[0]);e.push(a)}return shadow(this,"unicodeRange",e)}}class Exclude extends ContentObject{constructor(e){super(vn,"exclude")}[_r](){this[jr]=this[jr].trim().split(/\s+/).filter((e=>e&&["calculate","close","enter","exit","initialize","ready","validate"].includes(e)))}}class ExcludeNS extends StringObject{constructor(e){super(vn,"excludeNS")}}class FlipLabel extends OptionObject{constructor(e){super(vn,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(e){super(vn,"fontInfo",!0);this.embed=null;this.map=null;this.subsetBelow=null;this.alwaysEmbed=new XFAObjectArray;this.defaultTypeface=new XFAObjectArray;this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(e){super(vn,"formFieldFilling")}}class GroupParent extends StringObject{constructor(e){super(vn,"groupParent")}}class IfEmpty extends OptionObject{constructor(e){super(vn,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(e){super(vn,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(e){super(vn,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(e){super(vn,"incrementalMerge")}}class Interactive extends Option01{constructor(e){super(vn,"interactive")}}class Jog extends OptionObject{constructor(e){super(vn,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(e){super(vn,"labelPrinter",!0);this.name=getStringOption(e.name,["zpl","dpl","ipl","tcpl"]);this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class Layout extends OptionObject{constructor(e){super(vn,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(e){super(vn,"level",0,(e=>e>0))}}class Linearized extends Option01{constructor(e){super(vn,"linearized")}}class Locale extends StringObject{constructor(e){super(vn,"locale")}}class LocaleSet extends StringObject{constructor(e){super(vn,"localeSet")}}class Log extends XFAObject{constructor(e){super(vn,"log",!0);this.mode=null;this.threshold=null;this.to=null;this.uri=null}}class MapElement extends XFAObject{constructor(e){super(vn,"map",!0);this.equate=new XFAObjectArray;this.equateRange=new XFAObjectArray}}class MediumInfo extends XFAObject{constructor(e){super(vn,"mediumInfo",!0);this.map=null}}class config_Message extends XFAObject{constructor(e){super(vn,"message",!0);this.msgId=null;this.severity=null}}class Messaging extends XFAObject{constructor(e){super(vn,"messaging",!0);this.message=new XFAObjectArray}}class Mode extends OptionObject{constructor(e){super(vn,"mode",["append","overwrite"])}}class ModifyAnnots extends Option01{constructor(e){super(vn,"modifyAnnots")}}class MsgId extends IntegerObject{constructor(e){super(vn,"msgId",1,(e=>e>=1))}}class NameAttr extends StringObject{constructor(e){super(vn,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(e){super(vn,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(e){super(vn,"numberOfCopies",null,(e=>e>=2&&e<=5))}}class OpenAction extends XFAObject{constructor(e){super(vn,"openAction",!0);this.destination=null}}class Output extends XFAObject{constructor(e){super(vn,"output",!0);this.to=null;this.type=null;this.uri=null}}class OutputBin extends StringObject{constructor(e){super(vn,"outputBin")}}class OutputXSL extends XFAObject{constructor(e){super(vn,"outputXSL",!0);this.uri=null}}class Overprint extends OptionObject{constructor(e){super(vn,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(e){super(vn,"packets")}[_r](){"*"!==this[jr]&&(this[jr]=this[jr].trim().split(/\s+/).filter((e=>["config","datasets","template","xfdf","xslt"].includes(e))))}}class PageOffset extends XFAObject{constructor(e){super(vn,"pageOffset");this.x=getInteger({data:e.x,defaultValue:"useXDCSetting",validate:e=>!0});this.y=getInteger({data:e.y,defaultValue:"useXDCSetting",validate:e=>!0})}}class PageRange extends StringObject{constructor(e){super(vn,"pageRange")}[_r](){const e=this[jr].trim().split(/\s+/).map((e=>parseInt(e,10))),t=[];for(let i=0,a=e.length;i!1))}}class Pcl extends XFAObject{constructor(e){super(vn,"pcl",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.pageOffset=null;this.staple=null;this.xdc=null}}class Pdf extends XFAObject{constructor(e){super(vn,"pdf",!0);this.name=e.name||"";this.adobeExtensionLevel=null;this.batchOutput=null;this.compression=null;this.creator=null;this.encryption=null;this.fontInfo=null;this.interactive=null;this.linearized=null;this.openAction=null;this.pdfa=null;this.producer=null;this.renderPolicy=null;this.scriptModel=null;this.silentPrint=null;this.submitFormat=null;this.tagged=null;this.version=null;this.viewerPreferences=null;this.xdc=null}}class Pdfa extends XFAObject{constructor(e){super(vn,"pdfa",!0);this.amd=null;this.conformance=null;this.includeXDPContent=null;this.part=null}}class Permissions extends XFAObject{constructor(e){super(vn,"permissions",!0);this.accessibleContent=null;this.change=null;this.contentCopy=null;this.documentAssembly=null;this.formFieldFilling=null;this.modifyAnnots=null;this.plaintextMetadata=null;this.print=null;this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(e){super(vn,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(e){super(vn,"picture")}}class PlaintextMetadata extends Option01{constructor(e){super(vn,"plaintextMetadata")}}class Presence extends OptionObject{constructor(e){super(vn,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(e){super(vn,"present",!0);this.behaviorOverride=null;this.cache=null;this.common=null;this.copies=null;this.destination=null;this.incrementalMerge=null;this.layout=null;this.output=null;this.overprint=null;this.pagination=null;this.paginationOverride=null;this.script=null;this.validate=null;this.xdp=null;this.driver=new XFAObjectArray;this.labelPrinter=new XFAObjectArray;this.pcl=new XFAObjectArray;this.pdf=new XFAObjectArray;this.ps=new XFAObjectArray;this.submitUrl=new XFAObjectArray;this.webClient=new XFAObjectArray;this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(e){super(vn,"print")}}class PrintHighQuality extends Option01{constructor(e){super(vn,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(e){super(vn,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(e){super(vn,"printerName")}}class Producer extends StringObject{constructor(e){super(vn,"producer")}}class Ps extends XFAObject{constructor(e){super(vn,"ps",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.staple=null;this.xdc=null}}class Range extends ContentObject{constructor(e){super(vn,"range")}[_r](){this[jr]=this[jr].trim().split(/\s*,\s*/,2).map((e=>e.split("-").map((e=>parseInt(e.trim(),10))))).filter((e=>e.every((e=>!isNaN(e))))).map((e=>{1===e.length&&e.push(e[0]);return e}))}}class Record extends ContentObject{constructor(e){super(vn,"record")}[_r](){this[jr]=this[jr].trim();const e=parseInt(this[jr],10);!isNaN(e)&&e>=0&&(this[jr]=e)}}class Relevant extends ContentObject{constructor(e){super(vn,"relevant")}[_r](){this[jr]=this[jr].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(e){super(vn,"rename")}[_r](){this[jr]=this[jr].trim();(this[jr].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[jr]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(e){super(vn,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(e){super(vn,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(e){super(vn,"script",!0);this.currentPage=null;this.exclude=null;this.runScripts=null}}class ScriptModel extends OptionObject{constructor(e){super(vn,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(e){super(vn,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(e){super(vn,"silentPrint",!0);this.addSilentPrint=null;this.printerName=null}}class Staple extends XFAObject{constructor(e){super(vn,"staple");this.mode=getStringOption(e.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(e){super(vn,"startNode")}}class StartPage extends IntegerObject{constructor(e){super(vn,"startPage",0,(e=>!0))}}class SubmitFormat extends OptionObject{constructor(e){super(vn,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(e){super(vn,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(e){super(vn,"subsetBelow",100,(e=>e>=0&&e<=100))}}class SuppressBanner extends Option01{constructor(e){super(vn,"suppressBanner")}}class Tagged extends Option01{constructor(e){super(vn,"tagged")}}class config_Template extends XFAObject{constructor(e){super(vn,"template",!0);this.base=null;this.relevant=null;this.startPage=null;this.uri=null;this.xsl=null}}class Threshold extends OptionObject{constructor(e){super(vn,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(e){super(vn,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(e){super(vn,"templateCache");this.maxEntries=getInteger({data:e.maxEntries,defaultValue:5,validate:e=>e>=0})}}class Trace extends XFAObject{constructor(e){super(vn,"trace",!0);this.area=new XFAObjectArray}}class Transform extends XFAObject{constructor(e){super(vn,"transform",!0);this.groupParent=null;this.ifEmpty=null;this.nameAttr=null;this.picture=null;this.presence=null;this.rename=null;this.whitespace=null}}class Type extends OptionObject{constructor(e){super(vn,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(e){super(vn,"uri")}}class config_Validate extends OptionObject{constructor(e){super(vn,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(e){super(vn,"validateApprovalSignatures")}[_r](){this[jr]=this[jr].trim().split(/\s+/).filter((e=>["docReady","postSign"].includes(e)))}}class ValidationMessaging extends OptionObject{constructor(e){super(vn,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(e){super(vn,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(e){super(vn,"VersionControl");this.outputBelow=getStringOption(e.outputBelow,["warn","error","update"]);this.sourceAbove=getStringOption(e.sourceAbove,["warn","error"]);this.sourceBelow=getStringOption(e.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(e){super(vn,"viewerPreferences",!0);this.ADBE_JSConsole=null;this.ADBE_JSDebugger=null;this.addViewerPreferences=null;this.duplexOption=null;this.enforce=null;this.numberOfCopies=null;this.pageRange=null;this.pickTrayByPDFSize=null;this.printScaling=null}}class WebClient extends XFAObject{constructor(e){super(vn,"webClient",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class Whitespace extends OptionObject{constructor(e){super(vn,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(e){super(vn,"window")}[_r](){const e=this[jr].trim().split(/\s*,\s*/,2).map((e=>parseInt(e,10)));if(e.some((e=>isNaN(e))))this[jr]=[0,0];else{1===e.length&&e.push(e[0]);this[jr]=e}}}class Xdc extends XFAObject{constructor(e){super(vn,"xdc",!0);this.uri=new XFAObjectArray;this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(e){super(vn,"xdp",!0);this.packets=null}}class Xsl extends XFAObject{constructor(e){super(vn,"xsl",!0);this.debug=null;this.uri=null}}class Zpl extends XFAObject{constructor(e){super(vn,"zpl",!0);this.name=e.name?e.name.trim():"";this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class ConfigNamespace{static[$s](e,t){if(ConfigNamespace.hasOwnProperty(e))return ConfigNamespace[e](t)}static acrobat(e){return new Acrobat(e)}static acrobat7(e){return new Acrobat7(e)}static ADBE_JSConsole(e){return new ADBE_JSConsole(e)}static ADBE_JSDebugger(e){return new ADBE_JSDebugger(e)}static addSilentPrint(e){return new AddSilentPrint(e)}static addViewerPreferences(e){return new AddViewerPreferences(e)}static adjustData(e){return new AdjustData(e)}static adobeExtensionLevel(e){return new AdobeExtensionLevel(e)}static agent(e){return new Agent(e)}static alwaysEmbed(e){return new AlwaysEmbed(e)}static amd(e){return new Amd(e)}static area(e){return new config_Area(e)}static attributes(e){return new Attributes(e)}static autoSave(e){return new AutoSave(e)}static base(e){return new Base(e)}static batchOutput(e){return new BatchOutput(e)}static behaviorOverride(e){return new BehaviorOverride(e)}static cache(e){return new Cache(e)}static change(e){return new Change(e)}static common(e){return new Common(e)}static compress(e){return new Compress(e)}static compressLogicalStructure(e){return new CompressLogicalStructure(e)}static compressObjectStream(e){return new CompressObjectStream(e)}static compression(e){return new Compression(e)}static config(e){return new Config(e)}static conformance(e){return new Conformance(e)}static contentCopy(e){return new ContentCopy(e)}static copies(e){return new Copies(e)}static creator(e){return new Creator(e)}static currentPage(e){return new CurrentPage(e)}static data(e){return new Data(e)}static debug(e){return new Debug(e)}static defaultTypeface(e){return new DefaultTypeface(e)}static destination(e){return new Destination(e)}static documentAssembly(e){return new DocumentAssembly(e)}static driver(e){return new Driver(e)}static duplexOption(e){return new DuplexOption(e)}static dynamicRender(e){return new DynamicRender(e)}static embed(e){return new Embed(e)}static encrypt(e){return new config_Encrypt(e)}static encryption(e){return new config_Encryption(e)}static encryptionLevel(e){return new EncryptionLevel(e)}static enforce(e){return new Enforce(e)}static equate(e){return new Equate(e)}static equateRange(e){return new EquateRange(e)}static exclude(e){return new Exclude(e)}static excludeNS(e){return new ExcludeNS(e)}static flipLabel(e){return new FlipLabel(e)}static fontInfo(e){return new config_FontInfo(e)}static formFieldFilling(e){return new FormFieldFilling(e)}static groupParent(e){return new GroupParent(e)}static ifEmpty(e){return new IfEmpty(e)}static includeXDPContent(e){return new IncludeXDPContent(e)}static incrementalLoad(e){return new IncrementalLoad(e)}static incrementalMerge(e){return new IncrementalMerge(e)}static interactive(e){return new Interactive(e)}static jog(e){return new Jog(e)}static labelPrinter(e){return new LabelPrinter(e)}static layout(e){return new Layout(e)}static level(e){return new Level(e)}static linearized(e){return new Linearized(e)}static locale(e){return new Locale(e)}static localeSet(e){return new LocaleSet(e)}static log(e){return new Log(e)}static map(e){return new MapElement(e)}static mediumInfo(e){return new MediumInfo(e)}static message(e){return new config_Message(e)}static messaging(e){return new Messaging(e)}static mode(e){return new Mode(e)}static modifyAnnots(e){return new ModifyAnnots(e)}static msgId(e){return new MsgId(e)}static nameAttr(e){return new NameAttr(e)}static neverEmbed(e){return new NeverEmbed(e)}static numberOfCopies(e){return new NumberOfCopies(e)}static openAction(e){return new OpenAction(e)}static output(e){return new Output(e)}static outputBin(e){return new OutputBin(e)}static outputXSL(e){return new OutputXSL(e)}static overprint(e){return new Overprint(e)}static packets(e){return new Packets(e)}static pageOffset(e){return new PageOffset(e)}static pageRange(e){return new PageRange(e)}static pagination(e){return new Pagination(e)}static paginationOverride(e){return new PaginationOverride(e)}static part(e){return new Part(e)}static pcl(e){return new Pcl(e)}static pdf(e){return new Pdf(e)}static pdfa(e){return new Pdfa(e)}static permissions(e){return new Permissions(e)}static pickTrayByPDFSize(e){return new PickTrayByPDFSize(e)}static picture(e){return new config_Picture(e)}static plaintextMetadata(e){return new PlaintextMetadata(e)}static presence(e){return new Presence(e)}static present(e){return new Present(e)}static print(e){return new Print(e)}static printHighQuality(e){return new PrintHighQuality(e)}static printScaling(e){return new PrintScaling(e)}static printerName(e){return new PrinterName(e)}static producer(e){return new Producer(e)}static ps(e){return new Ps(e)}static range(e){return new Range(e)}static record(e){return new Record(e)}static relevant(e){return new Relevant(e)}static rename(e){return new Rename(e)}static renderPolicy(e){return new RenderPolicy(e)}static runScripts(e){return new RunScripts(e)}static script(e){return new config_Script(e)}static scriptModel(e){return new ScriptModel(e)}static severity(e){return new Severity(e)}static silentPrint(e){return new SilentPrint(e)}static staple(e){return new Staple(e)}static startNode(e){return new StartNode(e)}static startPage(e){return new StartPage(e)}static submitFormat(e){return new SubmitFormat(e)}static submitUrl(e){return new SubmitUrl(e)}static subsetBelow(e){return new SubsetBelow(e)}static suppressBanner(e){return new SuppressBanner(e)}static tagged(e){return new Tagged(e)}static template(e){return new config_Template(e)}static templateCache(e){return new TemplateCache(e)}static threshold(e){return new Threshold(e)}static to(e){return new To(e)}static trace(e){return new Trace(e)}static transform(e){return new Transform(e)}static type(e){return new Type(e)}static uri(e){return new Uri(e)}static validate(e){return new config_Validate(e)}static validateApprovalSignatures(e){return new ValidateApprovalSignatures(e)}static validationMessaging(e){return new ValidationMessaging(e)}static version(e){return new Version(e)}static versionControl(e){return new VersionControl(e)}static viewerPreferences(e){return new ViewerPreferences(e)}static webClient(e){return new WebClient(e)}static whitespace(e){return new Whitespace(e)}static window(e){return new Window(e)}static xdc(e){return new Xdc(e)}static xdp(e){return new Xdp(e)}static xsl(e){return new Xsl(e)}static zpl(e){return new Zpl(e)}}const Yn=An.connectionSet.id;class ConnectionSet extends XFAObject{constructor(e){super(Yn,"connectionSet",!0);this.wsdlConnection=new XFAObjectArray;this.xmlConnection=new XFAObjectArray;this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(e){super(Yn,"effectiveInputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(e){super(Yn,"effectiveOutputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Operation extends StringObject{constructor(e){super(Yn,"operation");this.id=e.id||"";this.input=e.input||"";this.name=e.name||"";this.output=e.output||"";this.use=e.use||"";this.usehref=e.usehref||""}}class RootElement extends StringObject{constructor(e){super(Yn,"rootElement");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAction extends StringObject{constructor(e){super(Yn,"soapAction");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAddress extends StringObject{constructor(e){super(Yn,"soapAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class connection_set_Uri extends StringObject{constructor(e){super(Yn,"uri");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlAddress extends StringObject{constructor(e){super(Yn,"wsdlAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlConnection extends XFAObject{constructor(e){super(Yn,"wsdlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.effectiveInputPolicy=null;this.effectiveOutputPolicy=null;this.operation=null;this.soapAction=null;this.soapAddress=null;this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(e){super(Yn,"xmlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.uri=null}}class XsdConnection extends XFAObject{constructor(e){super(Yn,"xsdConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.rootElement=null;this.uri=null}}class ConnectionSetNamespace{static[$s](e,t){if(ConnectionSetNamespace.hasOwnProperty(e))return ConnectionSetNamespace[e](t)}static connectionSet(e){return new ConnectionSet(e)}static effectiveInputPolicy(e){return new EffectiveInputPolicy(e)}static effectiveOutputPolicy(e){return new EffectiveOutputPolicy(e)}static operation(e){return new Operation(e)}static rootElement(e){return new RootElement(e)}static soapAction(e){return new SoapAction(e)}static soapAddress(e){return new SoapAddress(e)}static uri(e){return new connection_set_Uri(e)}static wsdlAddress(e){return new WsdlAddress(e)}static wsdlConnection(e){return new WsdlConnection(e)}static xmlConnection(e){return new XmlConnection(e)}static xsdConnection(e){return new XsdConnection(e)}}const Kn=An.datasets.id;class datasets_Data extends XmlObject{constructor(e){super(Kn,"data",e)}[ys](){return!0}}class Datasets extends XFAObject{constructor(e){super(Kn,"datasets",!0);this.data=null;this.Signature=null}[Gs](e){const t=e[Rs];("data"===t&&e[ks]===Kn||"Signature"===t&&e[ks]===An.signature.id)&&(this[t]=e);this[Yr](e)}}class DatasetsNamespace{static[$s](e,t){if(DatasetsNamespace.hasOwnProperty(e))return DatasetsNamespace[e](t)}static datasets(e){return new Datasets(e)}static data(e){return new datasets_Data(e)}}const Tn=An.localeSet.id;class CalendarSymbols extends XFAObject{constructor(e){super(Tn,"calendarSymbols",!0);this.name="gregorian";this.dayNames=new XFAObjectArray(2);this.eraNames=null;this.meridiemNames=null;this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(e){super(Tn,"currencySymbol");this.name=getStringOption(e.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(e){super(Tn,"currencySymbols",!0);this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(e){super(Tn,"datePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(e){super(Tn,"datePatterns",!0);this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(e){super(Tn,"dateTimeSymbols")}}class Day extends StringObject{constructor(e){super(Tn,"day")}}class DayNames extends XFAObject{constructor(e){super(Tn,"dayNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(e){super(Tn,"era")}}class EraNames extends XFAObject{constructor(e){super(Tn,"eraNames",!0);this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(e){super(Tn,"locale",!0);this.desc=e.desc||"";this.name="isoname";this.calendarSymbols=null;this.currencySymbols=null;this.datePatterns=null;this.dateTimeSymbols=null;this.numberPatterns=null;this.numberSymbols=null;this.timePatterns=null;this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(e){super(Tn,"localeSet",!0);this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(e){super(Tn,"meridiem")}}class MeridiemNames extends XFAObject{constructor(e){super(Tn,"meridiemNames",!0);this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(e){super(Tn,"month")}}class MonthNames extends XFAObject{constructor(e){super(Tn,"monthNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(e){super(Tn,"numberPattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(e){super(Tn,"numberPatterns",!0);this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(e){super(Tn,"numberSymbol");this.name=getStringOption(e.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(e){super(Tn,"numberSymbols",!0);this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(e){super(Tn,"timePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(e){super(Tn,"timePatterns",!0);this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(e){super(Tn,"typeFace",!0);this.name=""|e.name}}class TypeFaces extends XFAObject{constructor(e){super(Tn,"typeFaces",!0);this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[$s](e,t){if(LocaleSetNamespace.hasOwnProperty(e))return LocaleSetNamespace[e](t)}static calendarSymbols(e){return new CalendarSymbols(e)}static currencySymbol(e){return new CurrencySymbol(e)}static currencySymbols(e){return new CurrencySymbols(e)}static datePattern(e){return new DatePattern(e)}static datePatterns(e){return new DatePatterns(e)}static dateTimeSymbols(e){return new DateTimeSymbols(e)}static day(e){return new Day(e)}static dayNames(e){return new DayNames(e)}static era(e){return new Era(e)}static eraNames(e){return new EraNames(e)}static locale(e){return new locale_set_Locale(e)}static localeSet(e){return new locale_set_LocaleSet(e)}static meridiem(e){return new Meridiem(e)}static meridiemNames(e){return new MeridiemNames(e)}static month(e){return new Month(e)}static monthNames(e){return new MonthNames(e)}static numberPattern(e){return new NumberPattern(e)}static numberPatterns(e){return new NumberPatterns(e)}static numberSymbol(e){return new NumberSymbol(e)}static numberSymbols(e){return new NumberSymbols(e)}static timePattern(e){return new TimePattern(e)}static timePatterns(e){return new TimePatterns(e)}static typeFace(e){return new TypeFace(e)}static typeFaces(e){return new TypeFaces(e)}}const qn=An.signature.id;class signature_Signature extends XFAObject{constructor(e){super(qn,"signature",!0)}}class SignatureNamespace{static[$s](e,t){if(SignatureNamespace.hasOwnProperty(e))return SignatureNamespace[e](t)}static signature(e){return new signature_Signature(e)}}const On=An.stylesheet.id;class Stylesheet extends XFAObject{constructor(e){super(On,"stylesheet",!0)}}class StylesheetNamespace{static[$s](e,t){if(StylesheetNamespace.hasOwnProperty(e))return StylesheetNamespace[e](t)}static stylesheet(e){return new Stylesheet(e)}}const Pn=An.xdp.id;class xdp_Xdp extends XFAObject{constructor(e){super(Pn,"xdp",!0);this.uuid=e.uuid||"";this.timeStamp=e.timeStamp||"";this.config=null;this.connectionSet=null;this.datasets=null;this.localeSet=null;this.stylesheet=new XFAObjectArray;this.template=null}[Ms](e){const t=An[e[Rs]];return t&&e[ks]===t.id}}class XdpNamespace{static[$s](e,t){if(XdpNamespace.hasOwnProperty(e))return XdpNamespace[e](t)}static xdp(e){return new xdp_Xdp(e)}}const Wn=An.xhtml.id,jn=Symbol(),Xn=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),Vn=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",e=>"none"===e?"none":"normal"],["xfa-font-horizontal-scale",e=>`scaleX(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-font-vertical-scale",e=>`scaleY(${Math.max(0,Math.min(parseInt(e)/100)).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(e,t)=>measureToString(.99*(e=t.fontSize=Math.abs(getMeasurement(e))))],["letter-spacing",e=>measureToString(getMeasurement(e))],["line-height",e=>measureToString(getMeasurement(e))],["margin",e=>measureToString(getMeasurement(e))],["margin-bottom",e=>measureToString(getMeasurement(e))],["margin-left",e=>measureToString(getMeasurement(e))],["margin-right",e=>measureToString(getMeasurement(e))],["margin-top",e=>measureToString(getMeasurement(e))],["text-indent",e=>measureToString(getMeasurement(e))],["font-family",e=>e],["vertical-align",e=>measureToString(getMeasurement(e))]]),Zn=/\s+/g,_n=/[\r\n]+/g,zn=/\r\n?/g;function mapStyle(e,t,i){const a=Object.create(null);if(!e)return a;const r=Object.create(null);for(const[t,i]of e.split(";").map((e=>e.split(":",2)))){const e=Vn.get(t);if(""===e)continue;let s=i;e&&(s="string"==typeof e?e:e(i,r));t.endsWith("scale")?a.transform=a.transform?`${a[t]} ${s}`:s:a[t.replaceAll(/-([a-zA-Z])/g,((e,t)=>t.toUpperCase()))]=s}a.fontFamily&&setFontFamily({typeface:a.fontFamily,weight:a.fontWeight||"normal",posture:a.fontStyle||"normal",size:r.fontSize||0},t,t[Cs].fontFinder,a);if(i&&a.verticalAlign&&"0px"!==a.verticalAlign&&a.fontSize){const e=.583,t=.333,i=getMeasurement(a.fontSize);a.fontSize=measureToString(i*e);a.verticalAlign=measureToString(Math.sign(getMeasurement(a.verticalAlign))*i*t)}i&&a.fontSize&&(a.fontSize=`calc(${a.fontSize} * var(--scale-factor))`);fixTextIndent(a);return a}const $n=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(e,t){super(Wn,t);this[jn]=!1;this.style=e.style||""}[Tr](e){super[Tr](e);this.style=function checkStyle(e){return e.style?e.style.trim().split(/\s*;\s*/).filter((e=>!!e)).map((e=>e.split(/\s*:\s*/,2))).filter((([t,i])=>{"font-family"===t&&e[Cs].usedTypefaces.add(i);return Xn.has(t)})).map((e=>e.join(":"))).join(";"):""}(this)}[Jr](){return!$n.has(this[Rs])}[Us](e,t=!1){if(t)this[jn]=!0;else{e=e.replaceAll(_n,"");this.style.includes("xfa-spacerun:yes")||(e=e.replaceAll(Zn," "))}e&&(this[jr]+=e)}[xs](e,t=!0){const i=Object.create(null),a={top:NaN,bottom:NaN,left:NaN,right:NaN};let r=null;for(const[e,t]of this.style.split(";").map((e=>e.split(":",2))))switch(e){case"font-family":i.typeface=stripQuotes(t);break;case"font-size":i.size=getMeasurement(t);break;case"font-weight":i.weight=t;break;case"font-style":i.posture=t;break;case"letter-spacing":i.letterSpacing=getMeasurement(t);break;case"margin":const e=t.split(/ \t/).map((e=>getMeasurement(e)));switch(e.length){case 1:a.top=a.bottom=a.left=a.right=e[0];break;case 2:a.top=a.bottom=e[0];a.left=a.right=e[1];break;case 3:a.top=e[0];a.bottom=e[2];a.left=a.right=e[1];break;case 4:a.top=e[0];a.left=e[1];a.bottom=e[2];a.right=e[3]}break;case"margin-top":a.top=getMeasurement(t);break;case"margin-bottom":a.bottom=getMeasurement(t);break;case"margin-left":a.left=getMeasurement(t);break;case"margin-right":a.right=getMeasurement(t);break;case"line-height":r=getMeasurement(t)}e.pushData(i,a,r);if(this[jr])e.addString(this[jr]);else for(const t of this[os]())"#text"!==t[Rs]?t[xs](e):e.addString(t[jr]);t&&e.popFont()}[Vs](e){const t=[];this[Zr]={children:t};this[Kr]({});if(0===t.length&&!this[jr])return HTMLResult.EMPTY;let i;i=this[jn]?this[jr]?this[jr].replaceAll(zn,"\n"):void 0:this[jr]||void 0;return HTMLResult.success({name:this[Rs],attributes:{href:this.href,style:mapStyle(this.style,this,this[jn])},children:t,value:i})}}class A extends XhtmlObject{constructor(e){super(e,"a");this.href=fixURL(e.href)||""}}class B extends XhtmlObject{constructor(e){super(e,"b")}[xs](e){e.pushFont({weight:"bold"});super[xs](e);e.popFont()}}class Body extends XhtmlObject{constructor(e){super(e,"body")}[Vs](e){const t=super[Vs](e),{html:i}=t;if(!i)return HTMLResult.EMPTY;i.name="div";i.attributes.class=["xfaRich"];return t}}class Br extends XhtmlObject{constructor(e){super(e,"br")}[js](){return"\n"}[xs](e){e.addString("\n")}[Vs](e){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(e){super(e,"html")}[Vs](e){const t=[];this[Zr]={children:t};this[Kr]({});if(0===t.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[jr]||""});if(1===t.length){const e=t[0];if(e.attributes?.class.includes("xfaRich"))return HTMLResult.success(e)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:t})}}class I extends XhtmlObject{constructor(e){super(e,"i")}[xs](e){e.pushFont({posture:"italic"});super[xs](e);e.popFont()}}class Li extends XhtmlObject{constructor(e){super(e,"li")}}class Ol extends XhtmlObject{constructor(e){super(e,"ol")}}class P extends XhtmlObject{constructor(e){super(e,"p")}[xs](e){super[xs](e,!1);e.addString("\n");e.addPara();e.popFont()}[js](){return this[ls]()[os]().at(-1)===this?super[js]():super[js]()+"\n"}}class Span extends XhtmlObject{constructor(e){super(e,"span")}}class Sub extends XhtmlObject{constructor(e){super(e,"sub")}}class Sup extends XhtmlObject{constructor(e){super(e,"sup")}}class Ul extends XhtmlObject{constructor(e){super(e,"ul")}}class XhtmlNamespace{static[$s](e,t){if(XhtmlNamespace.hasOwnProperty(e))return XhtmlNamespace[e](t)}static a(e){return new A(e)}static b(e){return new B(e)}static body(e){return new Body(e)}static br(e){return new Br(e)}static html(e){return new Html(e)}static i(e){return new I(e)}static li(e){return new Li(e)}static ol(e){return new Ol(e)}static p(e){return new P(e)}static span(e){return new Span(e)}static sub(e){return new Sub(e)}static sup(e){return new Sup(e)}static ul(e){return new Ul(e)}}const Ao={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(e){this.namespaceId=e}[$s](e,t){return new XmlObject(this.namespaceId,e,t)}}class Root extends XFAObject{constructor(e){super(-1,"root",Object.create(null));this.element=null;this[Qs]=e}[Gs](e){this.element=e;return!0}[_r](){super[_r]();if(this.element.template instanceof Template){this[Qs].set(vs,this.element);this.element.template[Ys](this[Qs]);this.element.template[Qs]=this[Qs]}}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[Gs](e){return!1}}class Builder{constructor(e=null){this._namespaceStack=[];this._nsAgnosticLevel=0;this._namespacePrefixes=new Map;this._namespaces=new Map;this._nextNsId=Math.max(...Object.values(An).map((({id:e})=>e)));this._currentNamespace=e||new UnknownNamespace(++this._nextNsId)}buildRoot(e){return new Root(e)}build({nsPrefix:e,name:t,attributes:i,namespace:a,prefixes:r}){const s=null!==a;if(s){this._namespaceStack.push(this._currentNamespace);this._currentNamespace=this._searchNamespace(a)}r&&this._addNamespacePrefix(r);if(i.hasOwnProperty(Ns)){const e=Ao.datasets,t=i[Ns];let a=null;for(const[i,r]of Object.entries(t)){if(this._getNamespaceToUse(i)===e){a={xfa:r};break}}a?i[Ns]=a:delete i[Ns]}const n=this._getNamespaceToUse(e),o=n?.[$s](t,i)||new Empty;o[ys]()&&this._nsAgnosticLevel++;(s||r||o[ys]())&&(o[Or]={hasNamespace:s,prefixes:r,nsAgnostic:o[ys]()});return o}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(e){let t=this._namespaces.get(e);if(t)return t;for(const[i,{check:a}]of Object.entries(An))if(a(e)){t=Ao[i];if(t){this._namespaces.set(e,t);return t}break}t=new UnknownNamespace(++this._nextNsId);this._namespaces.set(e,t);return t}_addNamespacePrefix(e){for(const{prefix:t,value:i}of e){const e=this._searchNamespace(i);let a=this._namespacePrefixes.get(t);if(!a){a=[];this._namespacePrefixes.set(t,a)}a.push(e)}}_getNamespaceToUse(e){if(!e)return this._currentNamespace;const t=this._namespacePrefixes.get(e);if(t?.length>0)return t.at(-1);warn(`Unknown namespace prefix: ${e}.`);return null}clean(e){const{hasNamespace:t,prefixes:i,nsAgnostic:a}=e;t&&(this._currentNamespace=this._namespaceStack.pop());i&&i.forEach((({prefix:e})=>{this._namespacePrefixes.get(e).pop()}));a&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(e=null,t=!1){super();this._builder=new Builder(e);this._stack=[];this._globalData={usedTypefaces:new Set};this._ids=new Map;this._current=this._builder.buildRoot(this._ids);this._errorCode=Dr;this._whiteRegex=/^\s+$/;this._nbsps=/\xa0+/g;this._richText=t}parse(e){this.parseXml(e);if(this._errorCode===Dr){this._current[_r]();return this._current.element}}onText(e){e=e.replace(this._nbsps,(e=>e.slice(1)+" "));this._richText||this._current[Jr]()?this._current[Us](e,this._richText):this._whiteRegex.test(e)||this._current[Us](e.trim())}onCdata(e){this._current[Us](e)}_mkAttributes(e,t){let i=null,a=null;const r=Object.create({});for(const{name:s,value:n}of e)if("xmlns"===s)i?warn(`XFA - multiple namespace definition in <${t}>`):i=n;else if(s.startsWith("xmlns:")){const e=s.substring(6);a||(a=[]);a.push({prefix:e,value:n})}else{const e=s.indexOf(":");if(-1===e)r[s]=n;else{let t=r[Ns];t||(t=r[Ns]=Object.create(null));const[i,a]=[s.slice(0,e),s.slice(e+1)];(t[i]||=Object.create(null))[a]=n}}return[i,a,r]}_getNameAndPrefix(e,t){const i=e.indexOf(":");return-1===i?[e,null]:[e.substring(i+1),t?"":e.substring(0,i)]}onBeginElement(e,t,i){const[a,r,s]=this._mkAttributes(t,e),[n,o]=this._getNameAndPrefix(e,this._builder.isNsAgnostic()),g=this._builder.build({nsPrefix:o,name:n,attributes:s,namespace:a,prefixes:r});g[Cs]=this._globalData;if(i){g[_r]();this._current[Gs](g)&&g[Ts](this._ids);g[Tr](this._builder)}else{this._stack.push(this._current);this._current=g}}onEndElement(e){const t=this._current;if(t[ds]()&&"string"==typeof t[jr]){const e=new XFAParser;e._globalData=this._globalData;const i=e.parse(t[jr]);t[jr]=null;t[Gs](i)}t[_r]();this._current=this._stack.pop();this._current[Gs](t)&&t[Ts](this._ids);t[Tr](this._builder)}onError(e){this._errorCode=e}}class XFAFactory{constructor(e){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(e));const t=new Binder(this.root);this.form=t.bind();this.dataHandler=new DataHandler(this.root,t.getData());this.form[Cs].template=this.form}catch(e){warn(`XFA - an error occurred during parsing and binding: ${e}`)}}isValid(){return this.root&&this.form}_createPagesHelper(){const e=this.form[Xs]();return new Promise(((t,i)=>{const nextIteration=()=>{try{const i=e.next();i.done?t(i.value):setTimeout(nextIteration,0)}catch(e){i(e)}};setTimeout(nextIteration,0)}))}async _createPages(){try{this.pages=await this._createPagesHelper();this.dims=this.pages.children.map((e=>{const{width:t,height:i}=e.attributes.style;return[0,0,parseInt(t),parseInt(i)]}))}catch(e){warn(`XFA - an error occurred during layout: ${e}`)}}getBoundingBox(e){return this.dims[e]}async getNumPages(){this.pages||await this._createPages();return this.dims.length}setImages(e){this.form[Cs].images=e}setFonts(e){this.form[Cs].fontFinder=new FontFinder(e);const t=[];for(let e of this.form[Cs].usedTypefaces){e=stripQuotes(e);this.form[Cs].fontFinder.find(e)||t.push(e)}return t.length>0?t:null}appendFonts(e,t){this.form[Cs].fontFinder.add(e,t)}async getPages(){this.pages||await this._createPages();const e=this.pages;this.pages=null;return e}serializeData(e){return this.dataHandler.serialize(e)}static _createDocument(e){return e["/xdp:xdp"]?Object.values(e).join(""):e["xdp:xdp"]}static getRichTextAsHtml(e){if(!e||"string"!=typeof e)return null;try{let t=new XFAParser(XhtmlNamespace,!0).parse(e);if(!["body","xhtml"].includes(t[Rs])){const e=XhtmlNamespace.body({});e[Yr](t);t=e}const i=t[Vs]();if(!i.success)return null;const{html:a}=i,{attributes:r}=a;if(r){r.class&&(r.class=r.class.filter((e=>!e.startsWith("xfa"))));r.dir="auto"}return{html:a,str:t[js]()}}catch(e){warn(`XFA - an error occurred during parsing of rich text: ${e}`)}return null}}class AnnotationFactory{static createGlobals(e){return Promise.all([e.ensureCatalog("acroForm"),e.ensureDoc("xfaDatasets"),e.ensureCatalog("structTreeRoot"),e.ensureCatalog("baseUrl"),e.ensureCatalog("attachments")]).then((([t,i,a,r,s])=>({pdfManager:e,acroForm:t instanceof Dict?t:Dict.empty,xfaDatasets:i,structTreeRoot:a,baseUrl:r,attachments:s})),(e=>{warn(`createGlobals: "${e}".`);return null}))}static async create(e,t,i,a,r,s,n){const o=r?await this._getPageIndex(e,t,i.pdfManager):null;return i.pdfManager.ensure(this,"_create",[e,t,i,a,r,s,o,n])}static _create(e,t,i,a,r=!1,s=null,n=null,o=null){const g=e.fetchIfRef(t);if(!(g instanceof Dict))return;const{acroForm:c,pdfManager:l}=i,h=t instanceof Ref?t.toString():`annot_${a.createObjId()}`;let C=g.get("Subtype");C=C instanceof Name?C.name:null;const Q={xref:e,ref:t,dict:g,subtype:C,id:h,annotationGlobals:i,collectFields:r,orphanFields:s,needAppearances:!r&&!0===c.get("NeedAppearances"),pageIndex:n,evaluatorOptions:l.evaluatorOptions,pageRef:o};switch(C){case"Link":return new LinkAnnotation(Q);case"Text":return new TextAnnotation(Q);case"Widget":let e=getInheritableProperty({dict:g,key:"FT"});e=e instanceof Name?e.name:null;switch(e){case"Tx":return new TextWidgetAnnotation(Q);case"Btn":return new ButtonWidgetAnnotation(Q);case"Ch":return new ChoiceWidgetAnnotation(Q);case"Sig":return new SignatureWidgetAnnotation(Q)}warn(`Unimplemented widget field type "${e}", falling back to base field type.`);return new WidgetAnnotation(Q);case"Popup":return new PopupAnnotation(Q);case"FreeText":return new FreeTextAnnotation(Q);case"Line":return new LineAnnotation(Q);case"Square":return new SquareAnnotation(Q);case"Circle":return new CircleAnnotation(Q);case"PolyLine":return new PolylineAnnotation(Q);case"Polygon":return new PolygonAnnotation(Q);case"Caret":return new CaretAnnotation(Q);case"Ink":return new InkAnnotation(Q);case"Highlight":return new HighlightAnnotation(Q);case"Underline":return new UnderlineAnnotation(Q);case"Squiggly":return new SquigglyAnnotation(Q);case"StrikeOut":return new StrikeOutAnnotation(Q);case"Stamp":return new StampAnnotation(Q);case"FileAttachment":return new FileAttachmentAnnotation(Q);default:r||warn(C?`Unimplemented annotation type "${C}", falling back to base annotation.`:"Annotation is missing the required /Subtype.");return new Annotation(Q)}}static async _getPageIndex(e,t,i){try{const a=await e.fetchIfRefAsync(t);if(!(a instanceof Dict))return-1;const r=a.getRaw("P");if(r instanceof Ref)try{return await i.ensureCatalog("getPageIndex",[r])}catch(e){info(`_getPageIndex -- not a valid page reference: "${e}".`)}if(a.has("Kids"))return-1;const s=await i.ensureDoc("numPages");for(let e=0;ee/255))}function getQuadPoints(e,t){const i=e.getArray("QuadPoints");if(!isNumberArray(i,null)||0===i.length||i.length%8>0)return null;const a=new Float32Array(i.length);for(let e=0,r=i.length;et[2]||Et[3]))return null;a.set([C,u,Q,u,C,E,Q,E],e)}return a}function getTransformMatrix(e,t,i){const[a,r,s,n]=Util.getAxialAlignedBoundingBox(t,i);if(a===s||r===n)return[1,0,0,1,e[0],e[1]];const o=(e[2]-e[0])/(s-a),g=(e[3]-e[1])/(n-r);return[o,0,0,g,e[0]-a*o,e[1]-r*g]}class Annotation{constructor(e){const{dict:t,xref:i,annotationGlobals:a,ref:r,orphanFields:s}=e,n=s?.get(r);n&&t.set("Parent",n);this.setTitle(t.get("T"));this.setContents(t.get("Contents"));this.setModificationDate(t.get("M"));this.setFlags(t.get("F"));this.setRectangle(t.getArray("Rect"));this.setColor(t.getArray("C"));this.setBorderStyle(t);this.setAppearance(t);this.setOptionalContent(t);const o=t.get("MK");this.setBorderAndBackgroundColors(o);this.setRotation(o,t);this.ref=e.ref instanceof Ref?e.ref:null;this._streams=[];this.appearance&&this._streams.push(this.appearance);const g=!!(this.flags&iA),c=!!(this.flags&aA);this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:e.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:e.subtype,hasOwnCanvas:!1,noRotate:!!(this.flags&eA),noHTML:g&&c,isEditable:!1,structParent:-1};if(a.structTreeRoot){let i=t.get("StructParent");this.data.structParent=i=Number.isInteger(i)&&i>=0?i:-1;a.structTreeRoot.addAnnotationIdToPage(e.pageRef,i)}if(e.collectFields){const a=t.get("Kids");if(Array.isArray(a)){const e=[];for(const t of a)t instanceof Ref&&e.push(t.toString());0!==e.length&&(this.data.kidIds=e)}this.data.actions=collectActions(i,t,pA);this.data.fieldName=this._constructFieldName(t);this.data.pageIndex=e.pageIndex}const l=t.get("IT");l instanceof Name&&(this.data.it=l.name);this._isOffscreenCanvasSupported=e.evaluatorOptions.isOffscreenCanvasSupported;this._fallbackFontDict=null;this._needAppearances=!1}_hasFlag(e,t){return!!(e&t)}_buildFlags(e,t){let{flags:i}=this;if(void 0===e){if(void 0===t)return;return t?i&~AA:i&~$|AA}if(e){i|=AA;return t?i&~tA|$:i&~$|tA}i&=~($|tA);return t?i&~AA:i|AA}_isViewable(e){return!this._hasFlag(e,z)&&!this._hasFlag(e,tA)}_isPrintable(e){return this._hasFlag(e,AA)&&!this._hasFlag(e,$)&&!this._hasFlag(e,z)}mustBeViewed(e,t){const i=e?.get(this.data.id)?.noView;return void 0!==i?!i:this.viewable&&!this._hasFlag(this.flags,$)}mustBePrinted(e){const t=e?.get(this.data.id)?.noPrint;return void 0!==t?!t:this.printable}mustBeViewedWhenEditing(e,t=null){return e?!this.data.isEditable:!t?.has(this.data.id)}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&(0!==this.flags&&this._isPrintable(this.flags))}_parseStringHelper(e){const t="string"==typeof e?stringToPDFString(e):"";return{str:t,dir:t&&"rtl"===bidi(t).dir?"rtl":"ltr"}}setDefaultAppearance(e){const{dict:t,annotationGlobals:i}=e,a=getInheritableProperty({dict:t,key:"DA"})||i.acroForm.get("DA");this._defaultAppearance="string"==typeof a?a:"";this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(e){this._title=this._parseStringHelper(e)}setContents(e){this._contents=this._parseStringHelper(e)}setModificationDate(e){this.modificationDate="string"==typeof e?e:null}setFlags(e){this.flags=Number.isInteger(e)&&e>0?e:0;this.flags&z&&"Annotation"!==this.constructor.name&&(this.flags^=z)}hasFlag(e){return this._hasFlag(this.flags,e)}setRectangle(e){this.rectangle=lookupNormalRect(e,[0,0,0,0])}setColor(e){this.color=getRgbColor(e)}setLineEndings(e){this.lineEndings=["None","None"];if(Array.isArray(e)&&2===e.length)for(let t=0;t<2;t++){const i=e[t];if(i instanceof Name)switch(i.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[t]=i.name;continue}warn(`Ignoring invalid lineEnding: ${i}`)}}setRotation(e,t){this.rotation=0;let i=e instanceof Dict?e.get("R")||0:t.get("Rotate")||0;if(Number.isInteger(i)&&0!==i){i%=360;i<0&&(i+=360);i%90==0&&(this.rotation=i)}}setBorderAndBackgroundColors(e){if(e instanceof Dict){this.borderColor=getRgbColor(e.getArray("BC"),null);this.backgroundColor=getRgbColor(e.getArray("BG"),null)}else this.borderColor=this.backgroundColor=null}setBorderStyle(e){this.borderStyle=new AnnotationBorderStyle;if(e instanceof Dict)if(e.has("BS")){const t=e.get("BS");if(t instanceof Dict){const e=t.get("Type");if(!e||isName(e,"Border")){this.borderStyle.setWidth(t.get("W"),this.rectangle);this.borderStyle.setStyle(t.get("S"));this.borderStyle.setDashArray(t.getArray("D"))}}}else if(e.has("Border")){const t=e.getArray("Border");if(Array.isArray(t)&&t.length>=3){this.borderStyle.setHorizontalCornerRadius(t[0]);this.borderStyle.setVerticalCornerRadius(t[1]);this.borderStyle.setWidth(t[2],this.rectangle);4===t.length&&this.borderStyle.setDashArray(t[3],!0)}}else this.borderStyle.setWidth(0)}setAppearance(e){this.appearance=null;const t=e.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(i instanceof BaseStream){this.appearance=i;return}if(!(i instanceof Dict))return;const a=e.get("AS");if(!(a instanceof Name&&i.has(a.name)))return;const r=i.get(a.name);r instanceof BaseStream&&(this.appearance=r)}setOptionalContent(e){this.oc=null;const t=e.get("OC");t instanceof Name?warn("setOptionalContent: Support for /Name-entry is not implemented."):t instanceof Dict&&(this.oc=t)}loadResources(e,t){return t.dict.getAsync("Resources").then((t=>{if(!t)return;return new ObjectLoader(t,e,t.xref).load().then((function(){return t}))}))}async getOperatorList(e,t,i,r){const{hasOwnCanvas:s,id:n,rect:o}=this.data;let g=this.appearance;const l=!!(s&&i&c);if(l&&(o[0]===o[2]||o[1]===o[3])){this.data.hasOwnCanvas=!1;return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}if(!g){if(!l)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};g=new StringStream("");g.dict=new Dict}const h=g.dict,C=await this.loadResources(["ExtGState","ColorSpace","Pattern","Shading","XObject","Font"],g),Q=lookupRect(h.getArray("BBox"),[0,0,1,1]),E=lookupMatrix(h.getArray("Matrix"),a),u=getTransformMatrix(o,Q,E),d=new OperatorList;let f;this.oc&&(f=await e.parseMarkedContentProps(this.oc,null));void 0!==f&&d.addOp(Ke,["OC",f]);d.addOp(Ve,[n,o,u,E,l]);await e.getOperatorList({stream:g,task:t,resources:C,operatorList:d,fallbackFontDict:this._fallbackFontDict});d.addOp(Ze,[]);void 0!==f&&d.addOp(Te,[]);this.reset();return{opList:d,separateForm:!1,separateCanvas:l}}async save(e,t,i,a){return null}get hasTextContent(){return!1}async extractTextContent(e,t,i){if(!this.appearance)return;const a=await this.loadResources(["ExtGState","Font","Properties","XObject"],this.appearance),r=[],s=[];let n=null;const o={desiredSize:Math.Infinity,ready:!0,enqueue(e,t){for(const t of e.items)if(void 0!==t.str){n||=t.transform.slice(-2);s.push(t.str);if(t.hasEOL){r.push(s.join("").trimEnd());s.length=0}}}};await e.getTextContent({stream:this.appearance,task:t,resources:a,includeMarkedContent:!0,keepWhiteSpace:!0,sink:o,viewBox:i});this.reset();s.length&&r.push(s.join("").trimEnd());if(r.length>1||r[0]){const e=this.appearance.dict,t=lookupRect(e.getArray("BBox"),null),i=lookupMatrix(e.getArray("Matrix"),null);this.data.textPosition=this._transformPoint(n,t,i);this.data.textContent=r}}_transformPoint(e,t,i){const{rect:a}=this.data;t||=[0,0,1,1];i||=[1,0,0,1,0,0];const r=getTransformMatrix(a,t,i);r[4]-=a[0];r[5]-=a[1];e=Util.applyTransform(e,r);return Util.applyTransform(e,i)}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const e of this._streams)e.reset()}_constructFieldName(e){if(!e.has("T")&&!e.has("Parent")){warn("Unknown field name, falling back to empty field name.");return""}if(!e.has("Parent"))return stringToPDFString(e.get("T"));const t=[];e.has("T")&&t.unshift(stringToPDFString(e.get("T")));let i=e;const a=new RefSet;e.objId&&a.put(e.objId);for(;i.has("Parent");){i=i.get("Parent");if(!(i instanceof Dict)||i.objId&&a.has(i.objId))break;i.objId&&a.put(i.objId);i.has("T")&&t.unshift(stringToPDFString(i.get("T")))}return t.join(".")}}class AnnotationBorderStyle{constructor(){this.width=1;this.rawWidth=1;this.style=QA;this.dashArray=[3];this.horizontalCornerRadius=0;this.verticalCornerRadius=0}setWidth(e,t=[0,0,0,0]){if(e instanceof Name)this.width=0;else if("number"==typeof e){if(e>0){this.rawWidth=e;const i=(t[2]-t[0])/2,a=(t[3]-t[1])/2;if(i>0&&a>0&&(e>i||e>a)){warn(`AnnotationBorderStyle.setWidth - ignoring width: ${e}`);e=1}}this.width=e}}setStyle(e){if(e instanceof Name)switch(e.name){case"S":this.style=QA;break;case"D":this.style=EA;break;case"B":this.style=uA;break;case"I":this.style=dA;break;case"U":this.style=fA}}setDashArray(e,t=!1){if(Array.isArray(e)){let i=!0,a=!0;for(const t of e){if(!(+t>=0)){i=!1;break}t>0&&(a=!1)}if(0===e.length||i&&!a){this.dashArray=e;t&&this.setStyle(Name.get("D"))}else this.width=0}else e&&(this.width=0)}setHorizontalCornerRadius(e){Number.isInteger(e)&&(this.horizontalCornerRadius=e)}setVerticalCornerRadius(e){Number.isInteger(e)&&(this.verticalCornerRadius=e)}}class MarkupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;if(t.has("IRT")){const e=t.getRaw("IRT");this.data.inReplyTo=e instanceof Ref?e.toString():null;const i=t.get("RT");this.data.replyType=i instanceof Name?i.name:_}let i=null;if(this.data.replyType===Z){const e=t.get("IRT");this.setTitle(e.get("T"));this.data.titleObj=this._title;this.setContents(e.get("Contents"));this.data.contentsObj=this._contents;if(e.has("CreationDate")){this.setCreationDate(e.get("CreationDate"));this.data.creationDate=this.creationDate}else this.data.creationDate=null;if(e.has("M")){this.setModificationDate(e.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;i=e.getRaw("Popup");if(e.has("C")){this.setColor(e.getArray("C"));this.data.color=this.color}else this.data.color=null}else{this.data.titleObj=this._title;this.setCreationDate(t.get("CreationDate"));this.data.creationDate=this.creationDate;i=t.getRaw("Popup");t.has("C")||(this.data.color=null)}this.data.popupRef=i instanceof Ref?i.toString():null;t.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(t.get("RC")))}setCreationDate(e){this.creationDate="string"==typeof e?e:null}_setDefaultAppearance({xref:e,extra:t,strokeColor:i,fillColor:a,blendMode:r,strokeAlpha:s,fillAlpha:n,pointsCallback:o}){let g=Number.MAX_VALUE,c=Number.MAX_VALUE,l=Number.MIN_VALUE,h=Number.MIN_VALUE;const C=["q"];t&&C.push(t);i&&C.push(`${i[0]} ${i[1]} ${i[2]} RG`);a&&C.push(`${a[0]} ${a[1]} ${a[2]} rg`);const Q=this.data.quadPoints||Float32Array.from([this.rectangle[0],this.rectangle[3],this.rectangle[2],this.rectangle[3],this.rectangle[0],this.rectangle[1],this.rectangle[2],this.rectangle[1]]);for(let e=0,t=Q.length;e"string"==typeof e)).map((e=>stringToPDFString(e))):e instanceof Name?stringToPDFString(e.name):"string"==typeof e?stringToPDFString(e):null}hasFieldFlag(e){return!!(this.data.fieldFlags&e)}_isViewable(e){return!0}mustBeViewed(e,t){return t?this.viewable:super.mustBeViewed(e,t)&&!this._hasFlag(this.flags,tA)}getRotationMatrix(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(0===t)return a;return getRotationMatrix(t,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1])}getBorderAndBackgroundAppearances(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(!this.backgroundColor&&!this.borderColor)return"";const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],r=0===t||180===t?`0 0 ${i} ${a} re`:`0 0 ${a} ${i} re`;let s="";this.backgroundColor&&(s=`${getPdfColor(this.backgroundColor,!0)} ${r} f `);if(this.borderColor){s+=`${this.borderStyle.width||1} w ${getPdfColor(this.borderColor,!1)} ${r} S `}return s}async getOperatorList(e,t,i,a){if(i&C&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(e,t,i,a);const r=await this._getAppearance(e,t,i,a);if(this.appearance&&null===r)return super.getOperatorList(e,t,i,a);const s=new OperatorList;if(!this._defaultAppearance||null===r)return{opList:s,separateForm:!1,separateCanvas:!1};const n=!!(this.data.hasOwnCanvas&&i&c),o=[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]],g=getTransformMatrix(this.data.rect,o,[1,0,0,1,0,0]);let l;this.oc&&(l=await e.parseMarkedContentProps(this.oc,null));void 0!==l&&s.addOp(Ke,["OC",l]);s.addOp(Ve,[this.data.id,this.data.rect,g,this.getRotationMatrix(a),n]);const h=new StringStream(r);await e.getOperatorList({stream:h,task:t,resources:this._fieldResources.mergedResources,operatorList:s});s.addOp(Ze,[]);void 0!==l&&s.addOp(Te,[]);return{opList:s,separateForm:!1,separateCanvas:n}}_getMKDict(e){const t=new Dict(null);e&&t.set("R",e);this.borderColor&&t.set("BC",getPdfColorArray(this.borderColor));this.backgroundColor&&t.set("BG",getPdfColorArray(this.backgroundColor));return t.size>0?t:null}amendSavedDict(e,t){}setValue(e,t,i,a){const{dict:r,ref:s}=function getParentToUpdate(e,t,i){const a=new RefSet,r=e,s={dict:null,ref:null};for(;e instanceof Dict&&!a.has(t);){a.put(t);if(e.has("T"))break;if(!((t=e.getRaw("Parent"))instanceof Ref))return s;e=i.fetch(t)}if(e instanceof Dict&&e!==r){s.dict=e;s.ref=t}return s}(e,this.ref,i);if(r){if(!a.has(s)){const e=r.clone();e.set("V",t);a.put(s,{data:e});return e}}else e.set("V",t);return null}async save(e,t,i,r){const s=i?.get(this.data.id),n=this._buildFlags(s?.noView,s?.noPrint);let o=s?.value,g=s?.rotation;if(o===this.data.fieldValue||void 0===o){if(!this._hasValueFromXFA&&void 0===g&&void 0===n)return;o||=this.data.fieldValue}if(void 0===g&&!this._hasValueFromXFA&&Array.isArray(o)&&Array.isArray(this.data.fieldValue)&&isArrayEqual(o,this.data.fieldValue)&&void 0===n)return;void 0===g&&(g=this.rotation);let c=null;if(!this._needAppearances){c=await this._getAppearance(e,t,h,i);if(null===c&&void 0===n)return}let l=!1;if(c?.needAppearances){l=!0;c=null}const{xref:C}=e,Q=C.fetchIfRef(this.ref);if(!(Q instanceof Dict))return;const E=new Dict(C);for(const e of Q.getKeys())"AP"!==e&&E.set(e,Q.getRaw(e));if(void 0!==n){E.set("F",n);if(null===c&&!l){const e=Q.getRaw("AP");e&&E.set("AP",e)}}const u={path:this.data.fieldName,value:o},d=this.setValue(E,Array.isArray(o)?o.map(stringToAsciiOrUTF16BE):stringToAsciiOrUTF16BE(o),C,r);this.amendSavedDict(i,d||E);const f=this._getMKDict(g);f&&E.set("MK",f);r.put(this.ref,{data:E,xfa:u,needAppearances:l});if(null!==c){const e=C.getNewTemporaryRef(),t=new Dict(C);E.set("AP",t);t.set("N",e);const s=this._getSaveFieldResources(C),n=new StringStream(c),o=n.dict=new Dict(C);o.set("Subtype",Name.get("Form"));o.set("Resources",s);o.set("BBox",[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]]);const g=this.getRotationMatrix(i);g!==a&&o.set("Matrix",g);r.put(e,{data:n,xfa:null,needAppearances:!1})}E.set("M",`D:${getModificationDate()}`)}async _getAppearance(e,t,i,a){if(this.hasFieldFlag(oA))return null;const r=a?.get(this.data.id);let s,n;if(r){s=r.formattedValue||r.value;n=r.rotation}if(void 0===n&&void 0===s&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const g=this.getBorderAndBackgroundAppearances(a);if(void 0===s){s=this.data.fieldValue;if(!s)return`/Tx BMC q ${g}Q EMC`}Array.isArray(s)&&1===s.length&&(s=s[0]);assert("string"==typeof s,"Expected `value` to be a string.");s=s.trimEnd();if(this.data.combo){const e=this.data.options.find((({exportValue:e})=>s===e));s=e?.displayValue||s}if(""===s)return`/Tx BMC q ${g}Q EMC`;void 0===n&&(n=this.rotation);let c,l=-1;if(this.data.multiLine){c=s.split(/\r\n?|\n/).map((e=>e.normalize("NFC")));l=c.length}else c=[s.replace(/\r\n?|\n/,"").normalize("NFC")];let C=this.data.rect[3]-this.data.rect[1],Q=this.data.rect[2]-this.data.rect[0];90!==n&&270!==n||([Q,C]=[C,Q]);this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let E,u,d,f=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const p=[];let m=!1;for(const e of c){const t=f.encodeString(e);t.length>1&&(m=!0);p.push(t.join(""))}if(m&&i&h)return{needAppearances:!0};if(m&&this._isOffscreenCanvasSupported){const i=this.data.comb?"monospace":"sans-serif",a=new FakeUnicodeFont(e.xref,i),r=a.createFontResources(c.join("")),n=r.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const e=this._fieldResources.mergedResources.get("Font");for(const t of n.getKeys())e.set(t,n.getRaw(t))}else this._fieldResources.mergedResources.set("Font",n);const o=a.fontName.name;f=await WidgetAnnotation._getFontData(e,t,{fontName:o,fontSize:0},r);for(let e=0,t=p.length;e2)return`/Tx BMC q ${g}BT `+E+` 1 0 0 1 ${numberToString(2)} ${numberToString(D)} Tm (${escapeString(p[0])}) Tj ET Q EMC`;return`/Tx BMC q ${g}BT `+E+` 1 0 0 1 0 0 Tm ${this._renderText(p[0],f,u,Q,b,{shift:0},2,D)} ET Q EMC`}static async _getFontData(e,t,i,a){const r=new OperatorList,s={font:null,clone(){return this}},{fontName:n,fontSize:o}=i;await e.handleSetFont(a,[n&&Name.get(n),o],null,r,t,s,null);return s.font}_getTextWidth(e,t){return t.charsToGlyphs(e).reduce(((e,t)=>e+t.width),0)/1e3}_computeFontSize(e,t,i,a,r){let{fontSize:n}=this.data.defaultAppearanceData,o=(n||12)*s,g=Math.round(e/o);if(!n){const roundWithTwoDigits=e=>Math.floor(100*e)/100;if(-1===r){const r=this._getTextWidth(i,a);n=roundWithTwoDigits(Math.min(e/s,t/r));g=1}else{const c=i.split(/\r\n?|\n/),l=[];for(const e of c){const t=a.encodeString(e).join(""),i=a.charsToGlyphs(t),r=a.getCharPositions(t);l.push({line:t,glyphs:i,positions:r})}const isTooBig=i=>{let r=0;for(const s of l){r+=this._splitLine(null,a,i,t,s).length*i;if(r>e)return!0}return!1};g=Math.max(g,r);for(;;){o=e/g;n=roundWithTwoDigits(o/s);if(!isTooBig(n))break;g++}}const{fontName:c,fontColor:l}=this.data.defaultAppearanceData;this._defaultAppearance=function createDefaultAppearance({fontSize:e,fontName:t,fontColor:i}){return`/${escapePDFName(t)} ${e} Tf ${getPdfColor(i,!0)}`}({fontSize:n,fontName:c,fontColor:l})}return[this._defaultAppearance,n,e/g]}_renderText(e,t,i,a,r,s,n,o){let g;if(1===r){g=(a-this._getTextWidth(e,t)*i)/2}else if(2===r){g=a-this._getTextWidth(e,t)*i-n}else g=n;const c=numberToString(g-s.shift);s.shift=g;return`${c} ${o=numberToString(o)} Td (${escapeString(e)}) Tj`}_getSaveFieldResources(e){const{localResources:t,appearanceResources:i,acroFormResources:a}=this._fieldResources,r=this.data.defaultAppearanceData?.fontName;if(!r)return t||Dict.empty;for(const e of[t,i])if(e instanceof Dict){const t=e.get("Font");if(t instanceof Dict&&t.has(r))return e}if(a instanceof Dict){const i=a.get("Font");if(i instanceof Dict&&i.has(r)){const a=new Dict(e);a.set(r,i.getRaw(r));const s=new Dict(e);s.set("Font",a);return Dict.merge({xref:e,dictArray:[s,t],mergeSubDicts:!0})}}return t||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t}=e;if(t.has("PMD")){this.flags|=$;this.data.hidden=!0;warn("Barcodes are not supported")}this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML;this._hasText=!0;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let i=getInheritableProperty({dict:t,key:"Q"});(!Number.isInteger(i)||i<0||i>2)&&(i=null);this.data.textAlignment=i;let a=getInheritableProperty({dict:t,key:"MaxLen"});(!Number.isInteger(a)||a<0)&&(a=0);this.data.maxLen=a;this.data.multiLine=this.hasFieldFlag(nA);this.data.comb=this.hasFieldFlag(BA)&&!this.hasFieldFlag(nA)&&!this.hasFieldFlag(oA)&&!this.hasFieldFlag(lA)&&0!==this.data.maxLen;this.data.doNotScroll=this.hasFieldFlag(CA)}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(e,t,i,a,r,s,n,o,g,c,l){const h=r/this.data.maxLen,C=this.getBorderAndBackgroundAppearances(l),Q=[],E=t.getCharPositions(i);for(const[e,t]of E)Q.push(`(${escapeString(i.substring(e,t))}) Tj`);const u=Q.join(` ${numberToString(h)} 0 Td `);return`/Tx BMC q ${C}BT `+e+` 1 0 0 1 ${numberToString(n)} ${numberToString(o+g)} Tm ${u} ET Q EMC`}_getMultilineAppearance(e,t,i,a,r,s,n,o,g,c,l,h){const C=[],Q=r-2*o,E={shift:0};for(let e=0,s=t.length;ea){g.push(e.substring(C,i));C=i;Q=u;c=-1;h=-1}else{Q+=u;c=i;l=r;h=t}else if(Q+u>a)if(-1!==c){g.push(e.substring(C,l));C=l;t=h+1;c=-1;Q=0}else{g.push(e.substring(C,i));C=i;Q=u}else Q+=u}Ct?`\\${t}`:"\\s+"));new RegExp(`^\\s*${s}\\s*$`).test(this.data.fieldValue)&&(this.data.textContent=this.data.fieldValue.split("\n"))}getFieldObject(){return{id:this.data.id,value:this.data.fieldValue,defaultValue:this.data.defaultFieldValue||"",multiline:this.data.multiLine,password:this.hasFieldFlag(oA),charLimit:this.data.maxLen,comb:this.data.comb,editable:!this.data.readOnly,hidden:this.data.hidden,name:this.data.fieldName,rect:this.data.rect,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:"text"}}}class ButtonWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.checkedAppearance=null;this.uncheckedAppearance=null;this.data.checkBox=!this.hasFieldFlag(gA)&&!this.hasFieldFlag(IA);this.data.radioButton=this.hasFieldFlag(gA)&&!this.hasFieldFlag(IA);this.data.pushButton=this.hasFieldFlag(IA);this.data.isTooltipOnly=!1;if(this.data.checkBox)this._processCheckBox(e);else if(this.data.radioButton)this._processRadioButton(e);else if(this.data.pushButton){this.data.hasOwnCanvas=!0;this.data.noHTML=!1;this._processPushButton(e)}else warn("Invalid field flags for button widget annotation")}async getOperatorList(e,t,i,r){if(this.data.pushButton)return super.getOperatorList(e,t,i,!1,r);let s=null,n=null;if(r){const e=r.get(this.data.id);s=e?e.value:null;n=e?e.rotation:null}if(null===s&&this.appearance)return super.getOperatorList(e,t,i,r);null==s&&(s=this.data.checkBox?this.data.fieldValue===this.data.exportValue:this.data.fieldValue===this.data.buttonValue);const o=s?this.checkedAppearance:this.uncheckedAppearance;if(o){const s=this.appearance,g=lookupMatrix(o.dict.getArray("Matrix"),a);n&&o.dict.set("Matrix",this.getRotationMatrix(r));this.appearance=o;const c=super.getOperatorList(e,t,i,r);this.appearance=s;o.dict.set("Matrix",g);return c}return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}async save(e,t,i,a){this.data.checkBox?this._saveCheckbox(e,t,i,a):this.data.radioButton&&this._saveRadioButton(e,t,i,a)}async _saveCheckbox(e,t,i,a){if(!i)return;const r=i.get(this.data.id),s=this._buildFlags(r?.noView,r?.noPrint);let n=r?.rotation,o=r?.value;if(void 0===n&&void 0===s){if(void 0===o)return;if(this.data.fieldValue===this.data.exportValue===o)return}let g=e.xref.fetchIfRef(this.ref);if(!(g instanceof Dict))return;g=g.clone();void 0===n&&(n=this.rotation);void 0===o&&(o=this.data.fieldValue===this.data.exportValue);const c={path:this.data.fieldName,value:o?this.data.exportValue:""},l=Name.get(o?this.data.exportValue:"Off");this.setValue(g,l,e.xref,a);g.set("AS",l);g.set("M",`D:${getModificationDate()}`);void 0!==s&&g.set("F",s);const h=this._getMKDict(n);h&&g.set("MK",h);a.put(this.ref,{data:g,xfa:c,needAppearances:!1})}async _saveRadioButton(e,t,i,a){if(!i)return;const r=i.get(this.data.id),s=this._buildFlags(r?.noView,r?.noPrint);let n=r?.rotation,o=r?.value;if(void 0===n&&void 0===s){if(void 0===o)return;if(this.data.fieldValue===this.data.buttonValue===o)return}let g=e.xref.fetchIfRef(this.ref);if(!(g instanceof Dict))return;g=g.clone();void 0===o&&(o=this.data.fieldValue===this.data.buttonValue);void 0===n&&(n=this.rotation);const c={path:this.data.fieldName,value:o?this.data.buttonValue:""},l=Name.get(o?this.data.buttonValue:"Off");o&&this.setValue(g,l,e.xref,a);g.set("AS",l);g.set("M",`D:${getModificationDate()}`);void 0!==s&&g.set("F",s);const h=this._getMKDict(n);h&&g.set("MK",h);a.put(this.ref,{data:g,xfa:c,needAppearances:!1})}_getDefaultCheckedAppearance(e,t){const i=this.data.rect[2]-this.data.rect[0],a=this.data.rect[3]-this.data.rect[1],r=[0,0,i,a],s=.8*Math.min(i,a);let n,o;if("check"===t){n={width:.755*s,height:.705*s};o="3"}else if("disc"===t){n={width:.791*s,height:.705*s};o="l"}else unreachable(`_getDefaultCheckedAppearance - unsupported type: ${t}`);const g=`q BT /PdfJsZaDb ${s} Tf 0 g ${numberToString((i-n.width)/2)} ${numberToString((a-n.height)/2)} Td (${o}) Tj ET Q`,c=new Dict(e.xref);c.set("FormType",1);c.set("Subtype",Name.get("Form"));c.set("Type",Name.get("XObject"));c.set("BBox",r);c.set("Matrix",[1,0,0,1,0,0]);c.set("Length",g.length);const l=new Dict(e.xref),h=new Dict(e.xref);h.set("PdfJsZaDb",this.fallbackFontDict);l.set("Font",h);c.set("Resources",l);this.checkedAppearance=new StringStream(g);this.checkedAppearance.dict=c;this._streams.push(this.checkedAppearance)}_processCheckBox(e){const t=e.dict.get("AP");if(!(t instanceof Dict))return;const i=t.get("N");if(!(i instanceof Dict))return;const a=this._decodeFormValue(e.dict.get("AS"));"string"==typeof a&&(this.data.fieldValue=a);const r=null!==this.data.fieldValue&&"Off"!==this.data.fieldValue?this.data.fieldValue:"Yes",s=i.getKeys();if(0===s.length)s.push("Off",r);else if(1===s.length)"Off"===s[0]?s.push(r):s.unshift("Off");else if(s.includes(r)){s.length=0;s.push("Off",r)}else{const e=s.find((e=>"Off"!==e));s.length=0;s.push("Off",e)}s.includes(this.data.fieldValue)||(this.data.fieldValue="Off");this.data.exportValue=s[1];const n=i.get(this.data.exportValue);this.checkedAppearance=n instanceof BaseStream?n:null;const o=i.get("Off");this.uncheckedAppearance=o instanceof BaseStream?o:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"check");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(e){this.data.buttonValue=null;const t=e.dict.get("Parent");if(t instanceof Dict){this.parent=e.dict.getRaw("Parent");const i=t.get("V");i instanceof Name&&(this.data.fieldValue=this._decodeFormValue(i))}const i=e.dict.get("AP");if(!(i instanceof Dict))return;const a=i.get("N");if(!(a instanceof Dict))return;for(const e of a.getKeys())if("Off"!==e){this.data.buttonValue=this._decodeFormValue(e);break}const r=a.get(this.data.buttonValue);this.checkedAppearance=r instanceof BaseStream?r:null;const s=a.get("Off");this.uncheckedAppearance=s instanceof BaseStream?s:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"disc");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(e){const{dict:t,annotationGlobals:i}=e;if(t.has("A")||t.has("AA")||this.data.alternativeText){this.data.isTooltipOnly=!t.has("A")&&!t.has("AA");Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:i.baseUrl,docAttachments:i.attachments})}else warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let e,t="button";if(this.data.checkBox){t="checkbox";e=this.data.exportValue}else if(this.data.radioButton){t="radiobutton";e=this.data.buttonValue}return{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:e,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:t}}get fallbackFontDict(){const e=new Dict;e.set("BaseFont",Name.get("ZapfDingbats"));e.set("Type",Name.get("FallbackType"));e.set("Subtype",Name.get("FallbackType"));e.set("Encoding",Name.get("ZapfDingbatsEncoding"));return shadow(this,"fallbackFontDict",e)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.indices=t.getArray("I");this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0;this.data.options=[];const a=getInheritableProperty({dict:t,key:"Opt"});if(Array.isArray(a))for(let e=0,t=a.length;e=0&&t0&&(this.data.options=this.data.fieldValue.map((e=>({exportValue:e,displayValue:e}))));this.data.combo=this.hasFieldFlag(cA);this.data.multiSelect=this.hasFieldFlag(hA);this._hasText=!0}getFieldObject(){const e=this.data.combo?"combobox":"listbox",t=this.data.fieldValue.length>0?this.data.fieldValue[0]:null;return{id:this.data.id,value:t,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}amendSavedDict(e,t){if(!this.hasIndices)return;let i=e?.get(this.data.id)?.value;Array.isArray(i)||(i=[i]);const a=[],{options:r}=this.data;for(let e=0,t=0,s=r.length;ei){i=a;t=e}}[Q,E]=this._computeFontSize(e,c-4,t,C,-1)}const u=E*s,d=(u-E)/2,f=Math.floor(g/u);let p=0;if(h.length>0){const e=Math.min(...h),t=Math.max(...h);p=Math.max(0,t-f+1);p>e&&(p=e)}const m=Math.min(p+f+1,l),y=["/Tx BMC q",`1 1 ${c} ${g} re W n`];if(h.length){y.push("0.600006 0.756866 0.854904 rg");for(const e of h)p<=e&&ee.trimEnd()));const{coords:e,bbox:t,matrix:i}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,a);this.data.textPosition=this._transformPoint(e,t,i)}if(this._isOffscreenCanvasSupported){const r=e.dict.get("CA"),s=new FakeUnicodeFont(i,"sans-serif");this.appearance=s.createAppearance(this._contents.str,this.rectangle,this.rotation,a,t,r);this._streams.push(this.appearance)}else warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(e,t,{apRef:i,ap:a}){const{color:r,fontSize:s,oldAnnotation:n,rect:o,rotation:g,user:c,value:l}=e,h=n||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("FreeText"));if(n){h.set("M",`D:${getModificationDate()}`);h.delete("RC")}else h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",o);const C=`/Helv ${s} Tf ${getPdfColor(r,!0)}`;h.set("DA",C);h.set("Contents",stringToAsciiOrUTF16BE(l));h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",g);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);i?e.set("N",i):e.set("N",a)}return h}static async createNewAppearanceStream(e,t,i){const{baseFontRef:a,evaluator:r,task:n}=i,{color:o,fontSize:g,rect:c,rotation:l,value:h}=e,C=new Dict(t),Q=new Dict(t);if(a)Q.set("Helv",a);else{const e=new Dict(t);e.set("BaseFont",Name.get("Helvetica"));e.set("Type",Name.get("Font"));e.set("Subtype",Name.get("Type1"));e.set("Encoding",Name.get("WinAnsiEncoding"));Q.set("Helv",e)}C.set("Font",Q);const E=await WidgetAnnotation._getFontData(r,n,{fontName:"Helv",fontSize:g},C),[u,d,f,p]=c;let m=f-u,y=p-d;l%180!=0&&([m,y]=[y,m]);const w=h.split("\n"),b=g/1e3;let D=-1/0;const S=[];for(let e of w){const t=E.encodeString(e);if(t.length>1)return null;e=t.join("");S.push(e);let i=0;const a=E.charsToGlyphs(e);for(const e of a)i+=e.width*b;D=Math.max(D,i)}let k=1;D>m&&(k=m/D);let R=1;const N=s*g,G=1*g,M=N*w.length;M>y&&(R=y/M);const U=g*Math.min(k,R);let x,L,H;switch(l){case 0:H=[1,0,0,1];L=[c[0],c[1],m,y];x=[c[0],c[3]-G];break;case 90:H=[0,1,-1,0];L=[c[1],-c[2],m,y];x=[c[1],-c[0]-G];break;case 180:H=[-1,0,0,-1];L=[-c[2],-c[3],m,y];x=[-c[2],-c[1]-G];break;case 270:H=[0,-1,1,0];L=[-c[3],c[0],m,y];x=[-c[3],c[2]-G]}const J=["q",`${H.join(" ")} 0 0 cm`,`${L.join(" ")} re W n`,"BT",`${getPdfColor(o,!0)}`,`0 Tc /Helv ${numberToString(U)} Tf`];J.push(`${x.join(" ")} Td (${escapeString(S[0])}) Tj`);const v=numberToString(N);for(let e=1,t=S.length;e{e.push(`${a[0]} ${a[1]} m`,`${a[2]} ${a[3]} l`,"S");return[t[0]-g,t[2]+g,t[7]-g,t[3]+g]}})}}}class SquareAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=x;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),r=getRgbColor(t.getArray("IC"),null),s=r?getPdfColorArray(r):null,n=s?a:null;if(0===this.borderStyle.width&&!s)return;this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:s,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[4]+this.borderStyle.width/2,a=t[5]+this.borderStyle.width/2,r=t[6]-t[4]-this.borderStyle.width,n=t[3]-t[7]-this.borderStyle.width;e.push(`${i} ${a} ${r} ${n} re`);s?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=L;if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),r=getRgbColor(t.getArray("IC"),null),s=r?getPdfColorArray(r):null,n=s?a:null;if(0===this.borderStyle.width&&!s)return;const o=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:i,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:s,strokeAlpha:a,fillAlpha:n,pointsCallback:(e,t)=>{const i=t[0]+this.borderStyle.width/2,a=t[1]-this.borderStyle.width/2,r=t[6]-this.borderStyle.width/2,n=t[7]+this.borderStyle.width/2,g=i+(r-i)/2,c=a+(n-a)/2,l=(r-i)/2*o,h=(n-a)/2*o;e.push(`${g} ${n} m`,`${g+l} ${n} ${r} ${c+h} ${r} ${c} c`,`${r} ${c-h} ${g+l} ${a} ${g} ${a} c`,`${g-l} ${a} ${i} ${c-h} ${i} ${c} c`,`${i} ${c+h} ${g-l} ${n} ${g} ${n} c`,"h");s?e.push("B"):e.push("S");return[t[0],t[2],t[7],t[3]]}})}}}class PolylineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=J;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.vertices=null;if(!(this instanceof PolygonAnnotation)){this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings}const a=t.getArray("Vertices");if(!isNumberArray(a,null))return;const r=this.data.vertices=Float32Array.from(a);if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA"),s=this.borderStyle.width||1,n=2*s,o=[1/0,1/0,-1/0,-1/0];for(let e=0,t=r.length;e{for(let t=0,i=r.length;t{for(const t of this.data.inkLists){for(let i=0,a=t.length;ie/255)));Q.set("CA",n);const u=new Dict(t);Q.set("AP",u);i?u.set("N",i):u.set("N",a);return Q}static async createNewAppearanceStream(e,t,i){if(e.outlines)return this.createNewAppearanceStreamForHighlight(e,t,i);const{color:a,rect:r,paths:s,thickness:n,opacity:o}=e,g=[`${n} w 1 J 1 j`,`${getPdfColor(a,!1)}`];1!==o&&g.push("/R0 gs");for(const e of s.lines){g.push(`${numberToString(e[4])} ${numberToString(e[5])} m`);for(let t=6,i=e.length;t{e.push(`${t[0]} ${t[1]} m`,`${t[2]} ${t[3]} l`,`${t[6]} ${t[7]} l`,`${t[4]} ${t[5]} l`,"f");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}static createNewDict(e,t,{apRef:i,ap:a}){const{color:r,oldAnnotation:s,opacity:n,rect:o,rotation:g,user:c,quadPoints:l}=e,h=s||new Dict(t);h.set("Type",Name.get("Annot"));h.set("Subtype",Name.get("Highlight"));h.set(s?"M":"CreationDate",`D:${getModificationDate()}`);h.set("CreationDate",`D:${getModificationDate()}`);h.set("Rect",o);h.set("F",4);h.set("Border",[0,0,0]);h.set("Rotate",g);h.set("QuadPoints",l);h.set("C",Array.from(r,(e=>e/255)));h.set("CA",n);c&&h.set("T",stringToAsciiOrUTF16BE(c));if(i||a){const e=new Dict(t);h.set("AP",e);e.set("N",i||a)}return h}static async createNewAppearanceStream(e,t,i){const{color:a,rect:r,outlines:s,opacity:n}=e,o=[`${getPdfColor(a,!0)}`,"/R0 gs"],g=[];for(const e of s){g.length=0;g.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);for(let t=2,i=e.length;t{e.push(`${t[4]} ${t[5]+1.3} m`,`${t[6]} ${t[7]+1.3} l`,"S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class SquigglyAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:i}=e;this.data.annotationType=K;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=this.color?getPdfColorArray(this.color):[0,0,0],a=t.get("CA");this._setDefaultAppearance({xref:i,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:a,pointsCallback:(e,t)=>{const i=(t[1]-t[5])/6;let a=i,r=t[4];const s=t[5],n=t[6];e.push(`${r} ${s+a} m`);do{r+=2;a=0===a?i:0;e.push(`${r} ${s+a} l`)}while(r{e.push((t[0]+t[4])/2+" "+(t[1]+t[5])/2+" m",(t[2]+t[6])/2+" "+(t[3]+t[7])/2+" l","S");return[t[0],t[2],t[7],t[3]]}})}}else this.data.popupRef=null}}class StampAnnotation extends MarkupAnnotation{#T;constructor(e){super(e);this.data.annotationType=q;this.#T=this.data.hasOwnCanvas=this.data.noRotate;this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1}mustBeViewedWhenEditing(e,t=null){if(e){if(!this.data.isEditable)return!1;this.#T=this.data.hasOwnCanvas;this.data.hasOwnCanvas=!0;return!0}this.data.hasOwnCanvas=this.#T;return!t?.has(this.data.id)}static async createImage(e,t){const{width:i,height:a}=e,r=new OffscreenCanvas(i,a),s=r.getContext("2d",{alpha:!0});s.drawImage(e,0,0);const n=s.getImageData(0,0,i,a).data,o=new Uint32Array(n.buffer),g=o.some(FeatureTest.isLittleEndian?e=>e>>>24!=255:e=>!!(255&~e));if(g){s.fillStyle="white";s.fillRect(0,0,i,a);s.drawImage(e,0,0)}const c=r.convertToBlob({type:"image/jpeg",quality:1}).then((e=>e.arrayBuffer())),l=Name.get("XObject"),h=Name.get("Image"),C=new Dict(t);C.set("Type",l);C.set("Subtype",h);C.set("BitsPerComponent",8);C.set("ColorSpace",Name.get("DeviceRGB"));C.set("Filter",Name.get("DCTDecode"));C.set("BBox",[0,0,i,a]);C.set("Width",i);C.set("Height",a);let Q=null;if(g){const e=new Uint8Array(o.length);if(FeatureTest.isLittleEndian)for(let t=0,i=o.length;t>>24;else for(let t=0,i=o.length;t=0&&s<=1?s:null}}class DecryptStream extends DecodeStream{constructor(e,t,i){super(t);this.str=e;this.dict=e.dict;this.decrypt=i;this.nextChunk=null;this.initialized=!1}readBlock(){let e;if(this.initialized)e=this.nextChunk;else{e=this.str.getBytes(512);this.initialized=!0}if(!e?.length){this.eof=!0;return}this.nextChunk=this.str.getBytes(512);const t=this.nextChunk?.length>0;e=(0,this.decrypt)(e,!t);const i=this.bufferLength,a=i+e.length;this.ensureBuffer(a).set(e,i);this.bufferLength=a}}class ARCFourCipher{constructor(e){this.a=0;this.b=0;const t=new Uint8Array(256),i=e.length;for(let e=0;e<256;++e)t[e]=e;for(let a=0,r=0;a<256;++a){const s=t[a];r=r+s+e[a%i]&255;t[a]=t[r];t[r]=s}this.s=t}encryptBlock(e){let t=this.a,i=this.b;const a=this.s,r=e.length,s=new Uint8Array(r);for(let n=0;n>5&255;l[h++]=r>>13&255;l[h++]=r>>21&255;l[h++]=r>>>29&255;l[h++]=0;l[h++]=0;l[h++]=0;const E=new Int32Array(16);for(h=0;h>>32-o)|0;r=s}s=s+r|0;n=n+c|0;o=o+Q|0;g=g+u|0}return new Uint8Array([255&s,s>>8&255,s>>16&255,s>>>24&255,255&n,n>>8&255,n>>16&255,n>>>24&255,255&o,o>>8&255,o>>16&255,o>>>24&255,255&g,g>>8&255,g>>16&255,g>>>24&255])}}();class Word64{constructor(e,t){this.high=0|e;this.low=0|t}and(e){this.high&=e.high;this.low&=e.low}xor(e){this.high^=e.high;this.low^=e.low}or(e){this.high|=e.high;this.low|=e.low}shiftRight(e){if(e>=32){this.low=this.high>>>e-32|0;this.high=0}else{this.low=this.low>>>e|this.high<<32-e;this.high=this.high>>>e|0}}shiftLeft(e){if(e>=32){this.high=this.low<>>32-e;this.low<<=e}}rotateRight(e){let t,i;if(32&e){i=this.low;t=this.high}else{t=this.low;i=this.high}e&=31;this.low=t>>>e|i<<32-e;this.high=i>>>e|t<<32-e}not(){this.high=~this.high;this.low=~this.low}add(e){const t=(this.low>>>0)+(e.low>>>0);let i=(this.high>>>0)+(e.high>>>0);t>4294967295&&(i+=1);this.low=0|t;this.high=0|i}copyTo(e,t){e[t]=this.high>>>24&255;e[t+1]=this.high>>16&255;e[t+2]=this.high>>8&255;e[t+3]=255&this.high;e[t+4]=this.low>>>24&255;e[t+5]=this.low>>16&255;e[t+6]=this.low>>8&255;e[t+7]=255&this.low}assign(e){this.high=e.high;this.low=e.low}}const to=function calculateSHA256Closure(){function rotr(e,t){return e>>>t|e<<32-t}function ch(e,t,i){return e&t^~e&i}function maj(e,t,i){return e&t^e&i^t&i}function sigma(e){return rotr(e,2)^rotr(e,13)^rotr(e,22)}function sigmaPrime(e){return rotr(e,6)^rotr(e,11)^rotr(e,25)}function littleSigma(e){return rotr(e,7)^rotr(e,18)^e>>>3}const e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];return function hash(t,i,a){let r=1779033703,s=3144134277,n=1013904242,o=2773480762,g=1359893119,c=2600822924,l=528734635,h=1541459225;const C=64*Math.ceil((a+9)/64),Q=new Uint8Array(C);let E,u;for(E=0;E>>29&255;Q[E++]=a>>21&255;Q[E++]=a>>13&255;Q[E++]=a>>5&255;Q[E++]=a<<3&255;const f=new Uint32Array(64);for(E=0;E>>10)+f[u-7]+littleSigma(f[u-15])+f[u-16]|0;let t,i,a=r,C=s,d=n,m=o,y=g,w=c,b=l,D=h;for(u=0;u<64;++u){t=D+sigmaPrime(y)+ch(y,w,b)+e[u]+f[u];i=sigma(a)+maj(a,C,d);D=b;b=w;w=y;y=m+t|0;m=d;d=C;C=a;a=t+i|0}r=r+a|0;s=s+C|0;n=n+d|0;o=o+m|0;g=g+y|0;c=c+w|0;l=l+b|0;h=h+D|0}var p;return new Uint8Array([r>>24&255,r>>16&255,r>>8&255,255&r,s>>24&255,s>>16&255,s>>8&255,255&s,n>>24&255,n>>16&255,n>>8&255,255&n,o>>24&255,o>>16&255,o>>8&255,255&o,g>>24&255,g>>16&255,g>>8&255,255&g,c>>24&255,c>>16&255,c>>8&255,255&c,l>>24&255,l>>16&255,l>>8&255,255&l,h>>24&255,h>>16&255,h>>8&255,255&h])}}(),io=function calculateSHA512Closure(){function ch(e,t,i,a,r){e.assign(t);e.and(i);r.assign(t);r.not();r.and(a);e.xor(r)}function maj(e,t,i,a,r){e.assign(t);e.and(i);r.assign(t);r.and(a);e.xor(r);r.assign(i);r.and(a);e.xor(r)}function sigma(e,t,i){e.assign(t);e.rotateRight(28);i.assign(t);i.rotateRight(34);e.xor(i);i.assign(t);i.rotateRight(39);e.xor(i)}function sigmaPrime(e,t,i){e.assign(t);e.rotateRight(14);i.assign(t);i.rotateRight(18);e.xor(i);i.assign(t);i.rotateRight(41);e.xor(i)}function littleSigma(e,t,i){e.assign(t);e.rotateRight(1);i.assign(t);i.rotateRight(8);e.xor(i);i.assign(t);i.shiftRight(7);e.xor(i)}function littleSigmaPrime(e,t,i){e.assign(t);e.rotateRight(19);i.assign(t);i.rotateRight(61);e.xor(i);i.assign(t);i.shiftRight(6);e.xor(i)}const e=[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)];return function hash(t,i,a,r=!1){let s,n,o,g,c,l,h,C;if(r){s=new Word64(3418070365,3238371032);n=new Word64(1654270250,914150663);o=new Word64(2438529370,812702999);g=new Word64(355462360,4144912697);c=new Word64(1731405415,4290775857);l=new Word64(2394180231,1750603025);h=new Word64(3675008525,1694076839);C=new Word64(1203062813,3204075428)}else{s=new Word64(1779033703,4089235720);n=new Word64(3144134277,2227873595);o=new Word64(1013904242,4271175723);g=new Word64(2773480762,1595750129);c=new Word64(1359893119,2917565137);l=new Word64(2600822924,725511199);h=new Word64(528734635,4215389547);C=new Word64(1541459225,327033209)}const Q=128*Math.ceil((a+17)/128),E=new Uint8Array(Q);let u,d;for(u=0;u>>29&255;E[u++]=a>>21&255;E[u++]=a>>13&255;E[u++]=a>>5&255;E[u++]=a<<3&255;const p=new Array(80);for(u=0;u<80;u++)p[u]=new Word64(0,0);let m=new Word64(0,0),y=new Word64(0,0),w=new Word64(0,0),b=new Word64(0,0),D=new Word64(0,0),S=new Word64(0,0),k=new Word64(0,0),R=new Word64(0,0);const N=new Word64(0,0),G=new Word64(0,0),M=new Word64(0,0),U=new Word64(0,0);let x,L;for(u=0;u=1;--e){i=s[13];s[13]=s[9];s[9]=s[5];s[5]=s[1];s[1]=i;i=s[14];a=s[10];s[14]=s[6];s[10]=s[2];s[6]=i;s[2]=a;i=s[15];a=s[11];r=s[7];s[15]=s[3];s[11]=i;s[7]=a;s[3]=r;for(let e=0;e<16;++e)s[e]=this._inv_s[s[e]];for(let i=0,a=16*e;i<16;++i,++a)s[i]^=t[a];for(let e=0;e<16;e+=4){const t=this._mix[s[e]],a=this._mix[s[e+1]],r=this._mix[s[e+2]],n=this._mix[s[e+3]];i=t^a>>>8^a<<24^r>>>16^r<<16^n>>>24^n<<8;s[e]=i>>>24&255;s[e+1]=i>>16&255;s[e+2]=i>>8&255;s[e+3]=255&i}}i=s[13];s[13]=s[9];s[9]=s[5];s[5]=s[1];s[1]=i;i=s[14];a=s[10];s[14]=s[6];s[10]=s[2];s[6]=i;s[2]=a;i=s[15];a=s[11];r=s[7];s[15]=s[3];s[11]=i;s[7]=a;s[3]=r;for(let e=0;e<16;++e){s[e]=this._inv_s[s[e]];s[e]^=t[e]}return s}_encrypt(e,t){const i=this._s;let a,r,s;const n=new Uint8Array(16);n.set(e);for(let e=0;e<16;++e)n[e]^=t[e];for(let e=1;e=a;--i)if(e[i]!==t){t=0;break}o-=t;s[s.length-1]=e.subarray(0,16-t)}}const g=new Uint8Array(o);for(let e=0,t=0,i=s.length;e=256&&(o=255&(27^o))}for(let t=0;t<4;++t){i[e]=a^=i[e-32];e++;i[e]=r^=i[e-32];e++;i[e]=s^=i[e-32];e++;i[e]=n^=i[e-32];e++}}return i}}class PDF17{checkOwnerPassword(e,t,i,a){const r=new Uint8Array(e.length+56);r.set(e,0);r.set(t,e.length);r.set(i,e.length+t.length);return isArrayEqual(to(r,0,r.length),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(to(a,0,a.length),i)}getOwnerKey(e,t,i,a){const r=new Uint8Array(e.length+56);r.set(e,0);r.set(t,e.length);r.set(i,e.length+t.length);const s=to(r,0,r.length);return new AES256Cipher(s).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const r=to(a,0,a.length);return new AES256Cipher(r).decryptBlock(i,!1,new Uint8Array(16))}}class PDF20{_hash(e,t,i){let a=to(t,0,t.length).subarray(0,32),r=[0],s=0;for(;s<64||r.at(-1)>s-32;){const t=e.length+a.length+i.length,c=new Uint8Array(t);let l=0;c.set(e,l);l+=e.length;c.set(a,l);l+=a.length;c.set(i,l);const h=new Uint8Array(64*t);for(let e=0,i=0;e<64;e++,i+=t)h.set(c,i);r=new AES128Cipher(a.subarray(0,16)).encrypt(h,a.subarray(16,32));const C=r.slice(0,16).reduce(((e,t)=>e+t),0)%3;0===C?a=to(r,0,r.length):1===C?a=(n=r,o=0,g=r.length,io(n,o,g,!0)):2===C&&(a=io(r,0,r.length));s++}var n,o,g;return a.subarray(0,32)}checkOwnerPassword(e,t,i,a){const r=new Uint8Array(e.length+56);r.set(e,0);r.set(t,e.length);r.set(i,e.length+t.length);return isArrayEqual(this._hash(e,r,i),a)}checkUserPassword(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);return isArrayEqual(this._hash(e,a,[]),i)}getOwnerKey(e,t,i,a){const r=new Uint8Array(e.length+56);r.set(e,0);r.set(t,e.length);r.set(i,e.length+t.length);const s=this._hash(e,r,i);return new AES256Cipher(s).decryptBlock(a,!1,new Uint8Array(16))}getUserKey(e,t,i){const a=new Uint8Array(e.length+8);a.set(e,0);a.set(t,e.length);const r=this._hash(e,a,[]);return new AES256Cipher(r).decryptBlock(i,!1,new Uint8Array(16))}}class CipherTransform{constructor(e,t){this.StringCipherConstructor=e;this.StreamCipherConstructor=t}createStream(e,t){const i=new this.StreamCipherConstructor;return new DecryptStream(e,t,(function cipherTransformDecryptStream(e,t){return i.decryptBlock(e,t)}))}decryptString(e){const t=new this.StringCipherConstructor;let i=stringToBytes(e);i=t.decryptBlock(i,!0);return bytesToString(i)}encryptString(e){const t=new this.StringCipherConstructor;if(t instanceof AESBaseCipher){const i=16-e.length%16;e+=String.fromCharCode(i).repeat(i);const a=new Uint8Array(16);if("undefined"!=typeof crypto)crypto.getRandomValues(a);else for(let e=0;e<16;e++)a[e]=Math.floor(256*Math.random());let r=stringToBytes(e);r=t.encrypt(r,a);const s=new Uint8Array(16+r.length);s.set(a);s.set(r,16);return bytesToString(s)}let i=stringToBytes(e);i=t.encrypt(i);return bytesToString(i)}}class CipherTransformFactory{static#q=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);#O(e,t,i,a,r,s,n,o,g,c,l,h){if(t){const e=Math.min(127,t.length);t=t.subarray(0,e)}else t=[];const C=6===e?new PDF20:new PDF17;return C.checkUserPassword(t,o,n)?C.getUserKey(t,g,l):t.length&&C.checkOwnerPassword(t,a,s,i)?C.getOwnerKey(t,r,s,c):null}#P(e,t,i,a,r,s,n,o){const g=40+i.length+e.length,c=new Uint8Array(g);let l,h,C=0;if(t){h=Math.min(32,t.length);for(;C>8&255;c[C++]=r>>16&255;c[C++]=r>>>24&255;for(l=0,h=e.length;l=4&&!o){c[C++]=255;c[C++]=255;c[C++]=255;c[C++]=255}let Q=eo(c,0,C);const E=n>>3;if(s>=3)for(l=0;l<50;++l)Q=eo(Q,0,E);const u=Q.subarray(0,E);let d,f;if(s>=3){for(C=0;C<32;++C)c[C]=CipherTransformFactory.#q[C];for(l=0,h=e.length;l>3;if(i>=3)for(o=0;o<50;++o)g=eo(g,0,g.length);let l,h;if(i>=3){h=t;const e=new Uint8Array(c);for(o=19;o>=0;o--){for(let t=0;t>8&255;r[n++]=e>>16&255;r[n++]=255&t;r[n++]=t>>8&255;if(a){r[n++]=115;r[n++]=65;r[n++]=108;r[n++]=84}return eo(r,0,n).subarray(0,Math.min(i.length+5,16))}#X(e,t,i,a,r){if(!(t instanceof Name))throw new FormatError("Invalid crypt filter name.");const s=this,n=e.get(t.name),o=n?.get("CFM");if(!o||"None"===o.name)return function(){return new NullCipher};if("V2"===o.name)return function(){return new ARCFourCipher(s.#j(i,a,r,!1))};if("AESV2"===o.name)return function(){return new AES128Cipher(s.#j(i,a,r,!0))};if("AESV3"===o.name)return function(){return new AES256Cipher(r)};throw new FormatError("Unknown crypto method")}constructor(e,t,i){const a=e.get("Filter");if(!isName(a,"Standard"))throw new FormatError("unknown encryption method");this.filterName=a.name;this.dict=e;const r=e.get("V");if(!Number.isInteger(r)||1!==r&&2!==r&&4!==r&&5!==r)throw new FormatError("unsupported encryption algorithm");this.algorithm=r;let s=e.get("Length");if(!s)if(r<=3)s=40;else{const t=e.get("CF"),i=e.get("StmF");if(t instanceof Dict&&i instanceof Name){t.suppressEncryption=!0;const e=t.get(i.name);s=e?.get("Length")||128;s<40&&(s<<=3)}}if(!Number.isInteger(s)||s<40||s%8!=0)throw new FormatError("invalid key length");const n=stringToBytes(e.get("O")),o=stringToBytes(e.get("U")),g=n.subarray(0,32),c=o.subarray(0,32),l=e.get("P"),h=e.get("R"),C=(4===r||5===r)&&!1!==e.get("EncryptMetadata");this.encryptMetadata=C;const Q=stringToBytes(t);let E,u;if(i){if(6===h)try{i=utf8StringToString(i)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}E=stringToBytes(i)}if(5!==r)u=this.#P(Q,E,g,c,l,h,s,C);else{const t=n.subarray(32,40),i=n.subarray(40,48),a=o.subarray(0,48),r=o.subarray(32,40),s=o.subarray(40,48),l=stringToBytes(e.get("OE")),C=stringToBytes(e.get("UE")),Q=stringToBytes(e.get("Perms"));u=this.#O(h,E,g,t,i,a,c,r,s,l,C,Q)}if(!u&&!i)throw new PasswordException("No password given",ot);if(!u&&i){const e=this.#W(E,g,h,s);u=this.#P(Q,e,g,c,l,h,s,C)}if(!u)throw new PasswordException("Incorrect Password",gt);this.encryptionKey=u;if(r>=4){const t=e.get("CF");t instanceof Dict&&(t.suppressEncryption=!0);this.cf=t;this.stmf=e.get("StmF")||Name.get("Identity");this.strf=e.get("StrF")||Name.get("Identity");this.eff=e.get("EFF")||this.stmf}}createCipherTransform(e,t){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#X(this.cf,this.strf,e,t,this.encryptionKey),this.#X(this.cf,this.stmf,e,t,this.encryptionKey));const i=this.#j(e,t,this.encryptionKey,!1),cipherConstructor=function(){return new ARCFourCipher(i)};return new CipherTransform(cipherConstructor,cipherConstructor)}}function decodeString(e){try{return stringToUTF8String(e)}catch(t){warn(`UTF-8 decoding failed: "${t}".`);return e}}class DatasetXMLParser extends SimpleXMLParser{constructor(e){super(e);this.node=null}onEndElement(e){const t=super.onEndElement(e);if(t&&"xfa:datasets"===e){this.node=t;throw new Error("Aborting DatasetXMLParser.")}}}class DatasetReader{constructor(e){if(e.datasets)this.node=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e.datasets).documentElement;else{const t=new DatasetXMLParser({hasAttributes:!0});try{t.parseFromString(e["xdp:xdp"])}catch{}this.node=t.node}}getValue(e){if(!this.node||!e)return"";const t=this.node.searchNode(parseXFAPath(e),0);if(!t)return"";const i=t.firstChild;return"value"===i?.nodeName?t.children.map((e=>decodeString(e.textContent))):decodeString(t.textContent)}}class XRef{#V=null;constructor(e,t){this.stream=e;this.pdfManager=t;this.entries=[];this._xrefStms=new Set;this._cacheMap=new Map;this._pendingRefs=new RefSet;this._newPersistentRefNum=null;this._newTemporaryRefNum=null;this._persistentRefsCache=null}getNewPersistentRef(e){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const t=this._newPersistentRefNum++;this._cacheMap.set(t,e);return Ref.get(t,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum){this._newTemporaryRefNum=this.entries.length||1;if(this._newPersistentRefNum){this._persistentRefsCache=new Map;for(let e=this._newTemporaryRefNum;e0;){const[n,o]=s;if(!Number.isInteger(n)||!Number.isInteger(o))throw new FormatError(`Invalid XRef range fields: ${n}, ${o}`);if(!Number.isInteger(i)||!Number.isInteger(a)||!Number.isInteger(r))throw new FormatError(`Invalid XRef entry fields length: ${n}, ${o}`);for(let s=t.entryNum;s=e.length);){i+=String.fromCharCode(a);a=e[t]}return i}function skipUntil(e,t,i){const a=i.length,r=e.length;let s=0;for(;t=a)break;t++;s++}return s}const e=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,t=/\b(startxref|\d+\s+\d+\s+obj)\b/g,i=/^(\d+)\s+(\d+)\s+obj\b/,a=new Uint8Array([116,114,97,105,108,101,114]),r=new Uint8Array([115,116,97,114,116,120,114,101,102]),s=new Uint8Array([47,88,82,101,102]);this.entries.length=0;this._cacheMap.clear();const n=this.stream;n.pos=0;const o=n.getBytes(),g=bytesToString(o),c=o.length;let l=n.start;const h=[],C=[];for(;l=c)break;Q=o[l]}while(10!==Q&&13!==Q);continue}const E=readToken(o,l);let u;if(E.startsWith("xref")&&(4===E.length||/\s/.test(E[4]))){l+=skipUntil(o,l,a);h.push(l);l+=skipUntil(o,l,r)}else if(u=i.exec(E)){const t=0|u[1],i=0|u[2],a=l+E.length;let r,h=!1;if(this.entries[t]){if(this.entries[t].gen===i)try{new Parser({lexer:new Lexer(n.makeSubStream(a))}).getObj();h=!0}catch(e){e instanceof ParserEOFException?warn(`indexObjects -- checking object (${E}): "${e}".`):h=!0}}else h=!0;h&&(this.entries[t]={offset:l-n.start,gen:i,uncompressed:!0});e.lastIndex=a;const Q=e.exec(g);if(Q){r=e.lastIndex+1-l;if("endobj"!==Q[1]){warn(`indexObjects: Found "${Q[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`);r-=Q[1].length+1}}else r=c-l;const d=o.subarray(l,l+r),f=skipUntil(d,0,s);if(f0?Math.max(...this._xrefStms):null)}getEntry(e){const t=this.entries[e];return t&&!t.free&&t.offset?t:null}fetchIfRef(e,t=!1){return e instanceof Ref?this.fetch(e,t):e}fetch(e,t=!1){if(!(e instanceof Ref))throw new Error("ref object is not a reference");const i=e.num,a=this._cacheMap.get(i);if(void 0!==a){a instanceof Dict&&!a.objId&&(a.objId=e.toString());return a}let r=this.getEntry(i);if(null===r){this._cacheMap.set(i,r);return r}if(this._pendingRefs.has(e)){this._pendingRefs.remove(e);warn(`Ignoring circular reference: ${e}.`);return Qt}this._pendingRefs.put(e);try{r=r.uncompressed?this.fetchUncompressed(e,r,t):this.fetchCompressed(e,r,t);this._pendingRefs.remove(e)}catch(t){this._pendingRefs.remove(e);throw t}r instanceof Dict?r.objId=e.toString():r instanceof BaseStream&&(r.dict.objId=e.toString());return r}fetchUncompressed(e,t,i=!1){const a=e.gen;let r=e.num;if(t.gen!==a){const s=`Inconsistent generation in XRef: ${e}`;if(this._generationFallback&&t.gen0&&t[3]-t[1]>0)return t;warn(`Empty, or invalid, /${e} entry.`)}return null}get mediaBox(){return shadow(this,"mediaBox",this._getBoundingBox("MediaBox")||ao)}get cropBox(){return shadow(this,"cropBox",this._getBoundingBox("CropBox")||this.mediaBox)}get userUnit(){const e=this.pageDict.get("UserUnit");return shadow(this,"userUnit","number"==typeof e&&e>0?e:1)}get view(){const{cropBox:e,mediaBox:t}=this;if(e!==t&&!isArrayEqual(e,t)){const i=Util.intersect(e,t);if(i&&i[2]-i[0]>0&&i[3]-i[1]>0)return shadow(this,"view",i);warn("Empty /CropBox and /MediaBox intersection.")}return shadow(this,"view",t)}get rotate(){let e=this._getInheritableProperty("Rotate")||0;e%90!=0?e=0:e>=360?e%=360:e<0&&(e=(e%360+360)%360);return shadow(this,"rotate",e)}_onSubStreamError(e,t){if(!this.evaluatorOptions.ignoreErrors)throw e;warn(`getContentStream - ignoring sub-stream (${t}): "${e}".`)}getContentStream(){return this.pdfManager.ensure(this,"content").then((e=>e instanceof BaseStream?e:Array.isArray(e)?new StreamsSequenceStream(e,this._onSubStreamError.bind(this)):new NullStream))}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}async#Z(e,t,i){const a=[];for(const r of e)if(r.id){const e=Ref.fromString(r.id);if(!e){warn(`A non-linked annotation cannot be modified: ${r.id}`);continue}if(r.deleted){t.put(e,e);if(r.popupRef){const e=Ref.fromString(r.popupRef);e&&t.put(e,e)}continue}i?.put(e);r.ref=e;a.push(this.xref.fetchAsync(e).then((e=>{e instanceof Dict&&(r.oldAnnotation=e.clone())}),(()=>{warn(`Cannot fetch \`oldAnnotation\` for: ${e}.`)})));delete r.id}await Promise.all(a)}async saveNewAnnotations(e,t,i,a,r){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const s=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),n=new RefSetCache,o=new RefSet;await this.#Z(i,n,o);const g=this.pageDict,c=this.annotations.filter((e=>!(e instanceof Ref&&n.has(e)))),l=await AnnotationFactory.saveNewAnnotations(s,t,i,a,r);for(const{ref:e}of l.annotations)e instanceof Ref&&!o.has(e)&&c.push(e);const h=g.clone();h.set("Annots",c);r.put(this.ref,{data:h});for(const e of n)r.put(e,{data:null})}save(e,t,i,a){const r=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});return this._parsedAnnotations.then((function(e){const s=[];for(const n of e)s.push(n.save(r,t,i,a).catch((function(e){warn(`save - ignoring annotation data during "${t.name}" task: "${e}".`);return null})));return Promise.all(s)}))}loadResources(e){this.resourcesPromise||=this.pdfManager.ensure(this,"resources");return this.resourcesPromise.then((()=>new ObjectLoader(this.resources,e,this.xref).load()))}getOperatorList({handler:e,sink:t,task:i,intent:a,cacheKey:r,annotationStorage:s=null,modifiedIds:n=null}){const o=this.getContentStream(),h=this.loadResources(["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"]),u=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),f=this.xfaFactory?null:getNewAnnotationsMap(s),p=f?.get(this.pageIndex);let m=Promise.resolve(null),y=null;if(p){const e=this.pdfManager.ensureDoc("annotationGlobals");let t;const a=new Set;for(const{bitmapId:e,bitmap:t}of p)!e||t||a.has(e)||a.add(e);const{isOffscreenCanvasSupported:r}=this.evaluatorOptions;if(a.size>0){const e=p.slice();for(const[t,i]of s)t.startsWith(d)&&i.bitmap&&a.has(i.bitmapId)&&e.push(i);t=AnnotationFactory.generateImages(e,this.xref,r)}else t=AnnotationFactory.generateImages(p,this.xref,r);y=new RefSet;m=Promise.all([e,this.#Z(p,y,null)]).then((([e])=>e?AnnotationFactory.printNewAnnotations(e,u,i,p,t):null))}const w=Promise.all([o,h]).then((([s])=>{const n=new OperatorList(a,t);e.send("StartRenderPage",{transparency:u.hasBlendModes(this.resources,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:r});return u.getOperatorList({stream:s,task:i,resources:this.resources,operatorList:n}).then((function(){return n}))}));return Promise.all([w,this._parsedAnnotations,m]).then((function([e,t,r]){if(r){t=t.filter((e=>!(e.ref&&y.has(e.ref))));for(let e=0,i=r.length;ee.ref&&isRefsEqual(e.ref,a.refToReplace)));if(s>=0){t.splice(s,1,a);r.splice(e--,1);i--}}}t=t.concat(r)}if(0===t.length||a&Q){e.flush(!0);return{length:e.totalLength}}const o=!!(a&C),h=!!(a&E),d=!!(a&g),f=!!(a&c),p=!!(a&l),m=[];for(const e of t)(d||f&&e.mustBeViewed(s,o)&&e.mustBeViewedWhenEditing(h,n)||p&&e.mustBePrinted(s))&&m.push(e.getOperatorList(u,i,a,s).catch((function(e){warn(`getOperatorList - ignoring annotation data during "${i.name}" task: "${e}".`);return{opList:null,separateForm:!1,separateCanvas:!1}})));return Promise.all(m).then((function(t){let i=!1,a=!1;for(const{opList:r,separateForm:s,separateCanvas:n}of t){e.addOpList(r);i||=s;a||=n}e.flush(!0,{form:i,canvas:a});return{length:e.totalLength}}))}))}async extractTextContent({handler:e,task:t,includeMarkedContent:i,disableNormalization:a,sink:r}){const s=this.getContentStream(),n=this.loadResources(["ExtGState","Font","Properties","XObject"]),o=this.pdfManager.ensureCatalog("lang"),[g,,c]=await Promise.all([s,n,o]);return new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}).getTextContent({stream:g,task:t,resources:this.resources,includeMarkedContent:i,disableNormalization:a,sink:r,viewBox:this.view,lang:c})}async getStructTree(){const e=await this.pdfManager.ensureCatalog("structTreeRoot");if(!e)return null;await this._parsedAnnotations;const t=await this.pdfManager.ensure(this,"_parseStructTree",[e]);return this.pdfManager.ensure(t,"serializable")}_parseStructTree(e){const t=new StructTreePage(e,this.pageDict);t.parse(this.ref);return t}async getAnnotationsData(e,t,i){const a=await this._parsedAnnotations;if(0===a.length)return a;const r=[],s=[];let n;const o=!!(i&g),h=!!(i&c),C=!!(i&l);for(const i of a){const a=o||h&&i.viewable;(a||C&&i.printable)&&r.push(i.data);if(i.hasTextContent&&a){n||=new PartialEvaluator({xref:this.xref,handler:e,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});s.push(i.extractTextContent(n,t,[-1/0,-1/0,1/0,1/0]).catch((function(e){warn(`getAnnotationsData - ignoring textContent during "${t.name}" task: "${e}".`)})))}}await Promise.all(s);return r}get annotations(){const e=this._getInheritableProperty("Annots");return shadow(this,"annotations",Array.isArray(e)?e:[])}get _parsedAnnotations(){return shadow(this,"_parsedAnnotations",this.pdfManager.ensure(this,"annotations").then((async e=>{if(0===e.length)return e;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureDoc("fieldObjects")]);if(!t)return[];const a=i?.orphanFields,r=[];for(const i of e)r.push(AnnotationFactory.create(this.xref,i,t,this._localIdFactory,!1,a,this.ref).catch((function(e){warn(`_parsedAnnotations: "${e}".`);return null})));const s=[];let n,o;for(const e of await Promise.all(r))e&&(e instanceof WidgetAnnotation?(o||=[]).push(e):e instanceof PopupAnnotation?(n||=[]).push(e):s.push(e));o&&s.push(...o);n&&s.push(...n);return s})))}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,yA))}}const ro=new Uint8Array([37,80,68,70,45]),so=new Uint8Array([115,116,97,114,116,120,114,101,102]),no=new Uint8Array([101,110,100,111,98,106]);function find(e,t,i=1024,a=!1){const r=t.length,s=e.peekBytes(i),n=s.length-r;if(n<=0)return!1;if(a){const i=r-1;let a=s.length-1;for(;a>=i;){let n=0;for(;n=r){e.pos+=a-i;return!0}a--}}else{let i=0;for(;i<=n;){let a=0;for(;a=r){e.pos+=i;return!0}i++}}return!1}class PDFDocument{constructor(e,t){if(t.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=e;this.stream=t;this.xref=new XRef(t,e);this._pagePromises=new Map;this._version=null;const i={font:0};this._globalIdFactory=class{static getDocId(){return`g_${e.docId}`}static createFontId(){return"f"+ ++i.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(e){this.xref.parse(e);this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let e=null;try{e=Linearization.create(this.stream)}catch(e){if(e instanceof MissingDataException)throw e;info(e)}return shadow(this,"linearization",e)}get startXRef(){const e=this.stream;let t=0;if(this.linearization){e.reset();if(find(e,no)){e.skip(6);let i=e.peekByte();for(;isWhiteSpace(i);){e.pos++;i=e.peekByte()}t=e.pos-e.start}}else{const i=1024,a=so.length;let r=!1,s=e.end;for(;!r&&s>0;){s-=i-a;s<0&&(s=0);e.pos=s;r=find(e,so,i,!0)}if(r){e.skip(9);let i;do{i=e.getByte()}while(isWhiteSpace(i));let a="";for(;i>=32&&i<=57;){a+=String.fromCharCode(i);i=e.getByte()}t=parseInt(a,10);isNaN(t)&&(t=0)}}return shadow(this,"startXRef",t)}checkHeader(){const e=this.stream;e.reset();if(!find(e,ro))return;e.moveStart();e.skip(ro.length);let t,i="";for(;(t=e.getByte())>32&&i.length<7;)i+=String.fromCharCode(t);mt.test(i)?this._version=i:warn(`Invalid PDF header version: ${i}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let e=0;e=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages;return shadow(this,"numPages",e)}_hasOnlyDocumentSignatures(e,t=0){return!!Array.isArray(e)&&e.every((e=>{if(!((e=this.xref.fetchIfRef(e))instanceof Dict))return!1;if(e.has("Kids")){if(++t>10){warn("_hasOnlyDocumentSignatures: maximum recursion depth reached");return!1}return this._hasOnlyDocumentSignatures(e.get("Kids"),t)}const i=isName(e.get("FT"),"Sig"),a=e.get("Rect"),r=Array.isArray(a)&&a.every((e=>0===e));return i&&r}))}get _xfaStreams(){const e=this.catalog.acroForm;if(!e)return null;const t=e.get("XFA"),i={"xdp:xdp":"",template:"",datasets:"",config:"",connectionSet:"",localeSet:"",stylesheet:"","/xdp:xdp":""};if(t instanceof BaseStream&&!t.isEmpty){i["xdp:xdp"]=t;return i}if(!Array.isArray(t)||0===t.length)return null;for(let e=0,a=t.length;e0;e.hasFields=a;const r=t.get("XFA");e.hasXfa=Array.isArray(r)&&r.length>0||r instanceof BaseStream&&!r.isEmpty;const s=!!(1&t.get("SigFlags")),n=s&&this._hasOnlyDocumentSignatures(i);e.hasAcroForm=a&&!n;e.hasSignatures=s}catch(e){if(e instanceof MissingDataException)throw e;warn(`Cannot fetch form information: "${e}".`)}return shadow(this,"formInfo",e)}get documentInfo(){const e={PDFFormatVersion:this.version,Language:this.catalog.lang,EncryptFilterName:this.xref.encrypt?this.xref.encrypt.filterName:null,IsLinearized:!!this.linearization,IsAcroFormPresent:this.formInfo.hasAcroForm,IsXFAPresent:this.formInfo.hasXfa,IsCollectionPresent:!!this.catalog.collection,IsSignaturesPresent:this.formInfo.hasSignatures};let t;try{t=this.xref.trailer.get("Info")}catch(e){if(e instanceof MissingDataException)throw e;info("The document information dictionary is invalid.")}if(!(t instanceof Dict))return shadow(this,"documentInfo",e);for(const i of t.getKeys()){const a=t.get(i);switch(i){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof a){e[i]=stringToPDFString(a);continue}break;case"Trapped":if(a instanceof Name){e[i]=a;continue}break;default:let t;switch(typeof a){case"string":t=stringToPDFString(a);break;case"number":case"boolean":t=a;break;default:a instanceof Name&&(t=a)}if(void 0===t){warn(`Bad value, for custom key "${i}", in Info: ${a}.`);continue}e.Custom||(e.Custom=Object.create(null));e.Custom[i]=t;continue}warn(`Bad value, for key "${i}", in Info: ${a}.`)}return shadow(this,"documentInfo",e)}get fingerprints(){const e="\0".repeat(16);function validate(t){return"string"==typeof t&&16===t.length&&t!==e}const t=this.xref.trailer.get("ID");let i,a;if(Array.isArray(t)&&validate(t[0])){i=stringToBytes(t[0]);t[1]!==t[0]&&validate(t[1])&&(a=stringToBytes(t[1]))}else i=eo(this.stream.getByteRange(0,1024),0,1024);return shadow(this,"fingerprints",[toHexUtil(i),a?toHexUtil(a):null])}async _getLinearizationPage(e){const{catalog:t,linearization:i,xref:a}=this,r=Ref.get(i.objectNumberFirst,0);try{const e=await a.fetchAsync(r);if(e instanceof Dict){let i=e.getRaw("Type");i instanceof Ref&&(i=await a.fetchAsync(i));if(isName(i,"Page")||!e.has("Type")&&!e.has("Kids")&&e.has("Contents")){t.pageKidsCountCache.has(r)||t.pageKidsCountCache.put(r,1);t.pageIndexCache.has(r)||t.pageIndexCache.put(r,0);return[e,r]}}throw new FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(i){warn(`_getLinearizationPage: "${i.message}".`);return t.getPageDict(e)}}getPage(e){const t=this._pagePromises.get(e);if(t)return t;const{catalog:i,linearization:a,xfaFactory:r}=this;let s;s=r?Promise.resolve([Dict.empty,null]):a?.pageFirst===e?this._getLinearizationPage(e):i.getPageDict(e);s=s.then((([t,a])=>new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:e,pageDict:t,ref:a,globalIdFactory:this._globalIdFactory,fontCache:i.fontCache,builtInCMapCache:i.builtInCMapCache,standardFontDataCache:i.standardFontDataCache,globalImageCache:i.globalImageCache,systemFontCache:i.systemFontCache,nonBlendModesSet:i.nonBlendModesSet,xfaFactory:r})));this._pagePromises.set(e,s);return s}async checkFirstPage(e=!1){if(!e)try{await this.getPage(0)}catch(e){if(e instanceof XRefEntryException){this._pagePromises.delete(0);await this.cleanup();throw new XRefParseException}}}async checkLastPage(e=!1){const{catalog:t,pdfManager:i}=this;t.setActualNumPages();let a;try{await Promise.all([i.ensureDoc("xfaFactory"),i.ensureDoc("linearization"),i.ensureCatalog("numPages")]);if(this.xfaFactory)return;a=this.linearization?this.linearization.numPages:t.numPages;if(!Number.isInteger(a))throw new FormatError("Page count is not an integer.");if(a<=1)return;await this.getPage(a-1)}catch(r){this._pagePromises.delete(a-1);await this.cleanup();if(r instanceof XRefEntryException&&!e)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${a}.`);let s;try{s=await t.getAllPageDicts(e)}catch(i){if(i instanceof XRefEntryException&&!e)throw new XRefParseException;t.setActualNumPages(1);return}for(const[e,[a,r]]of s){let s;if(a instanceof Error){s=Promise.reject(a);s.catch((()=>{}))}else s=Promise.resolve(new Page({pdfManager:i,xref:this.xref,pageIndex:e,pageDict:a,ref:r,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:null}));this._pagePromises.set(e,s)}t.setActualNumPages(s.size)}}fontFallback(e,t){return this.catalog.fontFallback(e,t)}async cleanup(e=!1){return this.catalog?this.catalog.cleanup(e):clearGlobalCaches()}async#_(e,t,i,a,r,s,n){const{xref:o}=this;if(!(i instanceof Ref)||s.has(i))return;s.put(i);const g=await o.fetchAsync(i);if(!(g instanceof Dict))return;if(g.has("T")){const t=stringToPDFString(await g.getAsync("T"));e=""===e?t:`${e}.${t}`}else{let i=g;for(;;){i=i.getRaw("Parent")||t;if(i instanceof Ref){if(s.has(i))break;i=await o.fetchAsync(i)}if(!(i instanceof Dict))break;if(i.has("T")){const t=stringToPDFString(await i.getAsync("T"));e=""===e?t:`${e}.${t}`;break}}}t&&!g.has("Parent")&&isName(g.get("Subtype"),"Widget")&&n.put(i,t);a.has(e)||a.set(e,[]);a.get(e).push(AnnotationFactory.create(o,i,r,null,!0,n,null).then((e=>e?.getFieldObject())).catch((function(e){warn(`#collectFieldObjects: "${e}".`);return null})));if(!g.has("Kids"))return;const c=await g.getAsync("Kids");if(Array.isArray(c))for(const t of c)await this.#_(e,i,t,a,r,s,n)}get fieldObjects(){return shadow(this,"fieldObjects",this.pdfManager.ensureDoc("formInfo").then((async e=>{if(!e.hasFields)return null;const[t,i]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureCatalog("acroForm")]);if(!t)return null;const a=new RefSet,r=Object.create(null),s=new Map,n=new RefSetCache;for(const e of await i.getAsync("Fields"))await this.#_("",null,e,s,t,a,n);const o=[];for(const[e,t]of s)o.push(Promise.all(t).then((t=>{(t=t.filter((e=>!!e))).length>0&&(r[e]=t)})));await Promise.all(o);return{allFields:r,orphanFields:n}})))}get hasJSActions(){return shadow(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[e,t]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!e||!!t&&Object.values(t.allFields).some((e=>e.some((e=>null!==e.actions))))}get calculationOrderIds(){const e=this.catalog.acroForm?.get("CO");if(!Array.isArray(e)||0===e.length)return shadow(this,"calculationOrderIds",null);const t=[];for(const i of e)i instanceof Ref&&t.push(i.toString());return shadow(this,"calculationOrderIds",t.length?t:null)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}class BasePdfManager{constructor(e){this._docBaseUrl=function parseDocBaseUrl(e){if(e){const t=createValidAbsoluteUrl(e);if(t)return t.href;warn(`Invalid absolute docBaseUrl: "${e}".`)}return null}(e.docBaseUrl);this._docId=e.docId;this._password=e.password;this.enableXfa=e.enableXfa;e.evaluatorOptions.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported;e.evaluatorOptions.isImageDecoderSupported&&=FeatureTest.isImageDecoderSupported;this.evaluatorOptions=Object.freeze(e.evaluatorOptions)}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}get catalog(){return this.pdfDocument.catalog}ensureDoc(e,t){return this.ensure(this.pdfDocument,e,t)}ensureXRef(e,t){return this.ensure(this.pdfDocument.xref,e,t)}ensureCatalog(e,t){return this.ensure(this.pdfDocument.catalog,e,t)}getPage(e){return this.pdfDocument.getPage(e)}fontFallback(e,t){return this.pdfDocument.fontFallback(e,t)}loadXfaFonts(e,t){return this.pdfDocument.loadXfaFonts(e,t)}loadXfaImages(){return this.pdfDocument.loadXfaImages()}serializeXfaData(e){return this.pdfDocument.serializeXfaData(e)}cleanup(e=!1){return this.pdfDocument.cleanup(e)}async ensure(e,t,i){unreachable("Abstract method `ensure` called")}requestRange(e,t){unreachable("Abstract method `requestRange` called")}requestLoadedStream(e=!1){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(e){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(e){this._password=e}terminate(e){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(e){super(e);const t=new Stream(e.source);this.pdfDocument=new PDFDocument(this,t);this._loadedStreamPromise=Promise.resolve(t)}async ensure(e,t,i){const a=e[t];return"function"==typeof a?a.apply(e,i):a}requestRange(e,t){return Promise.resolve()}requestLoadedStream(e=!1){return this._loadedStreamPromise}terminate(e){}}class NetworkPdfManager extends BasePdfManager{constructor(e){super(e);this.streamManager=new ChunkedStreamManager(e.source,{msgHandler:e.handler,length:e.length,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize});this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(e,t,i){try{const a=e[t];return"function"==typeof a?a.apply(e,i):a}catch(a){if(!(a instanceof MissingDataException))throw a;await this.requestRange(a.begin,a.end);return this.ensure(e,t,i)}}requestRange(e,t){return this.streamManager.requestRange(e,t)}requestLoadedStream(e=!1){return this.streamManager.requestAllChunks(e)}sendProgressiveData(e){this.streamManager.onReceiveData({chunk:e})}terminate(e){this.streamManager.abort(e)}}const oo=1,go=2,Io=1,co=2,lo=3,ho=4,Co=5,Bo=6,Qo=7,Eo=8;function onFn(){}function wrapReason(e){if(e instanceof AbortException||e instanceof InvalidPDFException||e instanceof MissingPDFException||e instanceof PasswordException||e instanceof UnexpectedResponseException||e instanceof UnknownErrorException)return e;e instanceof Error||"object"==typeof e&&null!==e||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new AbortException(e.message);case"InvalidPDFException":return new InvalidPDFException(e.message);case"MissingPDFException":return new MissingPDFException(e.message);case"PasswordException":return new PasswordException(e.message,e.code);case"UnexpectedResponseException":return new UnexpectedResponseException(e.message,e.status);case"UnknownErrorException":return new UnknownErrorException(e.message,e.details)}return new UnknownErrorException(e.message,e.toString())}class MessageHandler{#z=new AbortController;constructor(e,t,i){this.sourceName=e;this.targetName=t;this.comObj=i;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);i.addEventListener("message",this.#$.bind(this),{signal:this.#z.signal})}#$({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#AA(e);return}if(e.callback){const t=e.callbackId,i=this.callbackCapabilities[t];if(!i)throw new Error(`Cannot resolve callback ${t}`);delete this.callbackCapabilities[t];if(e.callback===oo)i.resolve(e.data);else{if(e.callback!==go)throw new Error("Unexpected callback case");i.reject(wrapReason(e.reason))}return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const i=this.sourceName,a=e.sourceName,r=this.comObj;Promise.try(t,e.data).then((function(t){r.postMessage({sourceName:i,targetName:a,callback:oo,callbackId:e.callbackId,data:t})}),(function(t){r.postMessage({sourceName:i,targetName:a,callback:go,callbackId:e.callbackId,reason:wrapReason(t)})}))}else e.streamId?this.#eA(e):t(e.data)}on(e,t){const i=this.actionHandler;if(i[e])throw new Error(`There is already an actionName called "${e}"`);i[e]=t}send(e,t,i){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},i)}sendWithPromise(e,t,i){const a=this.callbackId++,r=Promise.withResolvers();this.callbackCapabilities[a]=r;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:a,data:t},i)}catch(e){r.reject(e)}return r.promise}sendWithStream(e,t,i,a){const r=this.streamId++,s=this.sourceName,n=this.targetName,o=this.comObj;return new ReadableStream({start:i=>{const g=Promise.withResolvers();this.streamControllers[r]={controller:i,startCall:g,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:s,targetName:n,action:e,streamId:r,data:t,desiredSize:i.desiredSize},a);return g.promise},pull:e=>{const t=Promise.withResolvers();this.streamControllers[r].pullCall=t;o.postMessage({sourceName:s,targetName:n,stream:Bo,streamId:r,desiredSize:e.desiredSize});return t.promise},cancel:e=>{assert(e instanceof Error,"cancel must have a valid reason");const t=Promise.withResolvers();this.streamControllers[r].cancelCall=t;this.streamControllers[r].isClosed=!0;o.postMessage({sourceName:s,targetName:n,stream:Io,streamId:r,reason:wrapReason(e)});return t.promise}},i)}#eA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,r=this.comObj,s=this,n=this.actionHandler[e.action],o={enqueue(e,s=1,n){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=s;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}r.postMessage({sourceName:i,targetName:a,stream:ho,streamId:t,chunk:e},n)},close(){if(!this.isCancelled){this.isCancelled=!0;r.postMessage({sourceName:i,targetName:a,stream:lo,streamId:t});delete s.streamSinks[t]}},error(e){assert(e instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;r.postMessage({sourceName:i,targetName:a,stream:Co,streamId:t,reason:wrapReason(e)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[t]=o;Promise.try(n,e.data,o).then((function(){r.postMessage({sourceName:i,targetName:a,stream:Eo,streamId:t,success:!0})}),(function(e){r.postMessage({sourceName:i,targetName:a,stream:Eo,streamId:t,reason:wrapReason(e)})}))}#AA(e){const t=e.streamId,i=this.sourceName,a=e.sourceName,r=this.comObj,s=this.streamControllers[t],n=this.streamSinks[t];switch(e.stream){case Eo:e.success?s.startCall.resolve():s.startCall.reject(wrapReason(e.reason));break;case Qo:e.success?s.pullCall.resolve():s.pullCall.reject(wrapReason(e.reason));break;case Bo:if(!n){r.postMessage({sourceName:i,targetName:a,stream:Qo,streamId:t,success:!0});break}n.desiredSize<=0&&e.desiredSize>0&&n.sinkCapability.resolve();n.desiredSize=e.desiredSize;Promise.try(n.onPull||onFn).then((function(){r.postMessage({sourceName:i,targetName:a,stream:Qo,streamId:t,success:!0})}),(function(e){r.postMessage({sourceName:i,targetName:a,stream:Qo,streamId:t,reason:wrapReason(e)})}));break;case ho:assert(s,"enqueue should have stream controller");if(s.isClosed)break;s.controller.enqueue(e.chunk);break;case lo:assert(s,"close should have stream controller");if(s.isClosed)break;s.isClosed=!0;s.controller.close();this.#tA(s,t);break;case Co:assert(s,"error should have stream controller");s.controller.error(wrapReason(e.reason));this.#tA(s,t);break;case co:e.success?s.cancelCall.resolve():s.cancelCall.reject(wrapReason(e.reason));this.#tA(s,t);break;case Io:if(!n)break;const o=wrapReason(e.reason);Promise.try(n.onCancel||onFn,o).then((function(){r.postMessage({sourceName:i,targetName:a,stream:co,streamId:t,success:!0})}),(function(e){r.postMessage({sourceName:i,targetName:a,stream:co,streamId:t,reason:wrapReason(e)})}));n.sinkCapability.reject(o);n.isCancelled=!0;delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}}async#tA(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]);delete this.streamControllers[t]}destroy(){this.#z?.abort();this.#z=null}}async function writeObject(e,t,i,{encrypt:a=null}){const r=a?.createCipherTransform(e.num,e.gen);i.push(`${e.num} ${e.gen} obj\n`);t instanceof Dict?await writeDict(t,i,r):t instanceof BaseStream?await writeStream(t,i,r):(Array.isArray(t)||ArrayBuffer.isView(t))&&await writeArray(t,i,r);i.push("\nendobj\n")}async function writeDict(e,t,i){t.push("<<");for(const a of e.getKeys()){t.push(` /${escapePDFName(a)} `);await writeValue(e.getRaw(a),t,i)}t.push(">>")}async function writeStream(e,t,i){let a=e.getBytes();const{dict:r}=e,[s,n]=await Promise.all([r.getAsync("Filter"),r.getAsync("DecodeParms")]),o=isName(Array.isArray(s)?await r.xref.fetchIfRefAsync(s[0]):s,"FlateDecode");if(a.length>=256||o)try{const e=new CompressionStream("deflate"),t=e.writable.getWriter();await t.ready;t.write(a).then((async()=>{await t.ready;await t.close()})).catch((()=>{}));const i=await new Response(e.readable).arrayBuffer();a=new Uint8Array(i);let g,c;if(s){if(!o){g=Array.isArray(s)?[Name.get("FlateDecode"),...s]:[Name.get("FlateDecode"),s];n&&(c=Array.isArray(n)?[null,...n]:[null,n])}}else g=Name.get("FlateDecode");g&&r.set("Filter",g);c&&r.set("DecodeParms",c)}catch(e){info(`writeStream - cannot compress data: "${e}".`)}let g=bytesToString(a);i&&(g=i.encryptString(g));r.set("Length",g.length);await writeDict(r,t,i);t.push(" stream\n",g,"\nendstream")}async function writeArray(e,t,i){t.push("[");let a=!0;for(const r of e){a?a=!1:t.push(" ");await writeValue(r,t,i)}t.push("]")}async function writeValue(e,t,i){if(e instanceof Name)t.push(`/${escapePDFName(e.name)}`);else if(e instanceof Ref)t.push(`${e.num} ${e.gen} R`);else if(Array.isArray(e)||ArrayBuffer.isView(e))await writeArray(e,t,i);else if("string"==typeof e){i&&(e=i.encryptString(e));t.push(`(${escapeString(e)})`)}else"number"==typeof e?t.push(numberToString(e)):"boolean"==typeof e?t.push(e.toString()):e instanceof Dict?await writeDict(e,t,i):e instanceof BaseStream?await writeStream(e,t,i):null===e?t.push("null"):warn(`Unhandled value in writer: ${typeof e}, please file a bug.`)}function writeInt(e,t,i,a){for(let r=t+i-1;r>i-1;r--){a[r]=255&e;e>>=8}return i+t}function writeString(e,t,i){for(let a=0,r=e.length;a1&&(s=i.documentElement.searchNode([r.at(-1)],0));s?s.childNodes=Array.isArray(a)?a.map((e=>new SimpleDOMNode("value",e))):[new SimpleDOMNode("#text",a)]:warn(`Node not found for path: ${t}`)}const a=[];i.documentElement.dump(a);return a.join("")}(a.fetchIfRef(t).getString(),i)}const r=new StringStream(e);r.dict=new Dict(a);r.dict.set("Type",Name.get("EmbeddedFile"));i.put(t,{data:r})}function getIndexes(e){const t=[];for(const{ref:i}of e)i.num===t.at(-2)+t.at(-1)?t[t.length-1]+=1:t.push(i.num,1);return t}function computeIDs(e,t,i){if(Array.isArray(t.fileIds)&&t.fileIds.length>0){const a=function computeMD5(e,t){const i=Math.floor(Date.now()/1e3),a=t.filename||"",r=[i.toString(),a,e.toString()];let s=r.reduce(((e,t)=>e+t.length),0);for(const e of Object.values(t.info)){r.push(e);s+=e.length}const n=new Uint8Array(s);let o=0;for(const e of r){writeString(e,o,n);o+=e.length}return bytesToString(eo(n))}(e,t);i.set("ID",[t.fileIds[0],a])}}async function incrementalUpdate({originalData:e,xrefInfo:t,changes:i,xref:a=null,hasXfa:r=!1,xfaDatasetsRef:s=null,hasXfaDatasetsEntry:n=!1,needAppearances:o,acroFormRef:g=null,acroForm:c=null,xfaData:l=null,useXrefStream:h=!1}){await async function updateAcroform({xref:e,acroForm:t,acroFormRef:i,hasXfa:a,hasXfaDatasetsEntry:r,xfaDatasetsRef:s,needAppearances:n,changes:o}){!a||r||s||warn("XFA - Cannot save it");if(!n&&(!a||!s||r))return;const g=t.clone();if(a&&!r){const e=t.get("XFA").slice();e.splice(2,0,"datasets");e.splice(3,0,s);g.set("XFA",e)}n&&g.set("NeedAppearances",!0);o.put(i,{data:g})}({xref:a,acroForm:c,acroFormRef:g,hasXfa:r,hasXfaDatasetsEntry:n,xfaDatasetsRef:s,needAppearances:o,changes:i});r&&updateXFA({xfaData:l,xfaDatasetsRef:s,changes:i,xref:a});const C=function getTrailerDict(e,t,i){const a=new Dict(null);a.set("Prev",e.startXRef);const r=e.newRef;if(i){t.put(r,{data:""});a.set("Size",r.num+1);a.set("Type",Name.get("XRef"))}else a.set("Size",r.num);null!==e.rootRef&&a.set("Root",e.rootRef);null!==e.infoRef&&a.set("Info",e.infoRef);null!==e.encryptRef&&a.set("Encrypt",e.encryptRef);return a}(t,i,h),Q=[],E=await async function writeChanges(e,t,i=[]){const a=[];for(const[r,{data:s}]of e.items())if(null!==s&&"string"!=typeof s){await writeObject(r,s,i,t);a.push({ref:r,data:i.join("")});i.length=0}else a.push({ref:r,data:s});return a.sort(((e,t)=>e.ref.num-t.ref.num))}(i,a,Q);let u=e.length;const d=e.at(-1);if(10!==d&&13!==d){Q.push("\n");u+=1}for(const{data:e}of E)null!==e&&Q.push(e);await(h?async function getXRefStreamTable(e,t,i,a,r){const s=[];let n=0,o=0;for(const{ref:e,data:a}of i){let i;n=Math.max(n,t);if(null!==a){i=Math.min(e.gen,65535);s.push([1,t,i]);t+=a.length}else{i=Math.min(e.gen+1,65535);s.push([0,0,i])}o=Math.max(o,i)}a.set("Index",getIndexes(i));const g=[1,getSizeInBytes(n),getSizeInBytes(o)];a.set("W",g);computeIDs(t,e,a);const c=g.reduce(((e,t)=>e+t),0),l=new Uint8Array(c*s.length),h=new Stream(l);h.dict=a;let C=0;for(const[e,t,i]of s){C=writeInt(e,g[0],C,l);C=writeInt(t,g[1],C,l);C=writeInt(i,g[2],C,l)}await writeObject(e.newRef,h,r,{});r.push("startxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,C,Q):async function getXRefTable(e,t,i,a,r){r.push("xref\n");const s=getIndexes(i);let n=0;for(const{ref:e,data:a}of i){if(e.num===s[n]){r.push(`${s[n]} ${s[n+1]}\n`);n+=2}if(null!==a){r.push(`${t.toString().padStart(10,"0")} ${Math.min(e.gen,65535).toString().padStart(5,"0")} n\r\n`);t+=a.length}else r.push(`0000000000 ${Math.min(e.gen+1,65535).toString().padStart(5,"0")} f\r\n`)}computeIDs(t,e,a);r.push("trailer\n");await writeDict(a,r);r.push("\nstartxref\n",t.toString(),"\n%%EOF\n")}(t,u,E,C,Q));const f=Q.reduce(((e,t)=>e+t.length),e.length),p=new Uint8Array(f);p.set(e);let m=e.length;for(const e of Q){writeString(e,m,p);m+=e.length}return p}class PDFWorkerStream{constructor(e){this._msgHandler=e;this._contentLength=null;this._fullRequestReader=null;this._rangeRequestReaders=[]}getFullReader(){assert(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once.");this._fullRequestReader=new PDFWorkerStreamReader(this._msgHandler);return this._fullRequestReader}getRangeReader(e,t){const i=new PDFWorkerStreamRangeReader(e,t,this._msgHandler);this._rangeRequestReaders.push(i);return i}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(const t of this._rangeRequestReaders.slice(0))t.cancel(e)}}class PDFWorkerStreamReader{constructor(e){this._msgHandler=e;this.onProgress=null;this._contentLength=null;this._isRangeSupported=!1;this._isStreamingSupported=!1;const t=this._msgHandler.sendWithStream("GetReader");this._reader=t.getReader();this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then((e=>{this._isStreamingSupported=e.isStreamingSupported;this._isRangeSupported=e.isRangeSupported;this._contentLength=e.contentLength}))}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class PDFWorkerStreamRangeReader{constructor(e,t,i){this._msgHandler=i;this.onProgress=null;const a=this._msgHandler.sendWithStream("GetRangeReader",{begin:e,end:t});this._reader=a.getReader()}get isStreamingSupported(){return!1}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class WorkerTask{constructor(e){this.name=e;this.terminated=!1;this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static{"undefined"==typeof window&&!i&&"undefined"!=typeof self&&"function"==typeof self.postMessage&&"onmessage"in self&&this.initializeFromPort(self)}static setup(e,t){let i=!1;e.on("test",(t=>{if(!i){i=!0;e.send("test",t instanceof Uint8Array)}}));e.on("configure",(e=>{!function setVerbosityLevel(e){Number.isInteger(e)&&(It=e)}(e.verbosity)}));e.on("GetDocRequest",(e=>this.createDocumentHandler(e,t)))}static createDocumentHandler(e,t){let i,a=!1,r=null;const s=new Set,n=getVerbosityLevel(),{docId:o,apiVersion:g}=e,c="4.10.38";if(g!==c)throw new Error(`The API version "${g}" does not match the Worker version "${c}".`);const l=[];for(const e in[])l.push(e);if(l.length)throw new Error("The `Array.prototype` contains unexpected enumerable properties: "+l.join(", ")+"; thus breaking e.g. `for...in` iteration of `Array`s.");const h=o+"_worker";let C=new MessageHandler(h,o,t);function ensureNotTerminated(){if(a)throw new Error("Worker was terminated")}function startWorkerTask(e){s.add(e)}function finishWorkerTask(e){e.finish();s.delete(e)}async function loadDocument(e){await i.ensureDoc("checkHeader");await i.ensureDoc("parseStartXRef");await i.ensureDoc("parse",[e]);await i.ensureDoc("checkFirstPage",[e]);await i.ensureDoc("checkLastPage",[e]);const t=await i.ensureDoc("isPureXfa");if(t){const e=new WorkerTask("loadXfaFonts");startWorkerTask(e);await Promise.all([i.loadXfaFonts(C,e).catch((e=>{})).then((()=>finishWorkerTask(e))),i.loadXfaImages()])}const[a,r]=await Promise.all([i.ensureDoc("numPages"),i.ensureDoc("fingerprints")]);return{numPages:a,fingerprints:r,htmlForXfa:t?await i.ensureDoc("htmlForXfa"):null}}function setupDoc(e){function onSuccess(e){ensureNotTerminated();C.send("GetDoc",{pdfInfo:e})}function onFailure(e){ensureNotTerminated();if(e instanceof PasswordException){const t=new WorkerTask(`PasswordException: response ${e.code}`);startWorkerTask(t);C.sendWithPromise("PasswordRequest",e).then((function({password:e}){finishWorkerTask(t);i.updatePassword(e);pdfManagerReady()})).catch((function(){finishWorkerTask(t);C.send("DocException",e)}))}else C.send("DocException",wrapReason(e))}function pdfManagerReady(){ensureNotTerminated();loadDocument(!1).then(onSuccess,(function(e){ensureNotTerminated();e instanceof XRefParseException?i.requestLoadedStream().then((function(){ensureNotTerminated();loadDocument(!0).then(onSuccess,onFailure)})):onFailure(e)}))}ensureNotTerminated();(async function getPdfManager({data:e,password:t,disableAutoFetch:i,rangeChunkSize:a,length:s,docBaseUrl:n,enableXfa:g,evaluatorOptions:c}){const l={source:null,disableAutoFetch:i,docBaseUrl:n,docId:o,enableXfa:g,evaluatorOptions:c,handler:C,length:s,password:t,rangeChunkSize:a};if(e){l.source=e;return new LocalPdfManager(l)}const h=new PDFWorkerStream(C),Q=h.getFullReader(),E=Promise.withResolvers();let u,d=[],f=0;Q.headersReady.then((function(){if(Q.isRangeSupported){l.source=h;l.length=Q.contentLength;l.disableAutoFetch||=Q.isStreamingSupported;u=new NetworkPdfManager(l);for(const e of d)u.sendProgressiveData(e);d=[];E.resolve(u);r=null}})).catch((function(e){E.reject(e);r=null}));new Promise((function(e,t){const readChunk=function({value:e,done:i}){try{ensureNotTerminated();if(i){if(!u){const e=arrayBuffersToBytes(d);d=[];s&&e.length!==s&&warn("reported HTTP length is different from actual");l.source=e;u=new LocalPdfManager(l);E.resolve(u)}r=null;return}f+=e.byteLength;Q.isStreamingSupported||C.send("DocProgress",{loaded:f,total:Math.max(f,Q.contentLength||0)});u?u.sendProgressiveData(e):d.push(e);Q.read().then(readChunk,t)}catch(e){t(e)}};Q.read().then(readChunk,t)})).catch((function(e){E.reject(e);r=null}));r=e=>{h.cancelAllRequests(e)};return E.promise})(e).then((function(e){if(a){e.terminate(new AbortException("Worker was terminated."));throw new Error("Worker was terminated")}i=e;i.requestLoadedStream(!0).then((e=>{C.send("DataLoaded",{length:e.bytes.byteLength})}))})).then(pdfManagerReady,onFailure)}C.on("GetPage",(function(e){return i.getPage(e.pageIndex).then((function(e){return Promise.all([i.ensure(e,"rotate"),i.ensure(e,"ref"),i.ensure(e,"userUnit"),i.ensure(e,"view")]).then((function([e,t,i,a]){return{rotate:e,ref:t,refStr:t?.toString()??null,userUnit:i,view:a}}))}))}));C.on("GetPageIndex",(function(e){const t=Ref.get(e.num,e.gen);return i.ensureCatalog("getPageIndex",[t])}));C.on("GetDestinations",(function(e){return i.ensureCatalog("destinations")}));C.on("GetDestination",(function(e){return i.ensureCatalog("getDestination",[e.id])}));C.on("GetPageLabels",(function(e){return i.ensureCatalog("pageLabels")}));C.on("GetPageLayout",(function(e){return i.ensureCatalog("pageLayout")}));C.on("GetPageMode",(function(e){return i.ensureCatalog("pageMode")}));C.on("GetViewerPreferences",(function(e){return i.ensureCatalog("viewerPreferences")}));C.on("GetOpenAction",(function(e){return i.ensureCatalog("openAction")}));C.on("GetAttachments",(function(e){return i.ensureCatalog("attachments")}));C.on("GetDocJSActions",(function(e){return i.ensureCatalog("jsActions")}));C.on("GetPageJSActions",(function({pageIndex:e}){return i.getPage(e).then((function(e){return i.ensure(e,"jsActions")}))}));C.on("GetOutline",(function(e){return i.ensureCatalog("documentOutline")}));C.on("GetOptionalContentConfig",(function(e){return i.ensureCatalog("optionalContentConfig")}));C.on("GetPermissions",(function(e){return i.ensureCatalog("permissions")}));C.on("GetMetadata",(function(e){return Promise.all([i.ensureDoc("documentInfo"),i.ensureCatalog("metadata")])}));C.on("GetMarkInfo",(function(e){return i.ensureCatalog("markInfo")}));C.on("GetData",(function(e){return i.requestLoadedStream().then((function(e){return e.bytes}))}));C.on("GetAnnotations",(function({pageIndex:e,intent:t}){return i.getPage(e).then((function(i){const a=new WorkerTask(`GetAnnotations: page ${e}`);startWorkerTask(a);return i.getAnnotationsData(C,a,t).then((e=>{finishWorkerTask(a);return e}),(e=>{finishWorkerTask(a);throw e}))}))}));C.on("GetFieldObjects",(function(e){return i.ensureDoc("fieldObjects").then((e=>e?.allFields||null))}));C.on("HasJSActions",(function(e){return i.ensureDoc("hasJSActions")}));C.on("GetCalculationOrderIds",(function(e){return i.ensureDoc("calculationOrderIds")}));C.on("SaveDocument",(async function({isPureXfa:e,numPages:t,annotationStorage:a,filename:r}){const s=[i.requestLoadedStream(),i.ensureCatalog("acroForm"),i.ensureCatalog("acroFormRef"),i.ensureDoc("startXRef"),i.ensureDoc("xref"),i.ensureDoc("linearization"),i.ensureCatalog("structTreeRoot")],n=new RefSetCache,o=[],g=e?null:getNewAnnotationsMap(a),[c,l,h,Q,E,u,d]=await Promise.all(s),f=E.trailer.getRaw("Root")||null;let p;if(g){d?await d.canUpdateStructTree({pdfManager:i,xref:E,newAnnotationsByPage:g})&&(p=d):await StructTreeRoot.canCreateStructureTree({catalogRef:f,pdfManager:i,newAnnotationsByPage:g})&&(p=null);const e=AnnotationFactory.generateImages(a.values(),E,i.evaluatorOptions.isOffscreenCanvasSupported),t=void 0===p?o:[];for(const[a,r]of g)t.push(i.getPage(a).then((t=>{const i=new WorkerTask(`Save (editor): page ${a}`);startWorkerTask(i);return t.saveNewAnnotations(C,i,r,e,n).finally((function(){finishWorkerTask(i)}))})));null===p?o.push(Promise.all(t).then((async()=>{await StructTreeRoot.createStructureTree({newAnnotationsByPage:g,xref:E,catalogRef:f,pdfManager:i,changes:n})}))):p&&o.push(Promise.all(t).then((async()=>{await p.updateStructureTree({newAnnotationsByPage:g,pdfManager:i,changes:n})})))}if(e)o.push(i.serializeXfaData(a));else for(let e=0;ee.needAppearances)),b=l instanceof Dict&&l.get("XFA")||null;let D=null,S=!1;if(Array.isArray(b)){for(let e=0,t=b.length;e{E.resetNewTemporaryRef()}))}));C.on("GetOperatorList",(function(e,t){const a=e.pageIndex;i.getPage(a).then((function(i){const r=new WorkerTask(`GetOperatorList: page ${a}`);startWorkerTask(r);const s=n>=bA?Date.now():0;i.getOperatorList({handler:C,sink:t,task:r,intent:e.intent,cacheKey:e.cacheKey,annotationStorage:e.annotationStorage,modifiedIds:e.modifiedIds}).then((function(e){finishWorkerTask(r);s&&info(`page=${a+1} - getOperatorList: time=${Date.now()-s}ms, len=${e.length}`);t.close()}),(function(e){finishWorkerTask(r);r.terminated||t.error(e)}))}))}));C.on("GetTextContent",(function(e,t){const{pageIndex:a,includeMarkedContent:r,disableNormalization:s}=e;i.getPage(a).then((function(e){const i=new WorkerTask("GetTextContent: page "+a);startWorkerTask(i);const o=n>=bA?Date.now():0;e.extractTextContent({handler:C,task:i,sink:t,includeMarkedContent:r,disableNormalization:s}).then((function(){finishWorkerTask(i);o&&info(`page=${a+1} - getTextContent: time=`+(Date.now()-o)+"ms");t.close()}),(function(e){finishWorkerTask(i);i.terminated||t.error(e)}))}))}));C.on("GetStructTree",(function(e){return i.getPage(e.pageIndex).then((function(e){return i.ensure(e,"getStructTree")}))}));C.on("FontFallback",(function(e){return i.fontFallback(e.id,C)}));C.on("Cleanup",(function(e){return i.cleanup(!0)}));C.on("Terminate",(function(e){a=!0;const t=[];if(i){i.terminate(new AbortException("Worker was terminated."));const e=i.cleanup();t.push(e);i=null}else clearGlobalCaches();r?.(new AbortException("Worker was terminated."));for(const e of s){t.push(e.finished);e.terminate()}return Promise.all(t).then((function(){C.destroy();C=null}))}));C.on("Ready",(function(t){setupDoc(e);e=null}));return h}static initializeFromPort(e){const t=new MessageHandler("worker","main",e);this.setup(t,e);t.send("ready",null)}}var uo=__webpack_exports__.WorkerMessageHandler;export{uo as WorkerMessageHandler}; \ No newline at end of file diff --git a/crates/guara-cli/src/serve.rs b/crates/guara-cli/src/serve.rs index ee3e7e1..773459a 100644 --- a/crates/guara-cli/src/serve.rs +++ b/crates/guara-cli/src/serve.rs @@ -3,12 +3,17 @@ use guara_core::service::Engine; use serde_json::json; use std::io::Read; -use tiny_http::{Header, Method, Response, Server}; +use std::sync::Arc; +use tiny_http::{Header, Method, Request, Response, Server, StatusCode}; const INDEX: &str = include_str!("../../../apps/gui/ui/index.html"); const CSS: &str = include_str!("../../../apps/gui/ui/app.css"); const JS: &str = include_str!("../../../apps/gui/ui/app.js"); +const PREVIEW_JS: &str = include_str!("../../../apps/gui/ui/preview.js"); +const LOGO: &str = include_str!("../../../apps/gui/ui/guara-logo.svg"); const ICON: &str = include_str!("../../../apps/gui/ui/guara.svg"); +const PDF_JS: &str = include_str!("../../../apps/gui/ui/vendor/pdf.min.mjs"); +const PDF_WORKER: &str = include_str!("../../../apps/gui/ui/vendor/pdf.worker.min.mjs"); pub fn run(port: u16, open: bool) -> Result<(), String> { let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?; @@ -19,78 +24,146 @@ pub fn run(port: u16, open: bool) -> Result<(), String> { .unwrap_or(port); let mut tok = [0u8; 16]; getrandom::getrandom(&mut tok).map_err(|e| e.to_string())?; - let token: String = tok.iter().map(|b| format!("{b:02x}")).collect(); + let token: Arc = tok + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + .into(); let url = format!("http://127.0.0.1:{real_port}/?token={token}"); eprintln!("Guará UI em {url}\n(Ctrl+C para encerrar. Para ler discos brutos, rode como administrador/root.)"); if open { open_browser(&url); } - let eng = Engine::new(); - let hosts = [ + let eng = Arc::new(Engine::new()); + let hosts: Arc<[String; 2]> = Arc::new([ format!("127.0.0.1:{real_port}"), format!("localhost:{real_port}"), - ]; - for mut req in server.incoming_requests() { - let host_ok = req - .headers() - .iter() - .any(|h| h.field.equiv("Host") && hosts.iter().any(|x| x == h.value.as_str())); - if !host_ok { - let _ = req.respond(Response::from_string("host inválido").with_status_code(403)); - continue; - } - let path = req.url().split('?').next().unwrap_or("/").to_string(); - let ct = |v: &str| Header::from_bytes("Content-Type", v).unwrap(); - match (req.method().clone(), path.as_str()) { - (Method::Get, "/") | (Method::Get, "/index.html") => { - let _ = req.respond( - Response::from_string(INDEX).with_header(ct("text/html; charset=utf-8")), - ); - } - (Method::Get, "/app.css") => { - let _ = req - .respond(Response::from_string(CSS).with_header(ct("text/css; charset=utf-8"))); - } - (Method::Get, "/app.js") => { - let _ = req.respond( - Response::from_string(JS).with_header(ct("text/javascript; charset=utf-8")), - ); - } - (Method::Get, "/guara.svg") => { - let _ = req.respond(Response::from_string(ICON).with_header(ct("image/svg+xml"))); - } - (Method::Post, p) if p.starts_with("/rpc/") => { - let ok = req - .headers() - .iter() - .any(|h| h.field.equiv("X-Guara-Token") && h.value.as_str() == token); - if !ok { - let _ = - req.respond(Response::from_string("token inválido").with_status_code(401)); - continue; - } - let method = p.trim_start_matches("/rpc/").to_string(); - let mut body = String::new(); - let _ = req.as_reader().take(1 << 20).read_to_string(&mut body); - let params = serde_json::from_str(&body).unwrap_or(json!({})); - let (code, out) = match eng.rpc(&method, params) { - Ok(v) => (200, v), - Err(e) => (400, json!({ "error": e.to_string() })), - }; - let _ = req.respond( - Response::from_string(out.to_string()) - .with_status_code(code) - .with_header(ct("application/json")), - ); - } - _ => { - let _ = req.respond(Response::from_string("não encontrado").with_status_code(404)); - } - } + ]); + for req in server.incoming_requests() { + let (eng, token, hosts) = (eng.clone(), token.clone(), hosts.clone()); + // Uma thread por requisição: vídeo/áudio em streaming não pode travar a interface. + std::thread::spawn(move || handle(req, &eng, &token, &hosts[..])); } Ok(()) } +fn header(name: &str, value: &str) -> Header { + Header::from_bytes(name.as_bytes(), value.as_bytes()).unwrap() +} + +fn handle(mut req: Request, eng: &Engine, token: &str, hosts: &[String]) { + let host_ok = req + .headers() + .iter() + .any(|h| h.field.equiv("Host") && hosts.iter().any(|x| x == h.value.as_str())); + if !host_ok { + let _ = req.respond(Response::from_string("host inválido").with_status_code(403)); + return; + } + let full = req.url().to_string(); + let (path, query) = full.split_once('?').unwrap_or((full.as_str(), "")); + let ct = |v: &str| header("Content-Type", v); + match (req.method().clone(), path) { + (Method::Get, "/") | (Method::Get, "/index.html") => { + let _ = req + .respond(Response::from_string(INDEX).with_header(ct("text/html; charset=utf-8"))); + } + (Method::Get, "/app.css") => { + let _ = + req.respond(Response::from_string(CSS).with_header(ct("text/css; charset=utf-8"))); + } + (Method::Get, "/app.js") => { + let _ = req.respond( + Response::from_string(JS).with_header(ct("text/javascript; charset=utf-8")), + ); + } + (Method::Get, "/preview.js") => { + let _ = req.respond( + Response::from_string(PREVIEW_JS).with_header(ct("text/javascript; charset=utf-8")), + ); + } + (Method::Get, "/guara-logo.svg") => { + let _ = req.respond(Response::from_string(LOGO).with_header(ct("image/svg+xml"))); + } + (Method::Get, "/guara.svg") => { + let _ = req.respond(Response::from_string(ICON).with_header(ct("image/svg+xml"))); + } + (Method::Get, "/vendor/pdf.min.mjs") => { + let _ = req.respond( + Response::from_string(PDF_JS).with_header(ct("text/javascript; charset=utf-8")), + ); + } + (Method::Get, "/vendor/pdf.worker.min.mjs") => { + let _ = req.respond( + Response::from_string(PDF_WORKER).with_header(ct("text/javascript; charset=utf-8")), + ); + } + (Method::Get, p) if p.starts_with("/file/") => { + let tok_ok = query + .split('&') + .any(|kv| kv.strip_prefix("t=") == Some(token)); + if !tok_ok { + let _ = req.respond(Response::from_string("token inválido").with_status_code(401)); + return; + } + let mut it = p.trim_start_matches("/file/").split('/'); + let (job, id) = ( + it.next().unwrap_or(""), + it.next().and_then(|s| s.parse::().ok()), + ); + let range = req + .headers() + .iter() + .find(|h| h.field.equiv("Range")) + .map(|h| h.value.as_str().to_string()); + let Some(id) = id else { + let _ = req.respond(Response::from_string("id inválido").with_status_code(400)); + return; + }; + match eng.file_slice(job, id, range.as_deref()) { + Ok(slice) => { + let (status, len) = (slice.status(), slice.len() as usize); + let headers: Vec
    = + slice.headers().iter().map(|(k, v)| header(k, v)).collect(); + let resp = + Response::new(StatusCode(status), headers, slice.reader(), Some(len), None); + let _ = req.respond(resp); + } + Err(code) => { + let _ = + req.respond(Response::from_string("indisponível").with_status_code(code)); + } + } + } + (Method::Post, p) if p.starts_with("/rpc/") => { + let ok = req + .headers() + .iter() + .any(|h| h.field.equiv("X-Guara-Token") && h.value.as_str() == token); + if !ok { + let _ = req.respond(Response::from_string("token inválido").with_status_code(401)); + return; + } + let method = p.trim_start_matches("/rpc/").to_string(); + let mut body = String::new(); + let _ = req.as_reader().take(1 << 20).read_to_string(&mut body); + let params = serde_json::from_str(&body).unwrap_or(json!({})); + let (code, out) = match eng.rpc(&method, params) { + Ok(v) => (200, v), + Err(e) => (400, json!({ "error": e.to_string() })), + }; + let _ = req.respond( + Response::from_string(out.to_string()) + .with_status_code(code) + .with_header(ct("application/json")), + ); + } + _ => { + let _ = req.respond(Response::from_string("não encontrado").with_status_code(404)); + } + } +} + fn open_browser(url: &str) { #[cfg(target_os = "linux")] let _ = std::process::Command::new("xdg-open").arg(url).spawn(); diff --git a/crates/guara-core/src/lib.rs b/crates/guara-core/src/lib.rs index 010e5f6..3d3d79a 100644 --- a/crates/guara-core/src/lib.rs +++ b/crates/guara-core/src/lib.rs @@ -12,6 +12,7 @@ pub mod partition; pub mod recover; pub mod scan; pub mod service; +pub mod settings; pub mod signatures; pub mod source; pub mod types; diff --git a/crates/guara-core/src/partition.rs b/crates/guara-core/src/partition.rs index 92f6aa4..7c73465 100644 --- a/crates/guara-core/src/partition.rs +++ b/crates/guara-core/src/partition.rs @@ -92,17 +92,16 @@ fn detect_fat(b: &[u8]) -> Option<(FsKind, Option)> { let root_secs = (root_entries * 32).div_ceil(bps); let data = total.saturating_sub(reserved + nfats * fatsz + root_secs); let clusters = data / spc; - let kind = if clusters < 4085 { - FsKind::Fat12 - } else if clusters < 65525 { - FsKind::Fat16 - } else { + // O layout do BPB manda: raiz fixa zerada + FAT de 32 bits = FAT32, mesmo com poucos + // clusters (mkfs.vfat -F 32 em mídias pequenas gera isso e o Linux monta). + let is32 = root_entries == 0 && fat16 == 0 && fat32 != 0; + let kind = if is32 { FsKind::Fat32 + } else if clusters < 4085 { + FsKind::Fat12 + } else { + FsKind::Fat16 }; - // Coerência: FAT32 tem root_entries == 0 e fat16 == 0. - if (kind == FsKind::Fat32) != (root_entries == 0 && fat16 == 0) { - return None; - } Some((kind, Some(total * bps))) } diff --git a/crates/guara-core/src/recover.rs b/crates/guara-core/src/recover.rs index 0c6fa5c..8a14def 100644 --- a/crates/guara-core/src/recover.rs +++ b/crates/guara-core/src/recover.rs @@ -210,3 +210,42 @@ pub fn write_file(src: &dyn Source, f: &Found, path: &Path) -> Result { .map(|b| format!("{b:02x}")) .collect()) } + +/// Lê `buf.len()` bytes do conteúdo lógico de um achado a partir de `offset` +/// (usado para streaming/pré-visualização sem gravar em disco). +pub fn read_found_at( + src: &dyn Source, + f: &Found, + offset: u64, + buf: &mut [u8], +) -> std::io::Result { + if offset >= f.size || buf.is_empty() { + return Ok(0); + } + let want = buf.len().min((f.size - offset) as usize); + match &f.data { + DataLoc::Resident { bytes } => { + let o = offset as usize; + let n = want.min(bytes.len().saturating_sub(o)); + buf[..n].copy_from_slice(&bytes[o..o + n]); + Ok(n) + } + DataLoc::Extents { extents } => { + let mut pos = 0u64; + for e in extents { + let elen = e.len.min(f.size.saturating_sub(pos)); + if offset < pos + elen { + let within = offset - pos; + let n = want.min((elen - within) as usize); + if e.sparse { + buf[..n].fill(0); + return Ok(n); + } + return src.read_at(e.offset + within, &mut buf[..n]); + } + pos += elen; + } + Ok(0) + } + } +} diff --git a/crates/guara-core/src/service.rs b/crates/guara-core/src/service.rs index b924bda..1ca06e4 100644 --- a/crates/guara-core/src/service.rs +++ b/crates/guara-core/src/service.rs @@ -278,37 +278,18 @@ impl Engine { Ok(json!({ "total": total, "items": page })) } - pub fn preview(&self, id: &str, file: u64) -> Result { + /// Achado + origem para leitura posicional (streaming de pré-visualização). + pub fn open_file(&self, id: &str, file: u64) -> Result<(Found, Arc)> { let j = self.job(id)?; - let (f, src) = { - let s = j.st.lock().unwrap(); - let i = *s - .index - .get(&file) - .ok_or_else(|| Error::msg("arquivo não encontrado"))?; - ( - s.found[i].clone(), - j.src.clone().ok_or_else(|| Error::msg("sem origem"))?, - ) - }; - let mime = match f.ext.as_str() { - "jpg" | "jpeg" => "image/jpeg", - "png" => "image/png", - "gif" => "image/gif", - "webp" => "image/webp", - "bmp" => "image/bmp", - _ => return Ok(json!({ "mime": null })), - }; - if f.size > 8 * 1024 * 1024 { - return Ok(json!({ "mime": null, "reason": "grande demais para pré-visualizar" })); - } - let tmp = - std::env::temp_dir().join(format!("guara-preview-{}-{}", std::process::id(), f.id)); - let r = recover::write_file(src.as_ref(), &f, &tmp); - let bytes = std::fs::read(&tmp); - let _ = std::fs::remove_file(&tmp); - r?; - Ok(json!({ "mime": mime, "base64": base64(&bytes?) })) + let s = j.st.lock().unwrap(); + let i = *s + .index + .get(&file) + .ok_or_else(|| Error::msg("arquivo não encontrado"))?; + Ok(( + s.found[i].clone(), + j.src.clone().ok_or_else(|| Error::msg("sem origem"))?, + )) } // ---------------------------------------------------------------- recuperação @@ -534,12 +515,12 @@ impl Engine { .unwrap_or_default(); self.results(&s("job")?, &q)? } - "preview" => self.preview( - &s("job")?, - p.get("id") - .and_then(|v| v.as_u64()) - .ok_or_else(|| Error::msg("id ausente"))?, - )?, + "settings_get" => json!(crate::settings::load()), + "settings_set" => { + let st: crate::settings::Settings = serde_json::from_value(p.clone())?; + crate::settings::save(&st)?; + json!({}) + } "recover_start" => { let ids: Option> = p .get("ids") @@ -697,3 +678,175 @@ pub fn base64(data: &[u8]) -> String { } out } + +/// Tipo MIME para servir a pré-visualização. Formatos que poderiam executar +/// script (HTML/SVG/XML) saem como texto puro. +pub fn mime_for(ext: &str) -> &'static str { + match ext.to_ascii_lowercase().as_str() { + "jpg" | "jpeg" => "image/jpeg", + "png" => "image/png", + "gif" => "image/gif", + "webp" => "image/webp", + "bmp" => "image/bmp", + "avif" => "image/avif", + "ico" => "image/x-icon", + "mp4" | "m4v" => "video/mp4", + "mov" => "video/quicktime", + "webm" => "video/webm", + "mkv" => "video/x-matroska", + "mp3" => "audio/mpeg", + "wav" => "audio/wav", + "ogg" | "opus" => "audio/ogg", + "m4a" => "audio/mp4", + "aac" => "audio/aac", + "flac" => "audio/flac", + "pdf" => "application/pdf", + _ => "application/octet-stream", + } +} + +/// Trecho de um arquivo achado, pronto para responder a uma requisição HTTP +/// (com suporte a `Range`) tanto no modo `guara ui` quanto no app Tauri. +pub struct FileSlice { + found: Found, + src: Arc, + pub start: u64, + /// Inclusivo. + pub end: u64, + pub total: u64, + pub partial: bool, +} + +impl FileSlice { + pub fn len(&self) -> u64 { + if self.total == 0 { + 0 + } else { + self.end - self.start + 1 + } + } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + pub fn status(&self) -> u16 { + if self.partial { + 206 + } else { + 200 + } + } + pub fn headers(&self) -> Vec<(&'static str, String)> { + let mut h = vec![ + ("Content-Type", mime_for(&self.found.ext).to_string()), + ("Accept-Ranges", "bytes".into()), + ("Cache-Control", "no-store".into()), + ("X-Content-Type-Options", "nosniff".into()), + // Conteúdo recuperado é não confiável: nunca executa script nem carrega nada. + ( + "Content-Security-Policy", + "sandbox; default-src 'none'".into(), + ), + ("Access-Control-Allow-Origin", "*".into()), + ("Content-Disposition", "inline".into()), + ]; + if self.partial { + h.push(( + "Content-Range", + format!("bytes {}-{}/{}", self.start, self.end, self.total), + )); + } + h + } + /// Lê o trecho inteiro em memória (limitado a `cap` bytes). + pub fn read_all(&self, cap: u64) -> std::io::Result> { + let n = self.len().min(cap) as usize; + let mut out = vec![0u8; n]; + let mut got = 0; + while got < n { + let r = crate::recover::read_found_at( + self.src.as_ref(), + &self.found, + self.start + got as u64, + &mut out[got..], + )?; + if r == 0 { + break; + } + got += r; + } + out.truncate(got); + Ok(out) + } + pub fn reader(self) -> FileSliceReader { + FileSliceReader { + pos: self.start, + slice: self, + } + } +} + +pub struct FileSliceReader { + slice: FileSlice, + pos: u64, +} + +impl std::io::Read for FileSliceReader { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.pos > self.slice.end || self.slice.total == 0 { + return Ok(0); + } + let left = (self.slice.end - self.pos + 1) as usize; + let n = buf.len().min(left).min(1 << 20); + let r = crate::recover::read_found_at( + self.slice.src.as_ref(), + &self.slice.found, + self.pos, + &mut buf[..n], + )?; + self.pos += r as u64; + Ok(r) + } +} + +impl Engine { + /// Resolve `/file//` + cabeçalho Range. `Err(status)` em caso de falha. + pub fn file_slice( + &self, + job: &str, + id: u64, + range: Option<&str>, + ) -> std::result::Result { + let (found, src) = self.open_file(job, id).map_err(|_| 404u16)?; + let total = found.size; + let (mut start, mut end, mut partial) = (0u64, total.saturating_sub(1), false); + if let Some(spec) = range.and_then(|r| r.strip_prefix("bytes=")) { + let spec = spec.split(',').next().unwrap_or(""); + if let Some((a, b)) = spec.split_once('-') { + let parsed = match (a.trim().parse::(), b.trim().parse::()) { + (Ok(a), Ok(b)) => Some((a, b.min(total.saturating_sub(1)))), + (Ok(a), Err(_)) if b.trim().is_empty() => Some((a, total.saturating_sub(1))), + (Err(_), Ok(n)) if a.trim().is_empty() && n > 0 => { + Some((total.saturating_sub(n), total.saturating_sub(1))) + } + _ => None, + }; + if let Some((a, b)) = parsed { + if a >= total || a > b { + return Err(416); + } + start = a; + end = b; + partial = true; + } + } + } + Ok(FileSlice { + found, + src, + start, + end, + total, + partial, + }) + } +} diff --git a/crates/guara-core/src/settings.rs b/crates/guara-core/src/settings.rs new file mode 100644 index 0000000..7f86780 --- /dev/null +++ b/crates/guara-core/src/settings.rs @@ -0,0 +1,118 @@ +//! Preferências do usuário (tema etc.), compartilhadas entre o app normal e o +//! reiniciado como administrador. + +use crate::error::Result; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Settings { + /// "auto", "light" ou "dark". + pub theme: String, +} + +impl Default for Settings { + fn default() -> Self { + Self { + theme: "auto".into(), + } + } +} + +/// Pasta de configuração do usuário *real*, mesmo quando rodando como root +/// via sudo/pkexec (para o tema não "mudar" ao elevar privilégios). +pub fn config_dir() -> PathBuf { + if let Ok(d) = std::env::var("GUARA_CONFIG_DIR") { + if !d.is_empty() { + return PathBuf::from(d); + } + } + #[cfg(unix)] + { + if let Some(home) = invoking_user_home() { + return default_dir(home); + } + } + default_dir(PathBuf::from( + std::env::var("HOME") + .or_else(|_| std::env::var("USERPROFILE")) + .unwrap_or_default(), + )) +} + +fn default_dir(home: PathBuf) -> PathBuf { + #[cfg(windows)] + { + if let Ok(a) = std::env::var("APPDATA") { + return PathBuf::from(a).join("Guara"); + } + home.join("AppData").join("Roaming").join("Guara") + } + #[cfg(target_os = "macos")] + { + home.join("Library") + .join("Application Support") + .join("Guara") + } + #[cfg(all(unix, not(target_os = "macos")))] + { + match std::env::var("XDG_CONFIG_HOME") { + Ok(x) + if !x.is_empty() + && std::env::var("SUDO_USER").is_err() + && std::env::var("PKEXEC_UID").is_err() => + { + PathBuf::from(x).join("guara") + } + _ => home.join(".config").join("guara"), + } + } +} + +/// Se somos root por sudo/pkexec, a home de quem invocou. +#[cfg(unix)] +fn invoking_user_home() -> Option { + // SAFETY: geteuid não tem pré-condições. + if unsafe { libc::geteuid() } != 0 { + return None; + } + let user = std::env::var("SUDO_USER").ok().filter(|u| u != "root"); + let uid = std::env::var("PKEXEC_UID").ok(); + let passwd = std::fs::read_to_string("/etc/passwd").ok()?; + for l in passwd.lines() { + let f: Vec<&str> = l.split(':').collect(); + if f.len() >= 6 && (user.as_deref() == Some(f[0]) || uid.as_deref() == Some(f[2])) { + return Some(PathBuf::from(f[5])); + } + } + None +} + +fn file() -> PathBuf { + config_dir().join("settings.json") +} + +pub fn load() -> Settings { + std::fs::read(file()) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() +} + +pub fn save(s: &Settings) -> Result<()> { + let dir = config_dir(); + std::fs::create_dir_all(&dir)?; + let path = file(); + std::fs::write(&path, serde_json::to_vec_pretty(s)?)?; + #[cfg(unix)] + { + // Como root, devolve a posse ao dono da pasta para o app normal conseguir regravar. + use std::os::unix::fs::MetadataExt; + if unsafe { libc::geteuid() } == 0 { + if let Ok(m) = std::fs::metadata(&dir) { + let _ = std::os::unix::fs::chown(&path, Some(m.uid()), Some(m.gid())); + } + } + } + Ok(()) +} diff --git a/crates/guara-core/tests/disk.rs b/crates/guara-core/tests/disk.rs index 047c0b2..e06a5b6 100644 --- a/crates/guara-core/tests/disk.rs +++ b/crates/guara-core/tests/disk.rs @@ -231,3 +231,74 @@ fn pausa_e_retoma_encontra_o_mesmo() { b.sort(); assert_eq!(a, b); } + +/// Streaming de pré-visualização: Range devolve exatamente os bytes do arquivo recuperado. +#[test] +fn file_slice_com_range_bate_com_o_arquivo_recuperado() { + use std::io::Read; + let Some(dir) = fixtures() else { return }; + let path = dir.join("ntfs.img"); + let eng = service::Engine::new(); + let job = eng + .start_scan( + path.to_str().unwrap(), + ScanOptions { + mode: ScanMode::Quick, + ..Default::default() + }, + ) + .unwrap(); + loop { + let st = eng.status(&job).unwrap(); + if st["status"] != "running" { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + let res = eng + .results( + &job, + &service::Query { + query: Some("relatorio.pdf".into()), + ..Default::default() + }, + ) + .unwrap(); + let id = res["items"][0]["id"].as_u64().unwrap(); + let size = res["items"][0]["size"].as_u64().unwrap(); + let want = expected(&dir, "ntfs") + .into_iter() + .find(|(_, p)| p.ends_with("relatorio.pdf")) + .unwrap() + .0; + + let full = eng.file_slice(&job, id, None).unwrap(); + assert_eq!((full.status(), full.len()), (200, size)); + let mut all = vec![]; + full.reader().read_to_end(&mut all).unwrap(); + assert_eq!(sha256(&all), want); + + let part = eng.file_slice(&job, id, Some("bytes=100-199")).unwrap(); + assert_eq!((part.status(), part.len()), (206, 100)); + assert_eq!(part.read_all(1 << 20).unwrap(), all[100..200]); + let tail = eng.file_slice(&job, id, Some("bytes=-50")).unwrap(); + assert_eq!(tail.read_all(1 << 20).unwrap(), all[all.len() - 50..]); + assert_eq!( + eng.file_slice(&job, id, Some(&format!("bytes={size}-"))) + .err(), + Some(416) + ); + assert_eq!(eng.file_slice(&job, 999_999, None).err(), Some(404)); +} + +#[test] +fn configuracoes_de_tema_persistem() { + let dir = tempfile::tempdir().unwrap(); + std::env::set_var("GUARA_CONFIG_DIR", dir.path()); + assert_eq!(settings::load().theme, "auto"); + settings::save(&settings::Settings { + theme: "dark".into(), + }) + .unwrap(); + assert_eq!(settings::load().theme, "dark"); +} diff --git a/crates/guara-core/tests/recovery.rs b/crates/guara-core/tests/recovery.rs index 86e62dd..4131aca 100644 --- a/crates/guara-core/tests/recovery.rs +++ b/crates/guara-core/tests/recovery.rs @@ -86,3 +86,58 @@ fn varredura_rapida_nao_faz_carving() { 7 ); } + +/// Regressão: mkfs.vfat -F 32 em mídia pequena (< 65525 clusters) é FAT32 pelo BPB. +#[test] +fn fat32_pequeno_com_poucos_clusters_e_reconhecido() { + use std::process::Command; + let dir = tempfile::tempdir().unwrap(); + let img = dir.path().join("p.img"); + let ok = Command::new("truncate") + .args(["-s", "32M"]) + .arg(&img) + .status() + .map(|s| s.success()) + .unwrap_or(false) + && Command::new("mkfs.vfat") + .args(["-F", "32"]) + .arg(&img) + .output() + .map(|o| o.status.success()) + .unwrap_or(false); + let file = dir.path().join("arquivo.txt"); + std::fs::write(&file, b"conteudo de teste\n".repeat(500)).unwrap(); + let ok = ok + && Command::new("mcopy") + .arg("-i") + .arg(&img) + .arg(&file) + .arg("::/") + .status() + .map(|s| s.success()) + .unwrap_or(false) + && Command::new("mdel") + .arg("-i") + .arg(&img) + .arg("::/arquivo.txt") + .status() + .map(|s| s.success()) + .unwrap_or(false); + if !ok { + eprintln!("SKIP: mtools/dosfstools ausentes"); + return; + } + let res = scan_path( + &img, + &ScanOptions { + mode: ScanMode::Quick, + ..Default::default() + }, + ); + let layout = res.layout.unwrap(); + assert_eq!(layout.partitions[0].fs, FsKind::Fat32); + assert_eq!(res.found.len(), 1); + let out = tempfile::tempdir().unwrap(); + recover_all(&img, &res.found, out.path()); + assert!(hashes_in(out.path()).contains_key(&sha256(&b"conteudo de teste\n".repeat(500)))); +} diff --git a/scripts/make-logo.py b/scripts/make-logo.py new file mode 100644 index 0000000..28aa196 --- /dev/null +++ b/scripts/make-logo.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Gera a identidade visual do Guará: pixels de tamanhos distintos, soltos à esquerda, +que se juntam até formar a cabeça de um lobo-guará à direita. + +Uso: python3 scripts/make-logo.py (escreve apps/gui/ui/guara.svg e guara-logo.svg) +Determinístico (semente fixa): a mesma execução gera o mesmo desenho. +""" +import math +import random +from pathlib import Path + +OUT = Path(__file__).resolve().parent.parent / "apps/gui/ui" + +# Cabeça de lobo-guará de perfil, olhando para a direita (coordenadas 0..100). +WOLF = [ + (-18, 100), (-2, 76), (10, 62), (16, 54), (21, 2), (30, 24), (41, 40), (47, 38), (57, 0), (62, 34), (72, 46), + (88, 55), (100, 60), (100, 69), (88, 73), (74, 77), (68, 84), (62, 100), (40, 100), +] +EYE = (63, 54, 2.4) # x, y, raio (em coords do lobo) + + +def inside(poly, x, y): + c = False + j = len(poly) - 1 + for i in range(len(poly)): + xi, yi = poly[i] + xj, yj = poly[j] + if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / (yj - yi) + xi: + c = not c + j = i + return c + + +def lerp(a, b, t): + return a + (b - a) * t + + +def hexmix(c1, c2, t): + a = [int(c1[i:i + 2], 16) for i in (1, 3, 5)] + b = [int(c2[i:i + 2], 16) for i in (1, 3, 5)] + return "#" + "".join(f"{round(lerp(x, y, t)):02x}" for x, y in zip(a, b)) + + +def smooth(t): + t = max(0.0, min(1.0, t)) + return t * t * (3 - 2 * t) + + +def pixels(x_from, x_to, c_left, c_right, seed=7): + rnd = random.Random(seed) + cell = 4.0 + out = [] + wolf_x0, wolf_w = 62, 98 # onde o lobo começa e quanto mede (em unidades do desenho) + for cy in range(25): + for cx in range(40): + x, y = cx * cell + cell / 2, cy * cell + cell / 2 + if not (x_from <= x <= x_to): + continue + t = smooth((x - 14) / 96) + wx, wy = (x - wolf_x0) * 100 / wolf_w, y + in_wolf = inside(WOLF, wx, wy) and math.hypot(wx - EYE[0], wy - EYE[1]) > EYE[2] + if in_wolf: + keep = 0.06 + 0.94 * t ** 1.15 + if t > 0.9: + keep = 1.0 + if rnd.random() > keep: + continue + size = cell * (0.28 + 0.72 * t ** 0.9) * (1 if t > 0.9 else rnd.uniform(0.65, 1.15)) + jit = (1 - t) ** 1.4 * cell * 0.9 + else: + if rnd.random() > 0.2 * (1 - t) ** 1.2 or x > 96: + continue + size = cell * rnd.uniform(0.22, 0.85) + jit = cell * 0.9 + size = min(size, cell * 1.05) + px = x - size / 2 + rnd.uniform(-jit, jit) + py = y - size / 2 + rnd.uniform(-jit, jit) + col = hexmix(c_left, c_right, max(0.0, min(1.0, t * 1.05 + rnd.uniform(-0.12, 0.12)))) + op = 0.5 + 0.5 * t if not in_wolf or t < 0.9 else 1 + out.append((px, py, size, col, op)) + return out + + +def rects(px, dx=0.0, dy=0.0): + return "".join( + f'' + for x, y, s, c, o in px + ) + + +def main(): + # Marca larga (fundo transparente): ciano claro -> verde-azulado profundo. + wide = pixels(0, 160, "#67e8f9", "#0f766e") + (OUT / "guara-logo.svg").write_text( + '' + rects(wide) + "\n" + ) + # Ícone quadrado: fundo verde-azulado escuro, pixels claros. + icon_px = pixels(30, 160, "#99f6e4", "#f0fdfa", seed=11) + (OUT / "guara.svg").write_text( + '' + '' + '' + '' + rects(icon_px) + "\n" + ) + + +if __name__ == "__main__": + main()