Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

53.2 KB
Raw Blame
// Prefer native webview navigation over page JS so Ctrl+R / [ / ] still work
// on blank error shells (no JS context). Falls back to history/location when
// the IPC bridge is unavailable.
function nativeNavigate(action) {
  const invoke = window.__PAKE_NATIVE__?.core?.invoke;
  if (invoke) {
    invoke("webview_navigate", { action }).catch(() => {
      fallbackNavigate(action);
    });
    return;
  }
  fallbackNavigate(action);
}

function fallbackNavigate(action) {
  if (action === "reload") {
    window.location.reload();
  } else if (action === "back") {
    window.history.back();
  } else if (action === "forward") {
    window.history.forward();
  } else if (action === "home") {
    const homeUrl = packagedHomeUrl();
    if (homeUrl) {
      window.location.href = homeUrl;
    }
  }
}

// A page on another origin has no IPC, so it goes home by address. A local
// app's url is only a file name, which would resolve against the site the
// window is on; its bundled page lives where navigation.rs says it does.
function packagedHomeUrl() {
  const url = window.pakeConfig?.url;
  if (!url || window.pakeConfig?.url_type !== "local") {
    return url;
  }
  const base = /win/i.test(getDesktopPlatform())
    ? "http://tauri.localhost/"
    : "tauri://localhost/";
  // Same escaping as local_site::entry_path, so `chart #1.html` stays one file name.
  return (
    base + url.replace(/%/g, "%25").replace(/#/g, "%23").replace(/\?/g, "%3F")
  );
}

const shortcuts = {
  "[": () => nativeNavigate("back"),
  "]": () => nativeNavigate("forward"),
  "-": () => zoomOut(),
  "=": () => zoomIn(),
  "+": () => zoomIn(),
  0: () => setZoom("100%"),
  r: () => nativeNavigate("reload"),
  ArrowUp: () => scrollTo(0, 0),
  ArrowDown: () => scrollTo(0, document.body.scrollHeight),
};

function setZoom(zoom) {
  // Use native WebView zoom (WKWebView pageZoom / WebView2 ZoomFactor) instead of
  // CSS hacks. `transform: scale` and `html.style.zoom` break complex SPAs like
  // ChatGPT: the page shifts right on Windows and parts of the UI stop repainting
  // on macOS. Native zoom recalculates layout exactly like a browser does.
  const zoomPercent = normalizeZoomPercent(zoom);
  const normalizedZoom = `${zoomPercent}%`;
  const invoke = window.__PAKE_NATIVE__?.core?.invoke;
  if (invoke) {
    invoke("set_zoom", { percent: zoomPercent }).catch(() => {});
  }

  try {
    window.localStorage.setItem("htmlZoom", normalizedZoom);
  } catch {}
}

function zoomCommon(zoomChange) {
  let currentZoom = "100%";
  try {
    currentZoom = window.localStorage.getItem("htmlZoom") || "100%";
  } catch {}
  setZoom(zoomChange(normalizeZoomPercent(currentZoom)));
}

function zoomIn() {
  zoomCommon((currentZoom) => `${Math.min(currentZoom + 10, 200)}%`);
}

function zoomOut() {
  zoomCommon((currentZoom) => `${Math.max(currentZoom - 10, 30)}%`);
}

function normalizeZoomPercent(zoom) {
  const parsed = parseFloat(zoom);
  return Number.isFinite(parsed) ? parsed : 100;
}

let pasteAsPlainTextPending = false;

function triggerPasteAsPlainText() {
  pasteAsPlainTextPending = true;
  document.execCommand("paste");
  setTimeout(() => {
    pasteAsPlainTextPending = false;
  }, 100);
}

function handleShortcut(event) {
  if (shortcuts[event.key]) {
    event.preventDefault();
    shortcuts[event.key]();
  }
}

// What the macOS app menu carries and Windows and Linux, with no menu, lacked:
// close the window, quit, copy the page address, as a browser's Ctrl+W, Ctrl+Q
// and Ctrl+L. A browser keeps all three for itself, so no page relies on them.
function closeCurrentWindow() {
  // close() raises the window's close request, so hide-on-close still applies.
  window.__PAKE_NATIVE__?.window?.getCurrentWindow?.()?.close?.();
}

function quitApp() {
  window.__PAKE_NATIVE__?.core?.invoke?.("quit_app")?.catch?.(() => {});
}

function copyPageAddress() {
  const address = window.location.href;
  const write = navigator.clipboard?.writeText?.(address);
  if (write?.catch) {
    write.catch(() => copyTextWithSelection(address));
  } else if (!write) {
    copyTextWithSelection(address);
  }
}

function copyTextWithSelection(text) {
  const field = document.createElement("textarea");
  field.value = text;
  field.setAttribute("readonly", "");
  field.style.cssText = "position:fixed;top:0;left:0;opacity:0;";
  document.body.appendChild(field);
  field.select();
  document.execCommand("copy");
  field.remove();
}

const windowShortcuts = {
  w: closeCurrentWindow,
  q: quitApp,
  l: copyPageAddress,
};

const shiftShortcuts = {
  h: () => nativeNavigate("home"),
};

const altShortcuts = {
  ArrowLeft: () => nativeNavigate("back"),
  ArrowRight: () => nativeNavigate("forward"),
};

// The page gets these keys first: this listens on window for keydown in the
// bubble phase, after the page's own handlers, and leaves alone a key the page
// prevented. A web terminal or editor that takes Ctrl+W (delete a word), Ctrl+L
// (clear) or Alt+Left (word left) on keydown keeps it, as find.js does for Ctrl+F.
function handleWindowShortcut(event) {
  if (!isNonMacDesktop() || event.defaultPrevented || event.repeat) {
    return;
  }

  let action;
  if (event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey) {
    action = windowShortcuts[event.key?.toLowerCase?.()];
  } else if (
    event.ctrlKey &&
    event.shiftKey &&
    !event.altKey &&
    !event.metaKey
  ) {
    // A window the page opened, such as a sign-in popup, is not the app's.
    action = window.pakeConfig?.page_popup
      ? undefined
      : shiftShortcuts[event.key?.toLowerCase?.()];
  } else if (
    event.altKey &&
    !event.ctrlKey &&
    !event.shiftKey &&
    !event.metaKey
  ) {
    action = altShortcuts[event.key];
  }
  if (!action) {
    return;
  }

  event.preventDefault();
  action();
}

const EDITABLE_SKIPPED_SHORTCUTS = new Set(["ArrowUp", "ArrowDown", "[", "]"]);

function handleWebShortcut(event) {
  if (event.defaultPrevented || event.altKey) {
    return;
  }
  if (event.shiftKey && event.key !== "+") {
    return;
  }
  if (
    EDITABLE_SKIPPED_SHORTCUTS.has(event.key) &&
    isEditableElement(document.activeElement)
  ) {
    return;
  }

  if (isNonMacDesktop() && event.ctrlKey && !event.metaKey) {
    handleShortcut(event);
    return;
  }

  const isMac = /mac/i.test(getDesktopPlatform());
  const isMacScrollShortcut =
    event.key === "ArrowUp" || event.key === "ArrowDown";
  if (isMac && event.metaKey && !event.ctrlKey && isMacScrollShortcut) {
    handleShortcut(event);
  }
}

function toggleNativeFullscreen(appWindow) {
  appWindow
    .isFullscreen()
    .then((fullscreen) => {
      if (document.fullscreenElement && document.exitFullscreen) {
        return document.exitFullscreen();
      }
      return appWindow.setFullscreen(!fullscreen);
    })
    .catch((error) => {
      console.warn("[Pake] Failed to toggle native fullscreen:", error);
    });
}

function handleWindowFullscreenShortcut(event) {
  if (
    !event.isTrusted ||
    event.repeat ||
    event.key !== "F11" ||
    !isNonMacDesktop()
  ) {
    return;
  }

  const appWindow = window.__PAKE_NATIVE__?.window?.getCurrentWindow?.();
  if (!appWindow) {
    return;
  }

  event.preventDefault();
  event.stopImmediatePropagation();
  toggleNativeFullscreen(appWindow);
}

function getDesktopPlatform() {
  return (
    navigator.userAgentData?.platform ||
    navigator.platform ||
    navigator.userAgent
  );
}

function isNonMacDesktop() {
  return /win|linux/i.test(getDesktopPlatform());
}

function hasImmersiveHeader(config = window["pakeConfig"] || {}) {
  return /mac/i.test(getDesktopPlatform())
    ? config.hide_title_bar === true
    : config.hide_window_decorations === true;
}

function isEditableElement(element) {
  if (!element) return false;

  const tagName = element.tagName;
  return (
    tagName === "INPUT" || tagName === "TEXTAREA" || element.isContentEditable
  );
}

function hasSelectedText() {
  return Boolean(window.getSelection?.()?.toString());
}

const NON_TEXT_INPUT_TYPES = new Set([
  "button",
  "checkbox",
  "color",
  "file",
  "hidden",
  "image",
  "radio",
  "range",
  "reset",
  "submit",
]);

function isTextInputElement(element) {
  return (
    element?.tagName === "INPUT" &&
    !NON_TEXT_INPUT_TYPES.has((element.type || "text").toLowerCase())
  );
}

function selectEditableElement(element) {
  if (typeof element.select === "function") {
    element.select();
    return true;
  }

  if (element.isContentEditable) {
    const range = document.createRange();
    range.selectNodeContents(element);
    const selection = window.getSelection?.();
    if (!selection) return false;

    selection.removeAllRanges();
    selection.addRange(range);
    return true;
  }

  return false;
}

function canPasteIntoEditableElement(element) {
  if (!isEditableElement(element)) return false;

  if (element.tagName === "INPUT") {
    return (
      isTextInputElement(element) &&
      element.disabled !== true &&
      element.readOnly !== true
    );
  }

  if (element.tagName === "TEXTAREA") {
    return element.disabled !== true && element.readOnly !== true;
  }

  return true;
}

function insertTextIntoEditableElement(element, text) {
  if (!text) return false;

  if (document.execCommand("insertText", false, text)) {
    return true;
  }

  if (
    element &&
    (isTextInputElement(element) || element.tagName === "TEXTAREA") &&
    typeof element.setRangeText === "function"
  ) {
    const valueLength =
      typeof element.value === "string" ? element.value.length : 0;
    const start =
      typeof element.selectionStart === "number"
        ? element.selectionStart
        : valueLength;
    const end =
      typeof element.selectionEnd === "number" ? element.selectionEnd : start;
    element.setRangeText(text, start, end, "end");
    element.dispatchEvent?.(new Event("input", { bubbles: true }));
    return true;
  }

  return false;
}

let clipboardPasteFallbackTarget;
let clipboardPasteFallbackArmedAt = 0;
// An armed fallback older than this is a leftover from a keyup the window
// never saw (alt-tab mid-press); firing it on a later plain "v" keyup would
// paste unexpectedly.
const CLIPBOARD_PASTE_FALLBACK_TTL_MS = 5000;

function pasteClipboardText(activeElement) {
  const readText = navigator.clipboard?.readText;
  if (typeof readText !== "function") {
    return;
  }

  readText
    .call(navigator.clipboard)
    .then((text) => {
      insertTextIntoEditableElement(activeElement, text);
    })
    .catch(() => {});
}

function handleClipboardShortcut(event) {
  if (
    event.isTrusted !== true ||
    !isNonMacDesktop() ||
    !event.ctrlKey ||
    event.metaKey ||
    event.altKey ||
    event.shiftKey
  ) {
    return false;
  }

  const key = event.key?.toLowerCase();
  const activeElement = document.activeElement;
  const isEditable = isEditableElement(activeElement);

  if (key === "c" && (isEditable || hasSelectedText())) {
    document.execCommand("copy");
    event.preventDefault();
    return true;
  }

  if (key === "x" && isEditable) {
    document.execCommand("cut");
    event.preventDefault();
    return true;
  }

  if (key === "v" && canPasteIntoEditableElement(activeElement)) {
    // Let the native WebView paste event run first so images, files, and rich
    // clipboard formats remain intact. If the platform does not emit paste,
    // keyup applies the existing text-only fallback. Key-repeat must not
    // re-arm: after a native paste already fired and disarmed the fallback,
    // a repeat keydown re-arming it would make keyup paste text a second
    // time. Repeats only refresh the TTL of a still-armed target.
    if (!event.repeat) {
      clipboardPasteFallbackTarget = activeElement;
      clipboardPasteFallbackArmedAt = Date.now();
    } else if (clipboardPasteFallbackTarget === activeElement) {
      clipboardPasteFallbackArmedAt = Date.now();
    }
    return false;
  }

  if (key === "a" && isEditable && selectEditableElement(activeElement)) {
    event.preventDefault();
    return true;
  }

  return false;
}

function handleClipboardPasteFallback(event) {
  if (
    event.isTrusted !== true ||
    !isNonMacDesktop() ||
    event.key?.toLowerCase() !== "v"
  ) {
    return false;
  }

  const activeElement = clipboardPasteFallbackTarget;
  const armedAt = clipboardPasteFallbackArmedAt;
  clipboardPasteFallbackTarget = undefined;
  if (
    !activeElement ||
    Date.now() - armedAt > CLIPBOARD_PASTE_FALLBACK_TTL_MS ||
    document.activeElement !== activeElement ||
    !canPasteIntoEditableElement(activeElement)
  ) {
    return false;
  }

  pasteClipboardText(activeElement);
  return true;
}

function handlePaste(event) {
  clipboardPasteFallbackTarget = undefined;
  if (!pasteAsPlainTextPending) return;

  event.preventDefault();
  event.stopImmediatePropagation();

  const text = event.clipboardData?.getData("text/plain") || "";
  if (text) {
    document.execCommand("insertText", false, text);
  }
}

const DOWNLOADABLE_FILE_EXTENSIONS = {
  documents: [
    "pdf",
    "doc",
    "docx",
    "xls",
    "xlsx",
    "ppt",
    "pptx",
    "txt",
    "rtf",
    "odt",
    "ods",
    "odp",
    "pages",
    "numbers",
    "key",
    "epub",
    "mobi",
  ],
  archives: [
    "zip",
    "rar",
    "7z",
    "tar",
    "gz",
    "gzip",
    "bz2",
    "xz",
    "lzma",
    "deb",
    "rpm",
    "pkg",
    "msi",
    "exe",
    "dmg",
    "apk",
    "ipa",
  ],
  // Navigable web formats (json/xml/js/css/html and friends) are intentionally
  // omitted: documentation and SPA content negotiation often serve them as
  // in-app pages. Real file downloads still match via the download attribute,
  // ?download / ?attachment, or binary extensions below.
  data: ["csv", "sql", "db", "sqlite"],
  scripts: ["sh", "bat", "ps1"],
  fonts: ["ttf", "otf", "woff", "woff2", "eot"],
  design: ["ai", "psd", "sketch", "fig", "xd"],
  system: [
    "iso",
    "img",
    "bin",
    "torrent",
    "jar",
    "war",
    "indd",
    "fla",
    "swf",
    "raw",
  ],
};

const ALL_DOWNLOADABLE_EXTENSIONS = Object.values(
  DOWNLOADABLE_FILE_EXTENSIONS,
).flat();

const PREVIEWABLE_MEDIA_EXTENSIONS = [
  "png",
  "jpg",
  "jpeg",
  "gif",
  "webp",
  "svg",
  "bmp",
  "tiff",
  "tif",
  "avif",
  "heic",
  "heif",
  "mp4",
  "webm",
  "mov",
  "m4v",
  "mkv",
  "avi",
  "ogv",
  "mp3",
  "wav",
  "ogg",
  "flac",
  "aac",
  "m4a",
];

// Path fragments that often host real file downloads. Keep this list empty:
// SPA routes such as "/assets/", "/dist/", "/files/", "/releases/",
// "/attachments/", and "/download/" (e.g. "/download/mac") have been mistaken
// for downloads in the wild. Real downloads still match via the download
// attribute, ?download / ?attachment query hints, or file extensions.
const DOWNLOAD_PATH_PATTERNS = [];

// Language detection utilities
function getUserLanguage() {
  return navigator.language || navigator.userLanguage;
}

function isChineseLanguage(language = getUserLanguage()) {
  return (
    language &&
    (language.startsWith("zh") ||
      language.includes("CN") ||
      language.includes("TW") ||
      language.includes("HK"))
  );
}

// User notification helper. Rust download_file already shows an in-page toast
// on failure via show_toast, so avoid raising a second Web Notification (which
// would also increment the Dock unread badge).
function showDownloadError(filename) {
  const isChinese = isChineseLanguage();
  const message = isChinese
    ? `下载失败: ${filename}`
    : `Download failed: ${filename}`;
  console.error(message);
}

function getExtension(url) {
  try {
    const pathname = new URL(url).pathname.toLowerCase();
    const extensionIndex = pathname.lastIndexOf(".");
    return extensionIndex > -1 ? pathname.slice(extensionIndex + 1) : "";
  } catch (e) {
    return "";
  }
}

function isPreviewableMedia(url) {
  const extension = getExtension(url);
  return PREVIEWABLE_MEDIA_EXTENSIONS.includes(extension);
}

// Unified file detection - replaces both isDownloadLink and isFileLink
function isDownloadableFile(url) {
  try {
    const extension = getExtension(url);
    if (PREVIEWABLE_MEDIA_EXTENSIONS.includes(extension)) {
      return false;
    }

    const urlObj = new URL(url);
    const hasDownloadHints =
      urlObj.searchParams.has("download") ||
      urlObj.searchParams.has("attachment");

    if (hasDownloadHints) {
      return true;
    }

    return (
      ALL_DOWNLOADABLE_EXTENSIONS.includes(extension) ||
      DOWNLOAD_PATH_PATTERNS.some((pattern) =>
        urlObj.pathname.toLowerCase().includes(pattern),
      )
    );
  } catch (e) {
    return false;
  }
}

function normalizeAnchorHref(rawHref) {
  return typeof rawHref === "string" ? rawHref.trim() : "";
}

function shouldBypassPakeLinkHandling(rawHref) {
  const normalizedHref = normalizeAnchorHref(rawHref).toLowerCase();
  if (!normalizedHref) {
    return false;
  }

  return (
    normalizedHref.startsWith("javascript:") || normalizedHref.startsWith("#")
  );
}

function shouldNavigateAuthInCurrentWindow() {
  // WKWebView can abort on auth popups, while WebKitGTK may return a truthy
  // proxy even when the native side denies the window. Keep those platforms
  // in-place without changing the working WebView2 popup path on Windows.
  return /mac|linux/i.test(getDesktopPlatform());
}

function canNavigateAuthUrl(url) {
  const normalizedUrl = normalizeAnchorHref(url).toLowerCase();
  return normalizedUrl !== "" && normalizedUrl !== "about:blank";
}

function isAppleAuthPopup(url, name) {
  if (name === "AppleAuthentication") {
    return true;
  }

  try {
    return (
      new URL(url, window.location.href).hostname.toLowerCase() ===
      "appleid.apple.com"
    );
  } catch (error) {
    return false;
  }
}

function navigateInCurrentWindow(url) {
  window.location.href = url;
  return window;
}

function openAuthNavigation(originalWindowOpen, url, name, specs) {
  if (isAppleAuthPopup(url, name)) {
    const authWindow = originalWindowOpen.call(window, url, name, specs);
    if (authWindow) {
      return authWindow;
    }
  }

  if (shouldNavigateAuthInCurrentWindow() && canNavigateAuthUrl(url)) {
    return navigateInCurrentWindow(url);
  }

  const authWindow = originalWindowOpen.call(window, url, name, specs);
  if (!authWindow) {
    return navigateInCurrentWindow(url);
  }

  return authWindow;
}

// A popup's page closes itself the moment it has answered its opener, often
// in its first script, while an IPC call of that page load is still out:
// Tauri's notification plugin asks for its permission in every document.
// WebKit cancels a closing page's requests, and on macOS the answer to a
// cancelled IPC request ends the whole app, because the release profile
// cannot catch the exception WebKit raises for it (measured: every sign-in
// popup that closed itself took the app with it). The answer takes a couple
// of milliseconds, so the close waits them out. Every top-level page gets
// the wait: a popup opened with noopener has no window.opener to tell it by.
// In the main window it is a precaution only; a first page that closed
// itself there did not end the app in three runs without it.
const WINDOW_CLOSE_DELAY_MS = 150;
function isTopWindow() {
  return !window.top || window === window.top;
}

function deferWindowClose() {
  if (!isTopWindow() || typeof window.close !== "function") return;
  if (!/mac/i.test(getDesktopPlatform())) return;
  const nativeClose = window.close.bind(window);
  let pending = false;
  window.close = function () {
    if (pending) return;
    pending = true;
    setTimeout(() => {
      pending = false;
      nativeClose();
    }, WINDOW_CLOSE_DELAY_MS);
  };
}
deferWindowClose();

// Install the receiver at document start: a subframe can open a link before
// the main page's DOMContentLoaded routing setup has run.
let openFrameLink = null;
const pendingFrameLinks = [];
function isDescendantFrame(source, parent = window) {
  for (let index = 0; index < parent.frames.length; index++) {
    const frame = parent.frames[index];
    if (frame === source || isDescendantFrame(source, frame)) return true;
  }
  return false;
}
function routeFrameLink(source, href) {
  try {
    // Recheck on delivery because the frame may have been removed meanwhile.
    if (!isDescendantFrame(source)) return;
    const url = new URL(href);
    if (!["http:", "https:", "mailto:", "tel:"].includes(url.protocol)) return;
    if (openFrameLink) {
      openFrameLink.call(window, url.href, "_blank");
    } else {
      pendingFrameLinks.push({ source, href: url.href });
    }
  } catch (error) {
    console.error("[Pake] Failed to route frame link:", error);
  }
}
if (isTopWindow()) {
  window.addEventListener("message", (event) => {
    if (
      event.data?.type !== "pake:frame-external-link" ||
      typeof event.data.url !== "string" ||
      !event.source ||
      event.source === window
    )
      return;
    routeFrameLink(event.source, event.data.url);
  });
  window.addEventListener("pagehide", () => {
    pendingFrameLinks.length = 0;
  });
}

document.addEventListener("DOMContentLoaded", () => {
  const tauri = window.__PAKE_NATIVE__;
  const appWindow = tauri.window.getCurrentWindow();
  const invoke = tauri.core.invoke;
  const pakeConfig = window["pakeConfig"] || {};
  const forceInternalNavigation = pakeConfig.force_internal_navigation === true;
  const matchesInternalUrl = createInternalUrlMatcher(
    pakeConfig.internal_url_regex,
  );
  const topWindow = isTopWindow();

  if (topWindow) {
    if (!document.getElementById("pake-top-dom") && hasImmersiveHeader()) {
      const topDom = document.createElement("div");
      topDom.id = "pake-top-dom";
      document.body.appendChild(topDom);
    }

    const domEl = document.getElementById("pake-top-dom");

    if (domEl) {
      domEl.addEventListener("touchstart", () => {
        appWindow.startDragging();
      });

      domEl.addEventListener("mousedown", (e) => {
        e.preventDefault();
        if (e.buttons === 1 && e.detail !== 2) {
          appWindow.startDragging();
        }
      });

      domEl.addEventListener("dblclick", () => {
        toggleNativeFullscreen(appWindow);
      });
    }

    if (window["pakeConfig"]?.disabled_web_shortcuts !== true) {
      document.addEventListener(
        "keydown",
        handleWindowFullscreenShortcut,
        true,
      );
      document.addEventListener("keydown", handleWebShortcut);
      window.addEventListener("keydown", handleWindowShortcut);
    }
  }

  document.addEventListener("keydown", handleClipboardShortcut, true);
  document.addEventListener("keyup", handleClipboardPasteFallback, true);
  document.addEventListener("paste", handlePaste, true);

  // Trigger a native browser download via a transient anchor click. The Rust
  // on_download handler then writes the file to the Downloads folder. This is
  // used for blob:/data: URLs because routing their bytes through the Tauri
  // IPC fails on strict-CSP sites (e.g. Gemini), whose connect-src blocks the
  // IPC origin. It also handles attachments when remote IPC is denied.
  const nativeDownloadAnchors = new WeakSet();
  function triggerNativeDownload(url, filename) {
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = filename || "";
    anchor.style.display = "none";
    nativeDownloadAnchors.add(anchor);
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
  }

  // process special download protocol['data:','blob:']
  const isSpecialDownload = (url) =>
    ["blob", "data"].some((protocol) => url.startsWith(protocol));

  // Cmd/Ctrl+click is a browser "open related" gesture, not "save as".
  // Only the download attribute and downloadable-file heuristics force a
  // download; modifiers must not rewrite ordinary navigation.
  const isDownloadRequired = (url, anchorElement, _e) =>
    Boolean(anchorElement.download) || isDownloadableFile(url);

  const handleExternalLink = (url) => {
    // Don't try to open blob: or data: URLs with shell
    if (isSpecialDownload(url)) {
      console.warn("Cannot open special URL with shell:", url);
      return;
    }

    // WebView2 runs this script in subframes too, where IPC is denied for the
    // frame's own origin. Hand the link to the top page like frame_links.js.
    if (!topWindow) {
      window.top.postMessage({ type: "pake:frame-external-link", url }, "*");
      return;
    }

    invoke("plugin:opener|open_url", {
      url,
    }).catch((error) => {
      console.error("Failed to open URL with opener:", url, error);
    });
  };

  function downloadFile(url, filename) {
    // download attributes reliably force same-origin resources to save instead
    // of navigating. Cross-origin resources retain the HTTP fallback because
    // browsers can ignore their download attribute (including PDFs and images).
    if (
      window.pakeNativeDownloads === true &&
      (isSpecialDownload(url) ||
        new URL(url, window.location.href).origin === window.location.origin)
    ) {
      triggerNativeDownload(url, filename);
      return Promise.resolve();
    }
    return invoke("download_file", {
      params: {
        url,
        filename,
        language: getUserLanguage(),
        user_agent: navigator.userAgent,
        page_url: window.location.href,
      },
    }).catch((error) => {
      // Debug and release builds have different ACL rejection messages.
      // Let the browser handle attachments without granting remote IPC.
      if (/^(?:Command )?download_file not allowed\b/.test(String(error))) {
        triggerNativeDownload(url, filename);
        return;
      }
      console.error("Failed to download file:", filename, error);
      showDownloadError(filename);
    });
  }

  const isInternalUrl = (url) => matchesInternalUrl(url, window.location.href);

  // An internal target="_blank" link clicked with --new-window, waiting for
  // the page's own handlers to have their say.
  let pendingBlankLink = null;
  const openUnhandledBlankLink = (e) => {
    const pending = pendingBlankLink;
    pendingBlankLink = null;
    if (!pending || pending.event !== e || e.defaultPrevented) return;
    if (pending.url) {
      e.preventDefault();
      originalWindowOpen.call(window, pending.url, "_blank");
      return;
    }
    routeLateNewTabLink(e, pending.anchor);
  };

  // A held link got its address during the click and nobody handled it: route
  // it now as the click guard would have at the start. An internal address
  // without --new-window is left to the default action, which follows the
  // link's _self target inside the app.
  const routeLateNewTabLink = (e, anchorElement) => {
    let lateUrl;
    try {
      lateUrl = new URL(anchorElement.href);
    } catch (error) {
      return;
    }
    if (!["http:", "https:"].includes(lateUrl.protocol)) return;
    const absoluteUrl = lateUrl.href;
    if (forceInternalNavigation || window.isAuthLink(absoluteUrl)) {
      e.preventDefault();
      window.location.href = absoluteUrl;
      return;
    }
    if (isInternalUrl(absoluteUrl)) {
      if (window.pakeConfig?.new_window) {
        e.preventDefault();
        originalWindowOpen.call(window, absoluteUrl, "_blank");
      }
      return;
    }
    e.preventDefault();
    handleExternalLink(absoluteUrl);
  };

  // A new-tab link with no address yet. Some pages give the link its address
  // during the click and handle the click themselves: Douyin's episode covers
  // are <a target="_blank"> with no href, their own handler sets the href to
  // "undefined", switches the video and prevents the default. The click guard
  // skipped a link with no address, so it kept its _blank target through the
  // bubble, where Tauri's shell plugin opens whatever address the link has by
  // then, handled or not: the browser came up at douyin.com/undefined on every
  // switch, with or without --new-window (the same user's second report,
  // 2026-11-19; the first fix only held links that had an address when the
  // click began). The target is taken away for the click, and
  // openUnhandledBlankLink routes the link if nobody handled it.
  const holdAddresslessNewTabLink = (e, anchorElement) => {
    const askedFor = anchorElement.target;
    anchorElement.target = "_self";
    pendingBlankLink = { event: e, anchor: anchorElement, url: null };
    setTimeout(() => {
      anchorElement.target = askedFor;
    }, 0);
  };

  // An internal link that asks for a new tab (target _blank or _new).
  //
  // With --new-window the Rust on_new_window handler opens an in-app window.
  // Without it, leaving the target untouched lets the native webview
  // escalate the click to a system-browser "new window".
  //
  // Many SPAs (e.g. Plane) tag in-app links with target="_blank" but route
  // the click themselves via a React onClick that calls preventDefault +
  // client-side navigation. Forcing a full window.location reload here (and
  // stopping propagation) would defeat that handler and reload the whole app
  // on every click. Instead, retarget the link to "_self" so the webview
  // never opens a browser window, then let the page's own handler run. If
  // nothing intercepts the click, the default _self navigation keeps it
  // inside the app.
  //
  // With --new-window the link is retargeted for this click as well: left
  // as _blank, Tauri's shell plugin, whose own click listener on body opens
  // every target="_blank" link in the system browser without asking whether
  // the page handled the click, sent the link there even after the page had
  // (Douyin's episode list: each switch opened douyin.com/undefined in the
  // browser, a user's report, 2026-11-18). openUnhandledBlankLink, last in
  // the bubble, opens the in-app window when nobody prevented the click.
  const keepInternalNewTabLinkInApp = (e, anchorElement, absoluteUrl) => {
    const askedFor = anchorElement.target;
    anchorElement.target = "_self";
    if (window.pakeConfig?.new_window) {
      pendingBlankLink = { event: e, anchor: anchorElement, url: absoluteUrl };
      setTimeout(() => {
        anchorElement.target = askedFor;
      }, 0);
    }
  };

  // Cmd-click on macOS and Ctrl-click on Windows and Linux open a link in the
  // default browser, the app's own site included, as a browser opens one in
  // a new tab; so does a middle click (a user's request, 2026-11-22). Ctrl on
  // macOS is a secondary click and stays one. A download link keeps
  // downloading, and blob: or data: has no browser to go to.
  const opensInBrowser = (e) =>
    /mac/i.test(getDesktopPlatform()) ? Boolean(e.metaKey) : Boolean(e.ctrlKey);

  const openLinkInBrowser = (e, anchorElement) => {
    if (!anchorElement || !anchorElement.href || anchorElement.download) {
      return false;
    }
    const rawHref = anchorElement.getAttribute("href") || "";
    if (shouldBypassPakeLinkHandling(rawHref)) return false;
    let url;
    try {
      url = new URL(anchorElement.href);
    } catch {
      return false;
    }
    if (url.protocol !== "http:" && url.protocol !== "https:") return false;
    e.preventDefault();
    e.stopImmediatePropagation();
    handleExternalLink(url.href);
    return true;
  };

  const openMiddleClickedLink = (e) => {
    if (e.button !== 1) return;
    if (!e.target || typeof e.target.closest !== "function") return;
    openLinkInBrowser(e, e.target.closest("a"));
  };

  const detectAnchorElementClick = (e) => {
    // Safety check: ensure e.target exists and is an Element with closest method
    if (!e.target || typeof e.target.closest !== "function") {
      return;
    }
    const anchorElement = e.target.closest("a");

    if (anchorElement && nativeDownloadAnchors.has(anchorElement)) return;

    if (opensInBrowser(e) && openLinkInBrowser(e, anchorElement)) return;

    if (
      anchorElement &&
      !anchorElement.href &&
      anchorElement.target === "_blank"
    ) {
      holdAddresslessNewTabLink(e, anchorElement);
      return;
    }

    if (anchorElement && anchorElement.href) {
      const rawHref = anchorElement.getAttribute("href") || "";
      if (shouldBypassPakeLinkHandling(rawHref)) {
        return;
      }

      const target = anchorElement.target;
      let hrefUrl;
      try {
        hrefUrl = new URL(anchorElement.href);
      } catch {
        return;
      }
      if (["mailto:", "tel:"].includes(hrefUrl.protocol)) return;
      const absoluteUrl = hrefUrl.href;
      let filename = anchorElement.download || getFilenameFromUrl(absoluteUrl);

      // Keep OAuth/authentication flows inside the app. Without --new-window,
      // navigate in place so the SSO redirect chain and callback stay in the
      // webview instead of falling through to the system browser.
      if (window.isAuthLink(absoluteUrl)) {
        console.log("[Pake] Handling OAuth navigation in-app:", absoluteUrl);
        e.preventDefault();
        e.stopImmediatePropagation();

        if (window.pakeConfig?.new_window) {
          openAuthNavigation(
            originalWindowOpen,
            absoluteUrl,
            "_blank",
            "width=1200,height=800,scrollbars=yes,resizable=yes",
          );
        } else {
          window.location.href = absoluteUrl;
        }

        return;
      }

      // Handle _blank links: internal links stay in-app, external links open in the system browser
      if (target === "_blank") {
        if (forceInternalNavigation) {
          e.preventDefault();
          e.stopImmediatePropagation();
          window.location.href = absoluteUrl;
          return;
        }

        if (isInternalUrl(absoluteUrl)) {
          keepInternalNewTabLinkInApp(e, anchorElement, absoluteUrl);
          return;
        }

        e.preventDefault();
        e.stopImmediatePropagation();
        handleExternalLink(absoluteUrl);
        return;
      }

      if (target === "_new") {
        if (forceInternalNavigation) {
          e.preventDefault();
          e.stopImmediatePropagation();
          window.location.href = absoluteUrl;
          return;
        }

        // "_new" is one more name for a new tab: a link to the app's own
        // site stays in the app as a _blank one does, instead of leaving
        // for the system browser.
        if (isInternalUrl(absoluteUrl)) {
          keepInternalNewTabLinkInApp(e, anchorElement, absoluteUrl);
          return;
        }

        e.preventDefault();
        handleExternalLink(absoluteUrl);
        return;
      }

      // Process download links.
      if (isDownloadRequired(absoluteUrl, anchorElement, e)) {
        // Let the browser download blob:/data: URLs natively; the Rust
        // on_download handler saves them to the Downloads folder. Routing them
        // through the IPC fails on strict-CSP sites (e.g. Gemini), whose
        // connect-src blocks the IPC origin, and on downloads triggered from a
        // sandboxed iframe where the IPC can't be reached.
        if (isSpecialDownload(absoluteUrl)) {
          return;
        }
        e.preventDefault();
        e.stopImmediatePropagation();
        downloadFile(absoluteUrl, filename);
        return;
      }

      // Handle regular links: internal URLs allow normal navigation, external links open in the system browser
      if (!target || target === "_self") {
        // Optimization: Allow previewable media to be handled by the app/browser directly
        // This fixes issues where CDN links are treated as external
        if (isPreviewableMedia(absoluteUrl)) {
          return;
        }

        if (!isInternalUrl(absoluteUrl)) {
          if (forceInternalNavigation) {
            return;
          }

          e.preventDefault();
          e.stopImmediatePropagation();
          handleExternalLink(absoluteUrl);
        }
      }
    }
  };

  window.addEventListener("click", (event) =>
    handleProtocolLinkClick(event, handleExternalLink),
  );
  window.addEventListener("click", openUnhandledBlankLink);

  // Capture web links before site popup handlers route them into the app.
  document.addEventListener("click", detectAnchorElementClick, true);
  document.addEventListener("auxclick", openMiddleClickedLink, true);

  // Rewrite the window.open function.
  const originalWindowOpen = window.open;
  window.open = function (url, name, specs) {
    url = normalizePopupUrl(url);
    const normalizedUrl = normalizeAnchorHref(url);
    // A two-stage popup needs its own WindowProxy. Returning the main window
    // makes a later popup.location assignment navigate away from the app.
    if (/^about:blank(?:[?#]|$)/i.test(normalizedUrl)) {
      return originalWindowOpen.call(window, url, name, specs);
    }
    if (normalizedUrl.startsWith("#")) {
      window.location.href = new URL(normalizedUrl, window.location.href).href;
      return window;
    }

    if (shouldBypassPakeLinkHandling(url)) {
      return originalWindowOpen.call(window, url, name, specs);
    }

    // A sized sign-in popup, or a sized popup of the app's own site, answers
    // its opener and closes; it gets a real window on macOS and Windows.
    if (opensSignInPopups() && requestsPopupWindow(name, specs)) {
      let popupUrl = "";
      try {
        popupUrl = new URL(url, window.location.href).href;
      } catch (error) {
        popupUrl = "";
      }
      // WebView2 runs this script in subframes too, where the app's own site
      // is the configured one, not the frame's address.
      const ownSite = topWindow
        ? isInternalUrl(popupUrl)
        : matchesInternalUrl(
            popupUrl,
            window.pakeConfig?.url || window.location.href,
          );
      if (
        /^https?:/i.test(popupUrl) &&
        (window.isAuthPopup(popupUrl, name) ||
          (!window.pakeConfig?.new_window && ownSite))
      ) {
        // Straight to its address, as a browser opens it: the native handler
        // builds a sized popup under every setting. Opening it blank first
        // and then sending it there lost the opener on sites that set
        // Cross-Origin-Opener-Policy (X does): WebKit keeps a popup with its
        // opener across that policy only on the popup's first navigation.
        const popup = originalWindowOpen.call(window, popupUrl, name, specs);
        if (popup) return popup;
      }
    }

    // Every other sign-in window.open: no size, noopener, a _self target, a
    // popup the engine refused, and all of them on Linux. macOS and Linux
    // continue in the current window, Windows asks for a native popup first.
    if (window.isAuthPopup(url, name)) {
      try {
        const baseUrl = window.location.origin + window.location.pathname;
        const absoluteUrl = new URL(url, baseUrl).href;
        return openAuthNavigation(originalWindowOpen, absoluteUrl, name, specs);
      } catch (error) {
        return openAuthNavigation(originalWindowOpen, url, name, specs);
      }
    }

    try {
      const baseUrl = window.location.origin + window.location.pathname;
      const hrefUrl = new URL(url, baseUrl);
      const absoluteUrl = hrefUrl.href;

      if (!isInternalUrl(absoluteUrl)) {
        if (forceInternalNavigation) {
          return originalWindowOpen.call(window, absoluteUrl, name, specs);
        }

        handleExternalLink(absoluteUrl);
        return null;
      }

      // With --new-window the native handler opens an in-app window; without it,
      // originalWindowOpen would route the internal target to the system browser
      // and strand SSO callbacks, so navigate in place instead.
      if (!window.pakeConfig?.new_window) {
        window.location.href = absoluteUrl;
        return window;
      }

      return originalWindowOpen.call(window, absoluteUrl, name, specs);
    } catch (error) {
      return originalWindowOpen.call(window, url, name, specs);
    }
  };

  if (topWindow) {
    // The sender is untrusted even when it belongs to this webview. This bridge
    // may only open external links, never navigate the top page or create auth
    // windows on a sandboxed frame's behalf.
    openFrameLink = (url) => {
      if (
        forceInternalNavigation ||
        isInternalUrl(url) ||
        window.isAuthLink(url)
      ) {
        return;
      }
      handleExternalLink(url);
    };
    for (const { source, href } of pendingFrameLinks.splice(0)) {
      routeFrameLink(source, href);
    }

    // Set the default zoom, There are problems with Loop without using try-catch.
    try {
      setDefaultZoom();
    } catch (e) {
      console.log(e);
    }
  }

  // Fix Chinese input method "Enter" on Safari.
  // WebKit flags a keydown the input method consumed with keyCode 229, and the
  // Enter that confirms a candidate arrives after compositionend. keyCode 229
  // is needed here because isComposing can already be false on that keydown.
  // stopPropagation, not preventDefault, so the input method can still commit.
  // Only Enter is held back; other composing keys still reach editors.
  document.addEventListener(
    "keydown",
    (e) => {
      const isImeEnter = e.key === "Enter" && e.keyCode === 229;
      if (isImeEnter || e.key === "Process") e.stopPropagation();
    },
    true,
  );
});

// Bridge the Web Notification + Web Badging APIs to Pake's Rust commands so
// pages running inside the webview can drive the macOS dock badge (and
// taskbar badge on Linux/Windows). Installs synchronously instead of waiting
// for DOMContentLoaded so feature-detection on Notification/setAppBadge
// returns the polyfill before site scripts run.
(function () {
  if (!isTopWindow()) return;
  const invoke = window.__PAKE_NATIVE__?.core?.invoke;
  if (!invoke) return;
  if (typeof EventTarget !== "function" || typeof Event !== "function") return;

  let NotificationEventTarget = EventTarget;
  try {
    new EventTarget();
  } catch (_) {
    // Safari before 14 exposes EventTarget but its constructor throws. A
    // fragment already has native event state and keeps event.target exact.
    NotificationEventTarget = class extends EventTarget {
      constructor() {
        return Object.setPrototypeOf(
          document.createDocumentFragment(),
          new.target.prototype,
        );
      }
    };
  }

  let permVal = "granted";
  // Pages that drive the badge directly via setAppBadge own its lifecycle;
  // notifications-driven counts auto-clear on the next user interaction.
  let pageManagedBadge = false;
  let autoBadgeActive = false;

  const normalizeBadgeCount = (count) => {
    if (typeof count !== "number" || !Number.isFinite(count)) {
      throw new TypeError("Badge count must be a finite number.");
    }
    const normalized = Math.floor(count);
    return normalized > 0 ? Math.min(normalized, 99999) : null;
  };
  const setBadge = (count) => {
    pageManagedBadge = true;
    autoBadgeActive = false;
    return invoke("set_dock_badge", { count }).catch(() => {});
  };
  const clearBadge = () => invoke("clear_dock_badge").catch(() => {});
  const setLabel = (label) => {
    pageManagedBadge = true;
    autoBadgeActive = false;
    return invoke("set_dock_badge_label", { label }).catch(() => {});
  };
  const incrementAutoBadge = () => {
    if (pageManagedBadge) return Promise.resolve();
    autoBadgeActive = true;
    return invoke("increment_dock_badge").catch(() => {});
  };

  // Notification click routing.
  //
  // On macOS the native center reports which notification was clicked and calls
  // __pakeNotificationClick with its exact id (see app/notification.rs).
  // Elsewhere the platform tells us nothing, so we approximate: a window that
  // regains focus shortly after a notification arrived while it was in the
  // background is treated as a click on that notification. The approximation is
  // deliberately narrow -- one shot, time-limited, and cancelled by any in-page
  // interaction -- because it cannot tell a notification click apart from the
  // user switching back by hand.
  const FOCUS_CLICK_WINDOW_MS = 60000;
  const MAX_TRACKED_NOTIFICATIONS = 200;
  const liveNotifications = new Map();
  let notifSeq = 0;
  let pendingFocusClick = null;
  let interactionSeq = 0;

  const withdrawNotification = (id) =>
    invoke("close_notification", { id }).catch((error) => {
      console.warn("[Pake] Failed to withdraw notification:", error);
    });

  const forgetNotification = (id) => {
    liveNotifications.delete(id);
    if (pendingFocusClick?.id === id) pendingFocusClick = null;
  };

  const clickNotification = (id) => {
    const notif = liveNotifications.get(id);
    if (!notif) return;
    pendingFocusClick = null;
    notif.dispatchEvent(new Event("click"));
  };

  window.addEventListener("focus", () => {
    interactionSeq++;
    const pending = pendingFocusClick;
    pendingFocusClick = null;
    if (!pending || Date.now() - pending.at > FOCUS_CLICK_WINDOW_MS) return;
    clickNotification(pending.id);
  });

  const clearAutoBadge = () => {
    interactionSeq++;
    // A real interaction means the user is already reading the page, so a later
    // focus is an app switch rather than a notification click.
    pendingFocusClick = null;
    if (pageManagedBadge || !autoBadgeActive) return;
    autoBadgeActive = false;
    clearBadge();
  };
  document.addEventListener("click", clearAutoBadge, true);
  document.addEventListener("keydown", clearAutoBadge, true);

  // A real EventTarget, not a bare object with an onclick slot: pages commonly
  // register their routing with addEventListener("click"), and the click
  // handler needs event.target to be the notification it fired for.
  class PakeNotification extends NotificationEventTarget {
    constructor(title, options) {
      super();
      const opts = options || {};
      Object.defineProperty(this, "_handlers", {
        value: new Map(),
        enumerable: false,
      });

      this.title = title === undefined ? "" : String(title);
      this.body = opts.body ?? "";
      this.tag = opts.tag ?? "";
      this.data = opts.data ?? null;
      this.dir = opts.dir ?? "auto";
      this.lang = opts.lang ?? "";
      this.silent = opts.silent ?? false;
      this.requireInteraction = opts.requireInteraction ?? false;
      this.timestamp = opts.timestamp ?? Date.now();

      let icon = opts.icon || "";
      if (icon.startsWith("/")) {
        icon = window.location.origin + icon;
      }
      this.icon = icon;

      // Must match the id charset validated in app/notification.rs.
      const id = `pake-${++notifSeq}-${Math.random().toString(36).slice(2, 10)}`;
      Object.defineProperty(this, "_id", { value: id, enumerable: false });

      // A new notification with the same tag replaces the previous one, which
      // must therefore stop being a click target.
      if (this.tag) {
        for (const other of liveNotifications.values()) {
          if (other.tag === this.tag) other.close();
        }
      }
      liveNotifications.set(id, this);
      while (liveNotifications.size > MAX_TRACKED_NOTIFICATIONS) {
        liveNotifications.values().next().value.close();
      }

      const raisedInBackground =
        typeof document.hasFocus === "function" ? !document.hasFocus() : true;
      const raisedAt = Date.now();
      const raisedAfterInteraction = interactionSeq;
      const sequence = notifSeq;
      // Clear the older candidate immediately, rather than when this IPC reply
      // arrives. Replies and native delivery may complete out of order.
      pendingFocusClick = null;

      invoke("send_notification", {
        params: {
          id,
          title: this.title,
          body: this.body,
          icon: this.icon,
          silent: this.silent,
        },
      })
        .then((outcome) => {
          if (liveNotifications.get(id) !== this) {
            // close/replacement may precede native delivery. Withdraw again
            // after its acknowledgement, using this object's unique id.
            return withdrawNotification(id);
          }
          const unread = raisedAfterInteraction === interactionSeq;
          // Another window already raised this exact message, so nothing was
          // shown: no click can arrive, and counting it would multiply the
          // badge by the number of windows.
          if (outcome?.suppressed) {
            forgetNotification(id);
            // The dock badge is shared, and the window that raised the copy
            // counted it. Reading here must still clear it.
            if (unread && !pageManagedBadge) autoBadgeActive = true;
            return undefined;
          }
          if (
            unread &&
            sequence === notifSeq &&
            raisedInBackground &&
            !outcome?.nativeClick
          ) {
            pendingFocusClick = { id, at: raisedAt };
          }
          this.dispatchEvent(new Event("show"));
          if (unread) return incrementAutoBadge();
        })
        .catch(() => {
          if (liveNotifications.get(id) !== this) return;
          forgetNotification(id);
          this.dispatchEvent(new Event("error"));
        });
    }

    close() {
      if (liveNotifications.get(this._id) !== this) return;
      forgetNotification(this._id);
      withdrawNotification(this._id);
      // Notification events are tasks. A synchronous close handler can create
      // another same-tag notification while the constructor is replacing it.
      setTimeout(() => this.dispatchEvent(new Event("close")), 0);
    }
  }

  for (const type of ["click", "close", "show", "error"]) {
    Object.defineProperty(PakeNotification.prototype, `on${type}`, {
      configurable: true,
      enumerable: true,
      get() {
        return this._handlers.get(type) || null;
      },
      set(handler) {
        const previous = this._handlers.get(type);
        if (previous) this.removeEventListener(type, previous);
        if (typeof handler === "function") {
          this._handlers.set(type, handler);
          this.addEventListener(type, handler);
        } else {
          this._handlers.delete(type);
        }
      },
    });
  }

  PakeNotification.requestPermission = (callback) => {
    if (typeof callback === "function") callback(permVal);
    return Promise.resolve(permVal);
  };
  Object.defineProperty(PakeNotification, "permission", {
    enumerable: true,
    configurable: true,
    get: () => permVal,
    set: (v) => {
      permVal = v;
    },
  });

  try {
    Object.defineProperty(window, "Notification", {
      configurable: true,
      writable: true,
      value: PakeNotification,
    });
  } catch (_) {}

  try {
    Object.defineProperty(window, "__pakeNotificationClick", {
      configurable: true,
      writable: true,
      value: clickNotification,
    });
  } catch (_) {}

  // Web Badging API: https://wicg.github.io/badging/
  // setAppBadge() with no argument shows an indicator dot; with a number,
  // shows the count (0 clears). clearAppBadge() removes the badge entirely.
  const setAppBadge = (count) => {
    if (count === undefined) return setLabel("•");
    let normalized;
    try {
      normalized = normalizeBadgeCount(count);
    } catch (error) {
      return Promise.reject(error);
    }
    if (normalized === null) {
      pageManagedBadge = false;
      autoBadgeActive = false;
      return clearBadge();
    }
    return setBadge(normalized);
  };
  const clearAppBadge = () => {
    pageManagedBadge = false;
    autoBadgeActive = false;
    return clearBadge();
  };
  try {
    Object.defineProperty(navigator, "setAppBadge", {
      configurable: true,
      writable: true,
      value: setAppBadge,
    });
    Object.defineProperty(navigator, "clearAppBadge", {
      configurable: true,
      writable: true,
      value: clearAppBadge,
    });
  } catch (_) {}
})();

function setDefaultZoom() {
  let htmlZoom = null;
  try {
    htmlZoom = window.localStorage.getItem("htmlZoom");
  } catch {}
  if (htmlZoom) {
    setZoom(htmlZoom);
  } else if (window.pakeConfig?.zoom && window.pakeConfig.zoom !== 100) {
    setZoom(`${window.pakeConfig.zoom}%`);
  }
}

// Browsers decode the last URL path segment when naming a download. Keep the
// encoded form when decoding fails or yields a path separator, a character
// Windows rejects in file names, or a control/format character.
function decodeFilenameSegment(segment) {
  try {
    const decoded = decodeURIComponent(segment);
    return /[\\/:*?"<>|\p{Cc}\p{Cf}]/u.test(decoded) ? segment : decoded;
  } catch (e) {
    return segment;
  }
}

function getFilenameFromUrl(url) {
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-");

  if (typeof url === "string" && url.startsWith("data:")) {
    // Read only the MIME type: stop at ';' (params) or ',' (data), whichever
    // comes first, so the encoding or payload never leaks into the extension.
    const semicolon = url.indexOf(";");
    const comma = url.indexOf(",");
    let end = url.length;
    if (semicolon !== -1) end = Math.min(end, semicolon);
    if (comma !== -1) end = Math.min(end, comma);
    const mime = url.substring(5, end).toLowerCase();
    if (mime.startsWith("image/")) {
      let ext = mime.substring(6).split("+")[0] || "png";
      if (ext === "jpeg") ext = "jpg";
      return `image-${timestamp}.${ext}`;
    }
    const subtype = mime.includes("/") ? mime.split("/")[1].split("+")[0] : "";
    const dataExtMap = {
      pdf: "pdf",
      zip: "zip",
      csv: "csv",
      json: "json",
      plain: "txt",
      xml: "xml",
      html: "html",
    };
    const mapped = dataExtMap[subtype];
    return mapped ? `download-${timestamp}.${mapped}` : `download-${timestamp}`;
  }

  try {
    const parsedUrl = new URL(url);
    const urlPath = parsedUrl.pathname;
    const rawSegment = decodeFilenameSegment(
      urlPath.substring(urlPath.lastIndexOf("/") + 1),
    ).trim();
    const segment = rawSegment === "." || rawSegment === ".." ? "" : rawSegment;

    if (segment && segment.includes(".") && !segment.startsWith(".")) {
      return segment;
    }

    // Leave extensionless link downloads without a fake .png suffix so the
    // Rust download handler can apply Content-Disposition or Content-Type.
    return segment || `download-${timestamp}`;
  } catch (e) {
    return `download-${timestamp}`;
  }
}