// ==UserScript== // @name Steam 愿望单区域比价 // @namespace http://tampermonkey.net/ // @version 2026.12.02.123 // @description 对比 Steam 愿望单各区现价,显示 ITAD Steam 本区历史最低价 // @author kuusei // @icon https://store.steampowered.com/favicon.ico // @match https://store.steampowered.com/wishlist* // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant unsafeWindow // @connect open.er-api.com // @connect api.isthereanydeal.com // @connect shared.akamai.steamstatic.com // @license MIT // @homepageURL https://script.kuusei.moe // @run-at document-idle // ==/UserScript== /* modern-screenshot 4.7.0 https://github.com/qq15725/modern-screenshot MIT License Copyright (c) 2021-present wxm Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. qrcode-generator 2.0.4 https://github.com/kazuhikoarase/qrcode-generator MIT License Copyright (c) 2009 Kazuhiko Arase Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ "use strict"; (() => { // src/shared/dom/style.ts var injectedStyleIds = /* @__PURE__ */ new Set(); function injectStyle(id, cssText) { if (injectedStyleIds.has(id) || document.getElementById(id)) { injectedStyleIds.add(id); return; } const style = document.createElement("style"); style.id = id; style.textContent = cssText; document.head.appendChild(style); injectedStyleIds.add(id); } // src/shared/dom/ready.ts function whenDocumentReady(fn) { if (document.readyState === "complete" || document.readyState === "interactive") { window.setTimeout(fn, 0); return; } document.addEventListener("DOMContentLoaded", fn, { once: true }); } function startPolling(fn, intervalMs, options) { if (options?.immediate ?? true) { void fn(); } return window.setInterval(() => { void fn(); }, intervalMs); } // src/shared/net/gm-request.ts var hasGmRequest = () => typeof GM_xmlhttpRequest === "function"; function gmRequest(options) { return new Promise((resolve, reject) => { GM_xmlhttpRequest({ ...options, onload: resolve, onerror: reject }); }); } async function fetchRequest(options) { const response = await fetch(options.url, { method: options.method ?? "GET", headers: options.headers, body: options.data }); const responseText = await response.text(); return { status: response.status, responseText, ok: response.ok }; } async function request(options) { if (hasGmRequest()) { return gmRequest(options); } const response = await fetchRequest(options); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } return response; } // src/shared/ui/apple-material.ts var STYLE_ID = "tm-shared-apple-material"; var APPLE_MATERIAL_CSS = ` :root { --tm-apple-font: -apple-system, BlinkMacSystemFont, "SF Pro Text", "PingFang SC", "Helvetica Neue", sans-serif; --tm-apple-blue: #0a84ff; --tm-apple-green: #30d158; --tm-apple-red: #ff453a; --tm-apple-label: rgba(255, 255, 255, 0.92); --tm-apple-secondary-label: #8e8e93; --tm-apple-tertiary-label: #aeaeb2; --tm-apple-glass-bg: rgba(44, 44, 46, 0.72); --tm-apple-glass-bg-strong: rgba(28, 28, 30, 0.75); --tm-apple-glass-bg-hover: rgba(58, 58, 60, 0.82); --tm-apple-glass-solid: #2c2c2e; --tm-apple-hairline: rgba(255, 255, 255, 0.08); --tm-apple-highlight: rgba(255, 255, 255, 0.28); --tm-apple-ease: cubic-bezier(0.32, 0.72, 0, 1); --tm-apple-ease-out: cubic-bezier(0.16, 1, 0.3, 1); } .tm-apple-glass { background: var(--tm-apple-glass-bg); color: var(--tm-apple-label); font-family: var(--tm-apple-font); backdrop-filter: blur(20px) saturate(180%); -webkit-backdrop-filter: blur(20px) saturate(180%); box-shadow: inset 0 0.5px 0 var(--tm-apple-highlight), 0 10px 30px rgba(0, 0, 0, 0.25); } .tm-apple-glass[data-active="true"], .tm-apple-glass--active { background: rgba(10, 132, 255, 0.78); } @media (prefers-reduced-transparency: reduce) { .tm-apple-glass { backdrop-filter: none; -webkit-backdrop-filter: none; background: var(--tm-apple-glass-solid); } .tm-apple-glass[data-active="true"], .tm-apple-glass--active { background: var(--tm-apple-blue); } } `; function ensureAppleMaterial() { injectStyle(STYLE_ID, APPLE_MATERIAL_CSS); } // src/shared/ui/hud.ts var CONTAINER_ID = "sync-pipeline-container"; var HUD_STYLE = ` #sync-pipeline-container { position: fixed; top: 24px; right: 24px; z-index: 2147483647; width: 280px; display: flex; flex-direction: column; gap: 12px; font-family: var(--tm-apple-font); pointer-events: none; } .sync-hud-card { background: var(--tm-apple-glass-bg-strong); backdrop-filter: blur(20px) saturate(180%); -webkit-backdrop-filter: blur(20px) saturate(180%); border: 1px solid var(--tm-apple-hairline); border-radius: 12px; padding: 14px 16px; box-shadow: inset 0 0.5px 0 var(--tm-apple-highlight), 0 10px 30px rgba(0, 0, 0, 0.25); color: #e5e5ea; font-size: 13px; font-weight: 400; letter-spacing: -0.1px; pointer-events: auto; transition: all 0.4s var(--tm-apple-ease-out); opacity: 0; transform: translateY(-10px) scale(0.98); } .sync-hud-card.visible { opacity: 1; transform: translateY(0) scale(1); } .sync-hud-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; } .sync-hud-title { font-weight: 500; color: #fff; } .sync-hud-status { font-size: 11px; color: var(--tm-apple-secondary-label); font-variant-numeric: tabular-nums; } .sync-hud-body { color: var(--tm-apple-tertiary-label); font-size: 12px; word-break: break-all; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sync-hud-progress-wrap { background: rgba(255, 255, 255, 0.1); width: 100%; height: 3px; border-radius: 1.5px; margin-top: 10px; overflow: hidden; display: none; } .sync-hud-progress-bar { background: var(--tm-apple-blue); height: 100%; width: 0%; transition: width 0.3s var(--tm-apple-ease); } .sync-hud-card.success { border-top: 2px solid var(--tm-apple-green); } .sync-hud-card.error { border-top: 2px solid var(--tm-apple-red); } .sync-hud-card.success .sync-hud-progress-bar { background: var(--tm-apple-green); } .sync-hud-card.error .sync-hud-progress-bar { background: var(--tm-apple-red); } @media (prefers-reduced-transparency: reduce) { .sync-hud-card { backdrop-filter: none; -webkit-backdrop-filter: none; background: var(--tm-apple-glass-solid); } } `; function ensureContainer() { ensureAppleMaterial(); injectStyle("tm-shared-hud-style", HUD_STYLE); let container = document.getElementById(CONTAINER_ID); if (!container) { container = document.createElement("div"); container.id = CONTAINER_ID; document.body.appendChild(container); } return container; } var HudCard = class { constructor(title, message) { const container = ensureContainer(); this.card = document.createElement("div"); this.card.className = "sync-hud-card"; const header = document.createElement("div"); header.className = "sync-hud-header"; const titleEl = document.createElement("span"); titleEl.className = "sync-hud-title"; titleEl.textContent = title; this.statusEl = document.createElement("span"); this.statusEl.className = "sync-hud-status"; this.statusEl.textContent = "进行中"; header.append(titleEl, this.statusEl); this.bodyEl = document.createElement("div"); this.bodyEl.className = "sync-hud-body"; this.bodyEl.textContent = message; this.progressWrapEl = document.createElement("div"); this.progressWrapEl.className = "sync-hud-progress-wrap"; this.progressBarEl = document.createElement("div"); this.progressBarEl.className = "sync-hud-progress-bar"; this.progressWrapEl.appendChild(this.progressBarEl); this.card.append(header, this.bodyEl, this.progressWrapEl); container.appendChild(this.card); window.requestAnimationFrame(() => { this.card.classList.add("visible"); }); } update(message, statusText, type = "") { this.bodyEl.innerText = message; if (statusText !== void 0) { this.statusEl.innerText = statusText; } this.card.classList.remove("success", "error"); if (type) { this.card.classList.add(type); } } setRequestCount(done, total) { if (total <= 0 && done <= 0) { this.statusEl.innerText = "缓存"; return; } this.statusEl.innerText = `${done}/${total}`; } setProgress(percent) { this.progressWrapEl.style.display = "block"; this.progressBarEl.style.width = `${percent}%`; } dismiss(delay = 3e3) { window.setTimeout(() => { this.card.style.opacity = "0"; this.card.style.transform = "translateY(10px) scale(0.95)"; window.setTimeout(() => this.card.remove(), 400); }, delay); } }; // src/shared/utils/storage.ts var hasGmStorage = () => typeof GM_getValue === "function" && typeof GM_setValue === "function"; function loadValue(key, fallback) { if (hasGmStorage()) { return GM_getValue(key, fallback); } try { const raw = localStorage.getItem(key); if (raw == null) { return fallback; } return JSON.parse(raw); } catch { return fallback; } } function saveValue(key, value) { if (hasGmStorage()) { GM_setValue(key, value); return; } localStorage.setItem(key, JSON.stringify(value)); } function loadTimedValue(key, options) { const cached = loadValue(key, null); if (!cached) { return null; } if (cached.version !== options.version) { return null; } if (Date.now() - cached.timestamp > options.ttlMs) { return null; } return cached.value; } function saveTimedValue(key, value, version) { saveValue(key, { version, timestamp: Date.now(), value }); } // src/shared/utils/time.ts function sleep(ms) { return new Promise((resolve) => { window.setTimeout(resolve, ms); }); } // src/scripts/steam-wishlist-prices/config.ts var CACHE_TTL_MS = 24 * 60 * 60 * 1e3; var WISHLIST_CACHE_TTL_MS = 60 * 60 * 1e3; var WISHLIST_STORE_PAGE_SIZE = 1e3; var WISHLIST_STORE_FILL_MAX = 2e3; var GIFT_BAND_STRICT = 0.1; var GIFT_BAND_LOOSE = 0.15; var FX_CHEAP_BAND = 0.01; var COUNTRIES = [ { code: "CN", label: "中国", group: "base" }, { code: "TW", label: "台湾", group: "base" }, { code: "HK", label: "香港", group: "base" }, { code: "SG", label: "新加坡", group: "base" }, { code: "JP", label: "日本", group: "base" }, { code: "US", label: "美国", group: "base" }, { code: "PK", label: "南亚", group: "low" }, { code: "IN", label: "印度", group: "low" }, { code: "ID", label: "印尼", group: "low" }, { code: "PH", label: "菲律宾", group: "low" }, { code: "VN", label: "越南", group: "low" }, { code: "TR", label: "土耳其", group: "low" }, { code: "UA", label: "乌克兰", group: "low" }, { code: "KZ", label: "哈萨克斯坦", group: "low" }, { code: "AZ", label: "独联体美元区", group: "low" }, { code: "RU", label: "俄罗斯", group: "low" }, { code: "AR", label: "阿根廷", group: "low" } ]; // src/scripts/steam-wishlist-prices/cache/cache.ts var VERSION = "v5"; var cacheGet = (key, ttlMs) => loadTimedValue(key, { version: VERSION, ttlMs }); var cachePeek = (key) => { const cached = loadValue(key, null); if (!cached || cached.version !== VERSION) { return null; } return cached.value; }; var cacheSet = (key, value) => saveTimedValue(key, value, VERSION); var cacheExpire = (key) => { const cached = loadValue(key, null); if (cached?.version === VERSION) saveValue(key, { ...cached, timestamp: 0 }); }; var cacheUpdate = (key, update) => { const cached = loadValue(key, null); if (!cached || cached.version !== VERSION) return; const value = update(cached.value); if (value !== cached.value) saveValue(key, { ...cached, value }); }; var wishlistCacheKey = (steamId2, home, viewer = null) => `wl-list:v3:${viewer ?? "public"}:${steamId2}:${home}`; var fxCacheKey = "wl-fx"; var priceCacheKey = (country) => `wl-price:v4:${country}`; var LIST_TTL_MS = WISHLIST_CACHE_TTL_MS; var PRICE_TTL_MS = WISHLIST_CACHE_TTL_MS; var FX_TTL_MS = CACHE_TTL_MS; // src/scripts/steam-wishlist-prices/requests/request-meter.ts var requestHook = null; var setRequestHook = (hook) => { requestHook = hook; }; var noteRequest = () => { requestHook?.(); }; var logWishlist = (event, data) => { const pageConsole = typeof unsafeWindow === "undefined" ? console : unsafeWindow.console; pageConsole.info(`[steam-wishlist-prices] ${event}`, data ?? {}); }; var createRequestMeter = (onChange) => { let done = 0; let total = 0; const emit = () => onChange(done, total); return { get done() { return done; }, get total() { return total; }, bump() { done += 1; if (done > total) { total = done; } emit(); }, setTotal(next) { total = Math.max(next, done); emit(); } }; }; // src/scripts/steam-wishlist-prices/requests/request-queue.ts var MAX_ACTIVE_PER_HOST = 3; var queues = /* @__PURE__ */ new Map(); var queueApiRequest = (url, send) => { const hostname = new URL(url).hostname; let queue = queues.get(hostname); if (!queue) { queue = { active: 0, waiting: [] }; queues.set(hostname, queue); } const host = queue; return new Promise((resolve, reject) => { const start = async () => { host.active += 1; try { resolve(await send()); } catch (error) { reject(error); } finally { host.active -= 1; const next = host.waiting.shift(); if (next) next(); else if (host.active === 0) queues.delete(hostname); } }; if (host.active < MAX_ACTIVE_PER_HOST) void start(); else host.waiting.push(start); }); }; // src/scripts/steam-wishlist-prices/pricing/currency-rates.ts var FX_URL = "https://open.er-api.com/v6/latest/USD"; var loadUsdRates = async () => { const cached = cacheGet(fxCacheKey, FX_TTL_MS); if (cached) { return cached; } const data = await queueApiRequest(FX_URL, async () => { noteRequest(); logWishlist("汇率请求", { method: "GET /v6/latest/USD" }); try { const response = await request({ url: FX_URL }); if (response.status < 200 || response.status >= 300) throw new Error(`HTTP ${response.status}`); const data2 = JSON.parse(response.responseText); logWishlist("汇率响应数据", { http: response.status, currencies: Object.keys(data2.rates ?? {}).length, usdToCny: data2.rates?.CNY }); return data2; } catch { logWishlist("汇率请求失败"); throw new Error("汇率请求失败"); } }); if (data.result !== "success" || !data.rates?.CNY) { throw new Error("FX response missing CNY rate"); } const rates = { fetchedAt: (/* @__PURE__ */ new Date()).toISOString(), usdTo: data.rates }; cacheSet(fxCacheKey, rates); return rates; }; var toCny = (amount, currency, rates) => { const code = currency.toUpperCase(); if (code === "CNY") { return amount; } const usdToCny = rates.usdTo.CNY; const usdToSource = code === "USD" ? 1 : rates.usdTo[code]; if (!usdToCny || !usdToSource) { return null; } return amount / usdToSource * usdToCny; }; // src/scripts/steam-wishlist-prices/steam/steam-id.ts var STEAM_ID_RE = /^7656119\d{10}$/; var steamId = (value) => typeof value === "string" && STEAM_ID_RE.test(value) ? value : null; var parseJson = (text) => { try { return text ? JSON.parse(text) : void 0; } catch { return void 0; } }; var pageText; var pageData; var storePage = () => { const text = globalThis.document?.getElementById("valve-ssr-data")?.textContent; if (text !== pageText) { pageText = text; pageData = parseJson(text); } return pageData; }; var loaderData = () => { const page = typeof unsafeWindow === "undefined" ? globalThis.window : unsafeWindow; return page?.SSR?.loaderData ?? storePage()?.loaderData ?? []; }; var headerText; var headerData; var storeHeader = () => { const text = loaderData()[0]; if (text !== headerText) { headerText = text; headerData = parseJson(text); } return headerData; }; var loggedInSteamId = () => { const headerId = storeHeader()?.steamid; if (headerId !== void 0) return steamId(headerId); const user = storePage()?.UserConfig; return user?.logged_in ? steamId(user.steamid) : null; }; var wishlistPageCountry = () => storeHeader()?.storeBrowseContext?.country || storePage()?.UserConfig?.country_code || "US"; var resolveSteamId = () => { const pathname = location.pathname; const fromUrl = steamId(pathname.match(/^\/wishlist\/profiles\/(\d+)(?:\/|$)/)?.[1]); if (fromUrl) return fromUrl; if (/^\/wishlist(?:\/|$)/.test(pathname)) { for (const entry of loaderData()) { const data = parseJson(entry); const owner = data?.filters && steamId(data.steamid); if (owner) return owner; } } const account = /^\/wishlist\/?$/.test(pathname) && loggedInSteamId(); if (account) return account; throw new Error("当前页找不到 Steam ID,请打开愿望单页面后再试"); }; // src/scripts/steam-wishlist-prices/cache/wishlist-cache.ts var parseWishlistCount = (text) => { const match = text.trim().match(/^([\d,,]+)\s*(?:个项目|個項目|items?)$/i); if (!match) return null; const count = Number(match[1].replace(/[,,]/g, "")); return Number.isSafeInteger(count) && count >= 0 ? count : null; }; var readWishlistPageCount = (root = document) => { const counts = /* @__PURE__ */ new Set(); for (const element of Array.from(root.querySelectorAll("div, span, p, label"))) { const count = parseWishlistCount(element.textContent ?? ""); if (count !== null) counts.add(count); } return counts.size === 1 ? [...counts][0] : null; }; var wishlistCacheState = (steamId2, home, pageCount, viewer = null) => { const key = wishlistCacheKey(steamId2, home, viewer); const games = cachePeek(key); const fresh2 = cacheGet(key, LIST_TTL_MS); const changed = pageCount !== null && games !== null && pageCount !== games.length; return { games: fresh2 ?? games, refresh: !fresh2 || changed }; }; var ownedWishlistCacheKeys = (steamId2) => COUNTRIES.flatMap(({ code }) => [wishlistCacheKey(steamId2, code, steamId2), wishlistCacheKey(steamId2, code)]); var expireCachedWishlist = (steamId2) => { for (const key of ownedWishlistCacheKeys(steamId2)) cacheExpire(key); }; var removeCachedWishlistGame = (steamId2, appid) => { for (const key of ownedWishlistCacheKeys(steamId2)) { cacheUpdate(key, (games) => games.some((game) => game.appid === appid) ? games.filter((game) => game.appid !== appid) : games); } }; // src/scripts/steam-wishlist-prices/requests/estimate-opening.ts var storePages = (count) => Math.max(1, Math.ceil(Math.max(count, 1) / WISHLIST_STORE_FILL_MAX)); var fxRequestPending = () => !cacheGet(fxCacheKey, FX_TTL_MS); var estimateOpeningRequests = (steamId2, home, pageCount = null, knownAppids = false, shared = false) => { let n = 0; const state = wishlistCacheState(steamId2, home, pageCount, loggedInSteamId()); if (shared || state.refresh) { const size = pageCount ?? state.games?.length ?? 0; n += (knownAppids || shared ? 0 : 1) + storePages(size); } if (fxRequestPending()) n += 1; return n; }; // src/scripts/steam-wishlist-prices/ui/report.generated.css var cssChunks = [ "/*! tailwindcss v4.3.5 | MIT License | https://tailwindcss.com */", "@layer properties;", "@layer theme, base, components, utilities;", "@layer theme {", " :root, :host {", ' --font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue",', ' "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji",', ' "Segoe UI Symbol", "Noto Color Emoji";', ' --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono",', ' "Courier New", monospace;', " --spacing: 0.25rem;", " --text-xs: 0.75rem;", " --text-xs--line-height: calc(1 / 0.75);", " --text-sm: 0.875rem;", " --text-sm--line-height: calc(1.25 / 0.875);", " --text-xl: 1.25rem;", " --text-xl--line-height: calc(1.75 / 1.25);", " --font-weight-normal: 400;", " --font-weight-medium: 500;", " --font-weight-semibold: 600;", " --font-weight-bold: 700;", " --radius-lg: 0.5rem;", " --radius-xl: 0.75rem;", " --default-transition-duration: 150ms;", " --default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);", " --default-font-family: var(--font-sans);", " --default-mono-font-family: var(--font-mono);", " --color-paper: #1b2838;", " --color-line: #2a475e;", " --color-ink: #c7d5e0;", " --color-muted: #8f98a0;", " --color-cheap: #a4d007;", " --color-near: #66c0f4;", " --color-cream: #2a475e;", " --color-gift: #a4d007;", " --color-chip: #2a475e;", " --color-surface: #16202d;", " --color-menu: #3d4450;", " }", "}", "@layer base {", " *, ::after, ::before, ::backdrop, ::file-selector-button {", " box-sizing: border-box;", " margin: 0;", " padding: 0;", " border: 0 solid;", " }", " html, :host {", " line-height: 1.5;", " -webkit-text-size-adjust: 100%;", " tab-size: 4;", ' font-family: var(--default-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");', " font-feature-settings: var(--default-font-feature-settings, normal);", " font-variation-settings: var(--default-font-variation-settings, normal);", " -webkit-tap-highlight-color: transparent;", " }", " hr {", " height: 0;", " color: inherit;", " border-top-width: 1px;", " }", " abbr:where([title]) {", " -webkit-text-decoration: underline dotted;", " text-decoration: underline dotted;", " }", " h1, h2, h3, h4, h5, h6 {", " font-size: inherit;", " font-weight: inherit;", " }", " a {", " color: inherit;", " -webkit-text-decoration: inherit;", " text-decoration: inherit;", " }", " b, strong {", " font-weight: bolder;", " }", " code, kbd, samp, pre {", ' font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);', " font-feature-settings: var(--default-mono-font-feature-settings, normal);", " font-variation-settings: var(--default-mono-font-variation-settings, normal);", " font-size: 1em;", " }", " small {", " font-size: 80%;", " }", " sub, sup {", " font-size: 75%;", " line-height: 0;", " position: relative;", " vertical-align: baseline;", " }", " sub {", " bottom: -0.25em;", " }", " sup {", " top: -0.5em;", " }", " table {", " text-indent: 0;", " border-color: inherit;", " border-collapse: collapse;", " }", " :-moz-focusring:where(:not(iframe)) {", " outline: auto;", " }", " progress {", " vertical-align: baseline;", " }", " summary {", " display: list-item;", " }", " ol, ul, menu {", " list-style: none;", " }", " img, svg, video, canvas, audio, iframe, embed, object {", " display: block;", " vertical-align: middle;", " }", " img, video {", " max-width: 100%;", " height: auto;", " }", " button, input, select, optgroup, textarea, ::file-selector-button {", " font: inherit;", " font-feature-settings: inherit;", " font-variation-settings: inherit;", " letter-spacing: inherit;", " color: inherit;", " border-radius: 0;", " background-color: transparent;", " opacity: 1;", " }", " :where(select:is([multiple], [size])) optgroup {", " font-weight: bolder;", " }", " :where(select:is([multiple], [size])) optgroup option {", " padding-inline-start: 20px;", " }", " ::file-selector-button {", " margin-inline-end: 4px;", " }", " ::placeholder {", " opacity: 1;", " }", " @supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {", " ::placeholder {", " color: currentcolor;", " @supports (color: color-mix(in lab, red, red)) {", " color: color-mix(in oklab, currentcolor 50%, transparent);", " }", " }", " }", " textarea {", " resize: vertical;", " }", " ::-webkit-search-decoration {", " -webkit-appearance: none;", " }", " ::-webkit-date-and-time-value {", " min-height: 1lh;", " text-align: inherit;", " }", " ::-webkit-datetime-edit {", " display: inline-flex;", " }", " ::-webkit-datetime-edit-fields-wrapper {", " padding: 0;", " }", " ::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {", " padding-block: 0;", " }", " ::-webkit-calendar-picker-indicator {", " line-height: 1;", " }", " :-moz-ui-invalid {", " box-shadow: none;", " }", ' button, input:where([type="button"], [type="reset"], [type="submit"]), ::file-selector-button {', " appearance: button;", " }", " ::-webkit-inner-spin-button, ::-webkit-outer-spin-button {", " height: auto;", " }", ' [hidden]:where(:not([hidden="until-found"])) {', " display: none !important;", " }", "}", "@layer utilities {", " .collapse {", " visibility: collapse;", " }", " .visible {", " visibility: visible;", " }", " .absolute {", " position: absolute;", " }", " .fixed {", " position: fixed;", " }", " .relative {", " position: relative;", " }", " .inset-0 {", " inset: 0px;", " }", " .top-full {", " top: 100%;", " }", " .left-0 {", " left: 0px;", " }", " .z-40 {", " z-index: 40;", " }", " .z-\\[2147483646\\] {", " z-index: 2147483646;", " }", " .container {", " width: 100%;", " @media (width >= 40rem) {", " max-width: 40rem;", " }", " @media (width >= 48rem) {", " max-width: 48rem;", " }", " @media (width >= 64rem) {", " max-width: 64rem;", " }", " @media (width >= 80rem) {", " max-width: 80rem;", " }", " @media (width >= 96rem) {", " max-width: 96rem;", " }", " }", " .mt-1 {", " margin-top: var(--spacing);", " }", " .mt-1\\.5 {", " margin-top: calc(var(--spacing) * 1.5);", " }", " .mt-2 {", " margin-top: calc(var(--spacing) * 2);", " }", " .ml-auto {", " margin-left: auto;", " }", " .block {", " display: block;", " }", " .contents {", " display: contents;", " }", " .flex {", " display: flex;", " }", " .grid {", " display: grid;", " }", " .hidden {", " display: none;", " }", " .inline {", " display: inline;", " }", " .inline-flex {", " display: inline-flex;", " }", " .table {", " display: table;", " }", " .size-3 {", " width: calc(var(--spacing) * 3);", " height: calc(var(--spacing) * 3);", " }", " .size-3\\.5 {", " width: calc(var(--spacing) * 3.5);", " height: calc(var(--spacing) * 3.5);", " }", " .h-5 {", " height: calc(var(--spacing) * 5);", " }", " .h-7 {", " height: calc(var(--spacing) * 7);", " }", " .h-full {", " height: 100%;", " }", " .max-h-72 {", " max-height: calc(var(--spacing) * 72);", " }", " .min-h-0 {", " min-height: 0px;", " }", " .w-40 {", " width: calc(var(--spacing) * 40);", " }", " .w-52 {", " width: calc(var(--spacing) * 52);", " }", " .w-64 {", " width: calc(var(--spacing) * 64);", " }", " .w-72 {", " width: calc(var(--spacing) * 72);", " }", " .w-full {", " width: 100%;", " }", " .w-max {", " width: max-content;", " }", " .min-w-0 {", " min-width: 0px;", " }", " .flex-1 {", " flex: 1;", " }", " .shrink-0 {", " flex-shrink: 0;", " }", " .transform {", " transform: var(--tw-rotate-x, ) var(--tw-rotate-y, ) var(--tw-rotate-z, ) var(--tw-skew-x, ) var(--tw-skew-y, );", " }", " .cursor-help {", " cursor: help;", " }", " .cursor-pointer {", " cursor: pointer;", " }", " .resize {", " resize: both;", " }", " .flex-col {", " flex-direction: column;", " }", " .flex-wrap {", " flex-wrap: wrap;", " }", " .items-center {", " align-items: center;", " }", " .justify-between {", " justify-content: space-between;", " }", " .gap-1 {", " gap: var(--spacing);", " }", " .gap-1\\.5 {", " gap: calc(var(--spacing) * 1.5);", " }", " .gap-2 {", " gap: calc(var(--spacing) * 2);", " }", " .gap-3 {", " gap: calc(var(--spacing) * 3);", " }", " .gap-x-1\\.5 {", " column-gap: calc(var(--spacing) * 1.5);", " }", " .gap-x-3 {", " column-gap: calc(var(--spacing) * 3);", " }", " .gap-y-1 {", " row-gap: var(--spacing);", " }", " .overflow-auto {", " overflow: auto;", " }", " .overflow-hidden {", " overflow: hidden;", " }", " .rounded {", " border-radius: 0.25rem;", " }", " .rounded-full {", " border-radius: calc(infinity * 1px);", " }", " .rounded-lg {", " border-radius: var(--radius-lg);", " }", " .rounded-xl {", " border-radius: var(--radius-xl);", " }", " .border {", " border-style: var(--tw-border-style);", " border-width: 1px;", " }", " .border-b {", " border-bottom-style: var(--tw-border-style);", " border-bottom-width: 1px;", " }", " .border-l {", " border-left-style: var(--tw-border-style);", " border-left-width: 1px;", " }", " .border-dotted {", " --tw-border-style: dotted;", " border-style: dotted;", " }", " .border-gift {", " border-color: var(--color-gift);", " }", " .border-line {", " border-color: var(--color-line);", " }", " .border-muted {", " border-color: var(--color-muted);", " }", " .bg-chip {", " background-color: var(--color-chip);", " }", " .bg-cream {", " background-color: var(--color-cream);", " }", " .bg-paper {", " background-color: var(--color-paper);", " }", " .bg-surface {", " background-color: var(--color-surface);", " }", " .p-2 {", " padding: calc(var(--spacing) * 2);", " }", " .p-3 {", " padding: calc(var(--spacing) * 3);", " }", " .px-1\\.5 {", " padding-inline: calc(var(--spacing) * 1.5);", " }", " .px-2 {", " padding-inline: calc(var(--spacing) * 2);", " }", " .px-5 {", " padding-inline: calc(var(--spacing) * 5);", " }", " .py-1\\.5 {", " padding-block: calc(var(--spacing) * 1.5);", " }", " .py-4 {", " padding-block: calc(var(--spacing) * 4);", " }", " .py-16 {", " padding-block: calc(var(--spacing) * 16);", " }", " .text-center {", " text-align: center;", " }", " .text-left {", " text-align: left;", " }", " .align-middle {", " vertical-align: middle;", " }", " .text-sm {", " font-size: var(--text-sm);", " line-height: var(--tw-leading, var(--text-sm--line-height));", " }", " .text-xl {", " font-size: var(--text-xl);", " line-height: var(--tw-leading, var(--text-xl--line-height));", " }", " .text-xs {", " font-size: var(--text-xs);", " line-height: var(--tw-leading, var(--text-xs--line-height));", " }", " .text-\\[11px\\] {", " font-size: 11px;", " }", " .leading-none {", " --tw-leading: 1;", " line-height: 1;", " }", " .font-bold {", " --tw-font-weight: var(--font-weight-bold);", " font-weight: var(--font-weight-bold);", " }", " .font-medium {", " --tw-font-weight: var(--font-weight-medium);", " font-weight: var(--font-weight-medium);", " }", " .font-normal {", " --tw-font-weight: var(--font-weight-normal);", " font-weight: var(--font-weight-normal);", " }", " .font-semibold {", " --tw-font-weight: var(--font-weight-semibold);", " font-weight: var(--font-weight-semibold);", " }", " .whitespace-nowrap {", " white-space: nowrap;", " }", " .text-cheap {", " color: var(--color-cheap);", " }", " .text-gift {", " color: var(--color-gift);", " }", " .text-ink {", " color: var(--color-ink);", " }", " .text-muted {", " color: var(--color-muted);", " }", " .text-near {", " color: var(--color-near);", " }", " .uppercase {", " text-transform: uppercase;", " }", " .tabular-nums {", " --tw-numeric-spacing: tabular-nums;", " font-variant-numeric: var(--tw-ordinal, ) var(--tw-slashed-zero, ) var(--tw-numeric-figure, ) var(--tw-numeric-spacing, ) var(--tw-numeric-fraction, );", " }", " .antialiased {", " -webkit-font-smoothing: antialiased;", " -moz-osx-font-smoothing: grayscale;", " }", " .accent-cheap {", " accent-color: var(--color-cheap);", " }", " .accent-near {", " accent-color: var(--color-near);", " }", " .shadow {", " --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));", " box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);", " }", " .shadow-xl {", " --tw-shadow: 0 20px 25px -5px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 8px 10px -6px var(--tw-shadow-color, rgb(0 0 0 / 0.1));", " box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);", " }", " .outline {", " outline-style: var(--tw-outline-style);", " outline-width: 1px;", " }", " .blur {", " --tw-blur: blur(8px);", " filter: var(--tw-blur, ) var(--tw-brightness, ) var(--tw-contrast, ) var(--tw-grayscale, ) var(--tw-hue-rotate, ) var(--tw-invert, ) var(--tw-saturate, ) var(--tw-sepia, ) var(--tw-drop-shadow, );", " }", " .filter {", " filter: var(--tw-blur, ) var(--tw-brightness, ) var(--tw-contrast, ) var(--tw-grayscale, ) var(--tw-hue-rotate, ) var(--tw-invert, ) var(--tw-saturate, ) var(--tw-sepia, ) var(--tw-drop-shadow, );", " }", " .backdrop-filter {", " -webkit-backdrop-filter: var(--tw-backdrop-blur, ) var(--tw-backdrop-brightness, ) var(--tw-backdrop-contrast, ) var(--tw-backdrop-grayscale, ) var(--tw-backdrop-hue-rotate, ) var(--tw-backdrop-invert, ) var(--tw-backdrop-opacity, ) var(--tw-backdrop-saturate, ) var(--tw-backdrop-sepia, );", " backdrop-filter: var(--tw-backdrop-blur, ) var(--tw-backdrop-brightness, ) var(--tw-backdrop-contrast, ) var(--tw-backdrop-grayscale, ) var(--tw-backdrop-hue-rotate, ) var(--tw-backdrop-invert, ) var(--tw-backdrop-opacity, ) var(--tw-backdrop-saturate, ) var(--tw-backdrop-sepia, );", " }", " .transition {", " transition-property: color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to, opacity, box-shadow, transform, translate, scale, rotate, filter, -webkit-backdrop-filter, backdrop-filter, display, content-visibility, overlay, pointer-events;", " transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));", " transition-duration: var(--tw-duration, var(--default-transition-duration));", " }", " .\\[build\\:css\\] {", " build: css;", " }", " .\\[build\\:index\\] {", " build: index;", " }", " .\\[build\\:meta\\] {", " build: meta;", " }", " .\\[build\\:user\\] {", " build: user;", " }", " .\\[watch\\:user\\] {", " watch: user;", " }", " @media (hover: hover) {", " .hover\\:bg-cream:hover {", " background-color: var(--color-cream);", " }", " .hover\\:text-ink:hover {", " color: var(--color-ink);", " }", " }", " .has-\\[\\:checked\\]\\:bg-cream:has(:is(:checked)) {", " background-color: var(--color-cream);", " }", "}", "@layer components {", " .wl-shot-trigger {", " position: absolute;", " right: 28px;", " bottom: 24px;", " z-index: 1;", " box-shadow: 0 2px 8px rgba(0, 0, 0, .35);", " }", " .wl-dialog-backdrop.wl-shot-modal {", " z-index: 80;", " }", " .wl-shot-dialog {", " --wl-dialog-width: 380px;", " }", " .wl-shot-presets {", " display: grid;", " grid-template-columns: repeat(2, minmax(0, 1fr));", " gap: 8px;", " margin: 16px 0;", " padding: 0;", " border: 0;", " }", " .wl-shot-presets legend {", " margin-bottom: 8px;", " color: #dbe7f2;", " font-size: 13px;", " }", " .wl-shot-dialog .wl-setup-switch-row + .wl-setup-switch-row {", " margin-top: 8px;", " }", " .wl-shot-error {", " margin: 12px 0 0;", " color: #ff9b8a;", " font-size: 12px;", " line-height: 1.6;", " overflow-wrap: anywhere;", " }", " .wl-shot-error:empty {", " display: none;", " }", " .wl-shot-note {", " margin: 12px 0 0;", " color: #a8bbca;", " font-size: 12px;", " line-height: 1.6;", " }", " .wl-shot-stage {", " position: fixed;", " top: 0;", " left: -100000px;", " pointer-events: none;", " }", " .wl-shot-document {", " box-sizing: border-box;", " padding: 24px;", " background: #1b2838;", " color: #c7d5e0;", ' font: 14px/1.5 "Motiva Sans", Arial, "Microsoft YaHei", sans-serif;', " }", " .wl-shot-document * {", " box-sizing: border-box;", " }", " .wl-shot-heading, .wl-shot-intro {", " border: 1px solid #355066;", " border-radius: 8px;", " overflow-wrap: anywhere;", " }", " .wl-shot-heading {", " margin-bottom: 16px;", " padding: 20px 24px 16px;", " background: linear-gradient(115deg, #2a475e, #16202d 80%);", " box-shadow: inset 0 3px #66c0f4;", " }", " .wl-shot-heading h1 {", " margin: 0 0 12px;", " color: #fff;", " font-size: 28px;", " font-weight: 700;", " line-height: 1.25;", " }", " .wl-shot-heading-main {", " display: flex;", " justify-content: space-between;", " align-items: center;", " gap: 16px;", " }", " .wl-shot-copy {", " min-width: 0;", " }", " .wl-shot-qr {", " display: block;", " flex: none;", " }", " .wl-shot-regions, .wl-shot-meta {", " display: flex;", " flex-wrap: wrap;", " align-items: center;", " gap: 8px 16px;", " }", " .wl-shot-regions span {", " min-width: 0;", " max-width: 100%;", " padding: 4px 9px;", " border: 1px solid #3b5e77;", " border-radius: 4px;", " background: #1b2838;", " color: #e1edf5;", " font-size: 12px;", " word-break: keep-all;", " }", " .wl-shot-regions strong {", " color: #8ed1fa;", " font-weight: 600;", " }", " .wl-shot-meta {", " justify-content: space-between;", " margin-top: 14px;", " padding-top: 12px;", " box-shadow: inset 0 1px #355066;", " }", " .wl-shot-meta p {", " min-width: 0;", " margin: 0;", " }", " .wl-shot-meta p:first-child {", " color: #e1edf5;", " font-weight: 600;", " }", " .wl-shot-meta p:last-child {", " color: #a8bbca;", " font-size: 12px;", " }", " .wl-shot-list {", " display: flex;", " flex-direction: column;", " gap: 8px;", " }", " .wl-shot-document .wl-row {", " margin: 0;", " }", " .wl-shot-document .wl-row:hover {", " background: rgba(0, 0, 0, .2);", " }", " .wl-shot-document .wl-title {", " overflow-wrap: anywhere;", " }", " .wl-shot-document .wl-row-stats {", " display: block;", " }", " .wl-shot-document .wl-row-stats > span {", " margin-right: 10px;", " }", " .wl-shot-document .wl-disc {", " max-width: 100%;", " flex-wrap: wrap;", " }", " .wl-shot-document .wl-disc-prices {", " white-space: normal;", " }", " .wl-shot-document .wl-disc-price-line {", " flex-wrap: wrap;", " overflow-wrap: anywhere;", " }", " .wl-shot-document .wl-game-tag {", " cursor: default;", " }", " .wl-shot-intro {", " margin-top: 16px;", " padding: 12px 16px;", " background: #16202d;", " box-shadow: inset 3px 0 #66c0f4;", " }", " .wl-shot-intro p {", " margin: 0;", " color: #e1edf5;", " font-weight: 600;", " }", " .wl-shot-intro a {", " display: inline-block;", " max-width: 100%;", " margin-top: 6px;", " padding: 5px 9px;", " border-radius: 4px;", " background: #1a3548;", " color: #8ed1fa;", " font-size: 12px;", " text-decoration: none;", " }", " .wl-shot-document.is-mobile {", " padding: 16px;", " }", " .wl-shot-document.is-mobile .wl-shot-heading {", " padding: 16px;", " }", " .wl-shot-document.is-mobile .wl-shot-heading h1 {", " font-size: 23px;", " }", " .wl-shot-document.is-mobile .wl-shot-meta {", " flex-direction: column;", " align-items: flex-start;", " }", " .wl-shot-document.is-mobile .wl-row {", " flex-direction: column;", " gap: 10px;", " padding: 12px;", " }", " .wl-shot-document.is-mobile .wl-cap {", " width: 184px;", " height: 69px;", " }", " .wl-tags-menu {", " position: absolute;", " left: 0;", " top: 100%;", " z-index: 45;", " width: min(320px, calc(100vw - 48px));", " margin-top: 8px;", " padding: 12px;", " border-radius: 4px;", " }", " .wl-tag-input {", " width: 100%;", " min-width: 0;", " height: 34px;", " padding: 6px 10px;", " border: 1px solid #355066;", " border-radius: 3px;", " background: #101c28;", " color: #e1edf5;", " font-size: 13px;", " }", " .wl-tag-input:focus-visible {", " outline: 2px solid #66c0f4;", " outline-offset: 1px;", " }", " .wl-tags-options {", " max-height: 240px;", " overflow: auto;", " margin: 8px 0;", " }", " .wl-tag-option {", " display: flex;", " align-items: center;", " gap: 8px;", " width: 100%;", " min-height: 34px;", " padding: 6px 8px;", " border: 0;", " border-radius: 3px;", " background: transparent;", " color: #e1edf5;", " text-align: left;", " font-size: 13px;", " cursor: pointer;", " overflow-wrap: anywhere;", " }", " .wl-tag-option.is-on {", " color: #bce6ff;", " }", " .wl-tag-filter-row {", " display: flex;", " align-items: stretch;", " gap: 4px;", " margin-bottom: 2px;", " border-radius: 3px;", " }", " .wl-tag-filter-row:hover, .wl-tag-filter-row:focus-within {", " background: #263e50;", " }", " .wl-tag-filter-row:has(.wl-tag-option.is-on) {", " background: #214c65;", " }", " .wl-tag-filter-row:has(.wl-tag-option.is-on):hover {", " background: #28556f;", " }", " .wl-tag-filter-row .wl-tag-option {", " flex: 1;", " min-width: 0;", " padding: 0 8px 0 0;", " }", " .wl-tag-exclude, .wl-tag-check {", " display: flex;", " align-items: center;", " justify-content: center;", " flex: none;", " width: 28px;", " min-height: 34px;", " color: #66c0f4;", " }", " .wl-tag-exclude {", " border: 0;", " border-radius: 3px;", " background: transparent;", " padding: 0;", " cursor: pointer;", " }", " .wl-tag-exclude:hover {", " color: #ffd1c9;", " }", " .wl-tag-filter-row.is-excluded {", " background: #493037;", " }", " .wl-tag-filter-row.is-excluded:hover, .wl-tag-filter-row:hover:has(.wl-tag-exclude:hover), .wl-tag-filter-row:has(.wl-tag-exclude:focus-visible) {", " background: #55343c;", " }", " .wl-tag-filter-row.is-excluded .wl-tag-option {", " color: #ffd1c9;", " }", ' .wl-tag-exclude[aria-pressed="true"] {', " color: #ffe0d9;", " }", " .wl-tag-exclude svg, .wl-tag-check svg {", " width: 16px;", " height: 16px;", " flex: none;", " }", " .wl-tag-count {", " margin-left: auto;", " color: #a8bbca;", " font-size: 12px;", " }", " .wl-tags-message {", " margin: 8px 0;", " color: #c7d5e0;", " font-size: 12px;", " line-height: 1.6;", " overflow-wrap: anywhere;", " }", " #tags-message:empty {", " display: none;", " }", " .wl-tags-actions {", " display: flex;", " flex-wrap: wrap;", " gap: 8px;", " padding-top: 8px;", " border-top: 1px solid #355066;", " }", " .wl-tag-action, .wl-tag-edit {", " border: 0;", " background: transparent;", " color: #8ed1fa;", " font-size: 12px;", " cursor: pointer;", " padding: 4px 6px;", " }", " .wl-tag-action:hover, .wl-tag-edit:hover {", " color: #fff;", " background: #2a475e;", " }", " .wl-row-tags {", " display: flex;", " flex-wrap: wrap;", " align-items: center;", " gap: 6px;", " margin: 5px 0 8px;", " }", " .wl-game-tag {", " border: 1px solid #3b5e77;", " border-radius: 3px;", " background: #1a3548;", " color: #c9e9fb;", " padding: 2px 7px;", " font-size: 11px;", " line-height: 1.6;", " cursor: pointer;", " overflow-wrap: anywhere;", " max-width: 100%;", " }", " .wl-game-tag:hover {", " background: #2a536d;", " border-color: #66c0f4;", " }", " .wl-tag-dialog {", " --wl-dialog-width: 520px;", " }", " .wl-tag-editor-section + .wl-dialog-input, .wl-dialog-input + .wl-tag-editor-section {", " margin-top: 12px;", " }", " .wl-tag-editor-section h3 {", " color: #bcc9d6;", " font-size: 12px;", " margin-bottom: 8px;", " }", " .wl-tag-chips {", " display: flex;", " flex-wrap: wrap;", " align-items: flex-start;", " gap: 5px;", " max-height: 180px;", " overflow: auto;", " }", " .wl-tag-chip {", " max-width: 100%;", " padding: 4px 8px;", " border: 1px solid #355066;", " border-radius: 5px;", " background: var(--color-surface);", " color: var(--color-ink);", " font-size: 12px;", " line-height: 1.4;", " overflow-wrap: anywhere;", " text-align: left;", " cursor: pointer;", " }", " .wl-tag-chip:hover {", " background: #203447;", " border-color: #466a87;", " }", " .wl-tag-chip.is-selected {", " background: rgba(38, 86, 120, .55);", " border-color: #4d94c4;", " color: #ecf7ff;", " }", " .wl-tag-chip:focus-visible {", " outline: 2px solid var(--color-near);", " outline-offset: -2px;", " }", " .wl-tag-chip.is-selected:hover {", " background: #543b42;", " border-color: #ab7b83;", " }", " .wl-tag-chip.is-selected span {", " padding-left: 5px;", " color: #b8c9d7;", " }", " .wl-tag-empty {", " margin: 0;", " color: #aebdcd;", " font-size: 12px;", " line-height: 1.8;", " }", " .wl-tag-create-choice {", " margin-top: 8px;", " border-style: dashed;", " color: #a8d6ef;", " }", " .wl-tag-rename {", " display: flex;", " align-items: center;", " gap: 8px;", " }", " .wl-tag-rename + .wl-tag-rename {", " margin-top: 8px;", " }", " .wl-tag-rename button {", " flex: none;", " }", " .wl-tag-dialog #tag-dialog-message:empty {", " display: none;", " }", " .tip {", " position: relative;", " }", " .tip-box {", " display: none;", " max-width: calc(100vw - 48px);", " padding: 8px 12px;", " border: 1px solid #4a7591;", " border-radius: 4px;", " background: #101c28;", " color: #e1edf5;", " font-size: 12px;", " font-weight: 400;", " line-height: 1.65;", " text-align: left;", " white-space: normal;", " box-shadow: 0 8px 24px rgba(0, 0, 0, 0.6);", " }", " .tip:hover .tip-box, .tip:focus-visible .tip-box, .tip:has(:focus-visible) > .tip-box {", " display: block;", " }", " .wl-overlay {", " color-scheme: dark;", " background: rgba(0, 0, 0, 0.75);", ' font-family: "Motiva Sans", Arial, Helvetica, sans-serif;', " }", " .wl-overlay ::-webkit-scrollbar {", " width: 6px;", " height: 6px;", " }", " .wl-overlay ::-webkit-scrollbar-button {", " display: none;", " width: 0;", " height: 0;", " }", " .wl-overlay ::-webkit-scrollbar-track, .wl-overlay ::-webkit-scrollbar-corner {", " background: transparent;", " }", " .wl-overlay ::-webkit-scrollbar-thumb {", " border-radius: 999px;", " background: rgba(102, 192, 244, 0.28);", " }", " .wl-overlay ::-webkit-scrollbar-thumb:hover {", " background: rgba(102, 192, 244, 0.48);", " }", " .wl-overlay ::-webkit-scrollbar-thumb:active {", " background: rgba(102, 192, 244, 0.65);", " }", " @supports not selector(::-webkit-scrollbar) {", " .wl-overlay, .wl-overlay * {", " scrollbar-width: thin;", " scrollbar-color: rgba(102, 192, 244, 0.32) transparent;", " }", " }", " .wl-chrome {", " display: flex;", " justify-content: flex-end;", " margin-bottom: 8px;", " }", " .wl-close {", " display: inline-flex;", " align-items: center;", " justify-content: center;", " width: 32px;", " height: 32px;", " padding: 0;", " border: 1px solid #355066;", " border-radius: 5px;", " background: var(--color-surface);", " color: var(--color-ink);", " cursor: pointer;", " transition: background 120ms, border-color 120ms, color 120ms;", " }", " .wl-close:hover {", " background: #24394b;", " border-color: #4d708a;", " color: #fff;", " }", " .wl-close:focus-visible {", " outline: 2px solid var(--color-near);", " outline-offset: 2px;", " }", " .wl-close svg {", " width: 16px;", " height: 16px;", " }", " .rounded-xl, .rounded-lg, .rounded-2xl {", " border-radius: 2px;", " }", " #q:focus {", " border-color: #66c0f4;", " }", " .wl-toolbar {", " display: grid;", " flex: none;", " grid-template-columns: minmax(0, 1fr) auto;", " align-items: start;", " gap: 10px 16px;", " padding: 12px 20px;", " border-bottom: 1px solid var(--color-line);", " background: var(--color-paper);", " }", " .wl-toolbar-controls {", " display: flex;", " min-width: 0;", " flex-wrap: wrap;", " align-items: center;", " gap: 10px;", " }", " .wl-toolbar-search, .wl-toolbar-button {", " height: 34px;", " border: 1px solid #355066;", " border-radius: 4px;", " background: var(--color-surface);", " color: var(--color-ink);", " font-size: 13px;", " }", " .wl-toolbar-search {", " width: 220px;", " min-width: 140px;", " padding: 0 12px;", " outline: none;", " }", " .wl-toolbar-search::placeholder {", " color: var(--color-muted);", " }", " .wl-toolbar-button {", " display: inline-flex;", " align-items: center;", " justify-content: center;", " gap: 7px;", " padding: 0 11px;", " white-space: nowrap;", " cursor: pointer;", " }", " .wl-toolbar-button:hover {", " background: #24394b;", " border-color: #4d708a;", " }", " .wl-toolbar-button:focus-visible {", " outline: 2px solid var(--color-near);", " outline-offset: 2px;", " }", " .wl-header-action {", " color: var(--color-near);", " font-size: 12px;", " font-weight: 400;", " text-decoration: underline;", " text-underline-offset: 2px;", " cursor: pointer;", " }", " .wl-header-action:hover {", " color: #9ad8fb;", " }", " .wl-header-action:focus-visible {", " outline: 2px solid var(--color-near);", " outline-offset: 2px;", " }", " .wl-icon-button {", " display: inline-flex;", " flex: none;", " align-items: center;", " justify-content: center;", " width: 44px;", " height: 44px;", " padding: 0;", " border: 1px solid #355066;", " border-radius: 4px;", " background: var(--color-surface);", " color: var(--color-ink);", " cursor: pointer;", " }", " .wl-icon-button > svg {", " width: 22px;", " height: 22px;", " }", " .wl-icon-button:hover {", " background: #24394b;", " border-color: #4d708a;", " color: #fff;", " }", " .wl-icon-button:focus-visible {", " outline: 2px solid var(--color-near);", " outline-offset: 2px;", " }", " .wl-toolbar-sort {", " flex: none;", " }", " .wl-sort-controls {", " display: flex;", " overflow: hidden;", " border: 1px solid #355066;", " border-radius: 4px;", " }", " .wl-sort-controls > button {", " border: 0;", " border-radius: 0;", " height: 32px;", " }", " .wl-sort-controls > button + button {", " border-left: 1px solid #355066;", " }", " .wl-report-metrics {", " display: grid;", " grid-template-columns: repeat(4, minmax(0, max-content));", " justify-self: end;", " max-width: 100%;", " gap: 5px;", " margin: 0;", " }", " .wl-report-metric {", " min-width: 0;", " padding: 4px 7px;", " border: 1px solid #314b61;", " border-left: 2px solid #526c80;", " border-radius: 4px;", " background: #162331;", " }", ' .wl-report-metric[data-metric="current"] {', " border-left-color: #66c0f4;", " }", ' .wl-report-metric[data-metric="history"] {', " border-left-color: #a4d007;", " background: #202d29;", " }", " .wl-report-metric dt {", " color: #a8bbca;", " font-size: 10px;", " line-height: 13px;", " }", " .wl-report-metric-value {", " margin: 0;", " color: #e1edf5;", " font-size: 13px;", " font-weight: 600;", " line-height: 16px;", " font-variant-numeric: tabular-nums;", " overflow-wrap: anywhere;", " }", " .wl-report-metric-value span, .wl-report-metric-detail {", " color: #a8bbca;", " font-size: 10px;", " font-weight: normal;", " }", " .wl-report-metric-detail {", " margin: 0;", " line-height: 12px;", " }", ' [data-metric="current"] > .wl-report-metric-value {', " color: #8ed1fa;", " }", ' [data-metric="history"] > .wl-report-metric-value {', " color: #c3de81;", " }", " .wl-toolbar-filters {", " display: flex;", " flex-basis: 100%;", " flex-wrap: wrap;", " align-items: center;", " gap: 8px;", " }", " .wl-filter-toggle {", " position: relative;", " display: inline-flex;", " cursor: pointer;", " }", " .wl-filter-option {", " display: inline-flex;", " }", " .wl-filter-tip-box {", " position: absolute;", " left: 0;", " top: calc(100% + 6px);", " z-index: 40;", " width: min(288px, calc(100vw - 48px));", " }", " .wl-filter-toggle > input {", " position: absolute;", " width: 1px;", " height: 1px;", " padding: 0;", " margin: -1px;", " overflow: hidden;", " clip-path: inset(50%);", " white-space: nowrap;", " }", " .wl-filter-face {", " display: flex;", " align-items: center;", " gap: 6px;", " height: 32px;", " padding: 0 12px;", " border: 1px solid #355066;", " border-radius: 4px;", " background: var(--color-surface);", " color: #aabccc;", " font-size: 13px;", " white-space: nowrap;", " transition: color 120ms, background 120ms, border-color 120ms;", " }", " .wl-filter-face > svg {", " width: 14px;", " height: 14px;", " flex: none;", " color: #738b9d;", " }", " .wl-filter-option.tip .wl-filter-face > span {", " text-decoration-line: underline;", " text-decoration-style: dotted;", " text-decoration-thickness: 1px;", " text-underline-offset: 4px;", " }", " .wl-filter-check {", " display: none;", " }", " .wl-filter-toggle:hover > .wl-filter-face {", " background: #24394b;", " color: #e1edf5;", " }", " .wl-filter-toggle > input:checked + .wl-filter-face {", " background: #224b65;", " border-color: #4a8bb3;", " color: #b4e2ff;", " }", " .wl-filter-toggle > input:checked + .wl-filter-face > svg {", " color: #8fd3ff;", " }", " .wl-filter-toggle > input:checked + .wl-filter-face .wl-filter-add {", " display: none;", " }", " .wl-filter-toggle > input:checked + .wl-filter-face .wl-filter-check {", " display: block;", " }", " .wl-filter-toggle > input:focus-visible + .wl-filter-face {", " outline: 2px solid var(--color-near);", " outline-offset: -2px;", " }", " .wl-price-filters {", " position: relative;", " display: inline-flex;", " flex: none;", " border: 1px solid #355066;", " border-radius: 4px;", " }", " .wl-price-filters .wl-filter-face {", " height: 30px;", " border: 0;", " border-radius: 0;", " }", " .wl-price-filters > .wl-filter-option {", " position: static;", " }", " .wl-price-filters > .wl-filter-option + .wl-filter-option {", " border-left: 1px solid #355066;", " }", " .wl-price-filters > .wl-filter-option:first-child .wl-filter-face {", " border-radius: 3px 0 0 3px;", " }", " .wl-price-filters > .wl-filter-option:last-child .wl-filter-face {", " border-radius: 0 3px 3px 0;", " }", " .wl-price-filters > .wl-filter-option:only-child .wl-filter-face {", " border-radius: 3px;", " }", ' .wl-opt > input[type="checkbox"], #fxCheap {', " appearance: none;", " flex: none;", " width: 14px;", " height: 14px;", " border: 1px solid #6a8294;", " border-radius: 3px;", " background: #16202d;", " cursor: pointer;", " }", ' .wl-opt > input[type="checkbox"]:checked, #fxCheap:checked {', " border-color: var(--color-near);", ` background: #66c0f4 url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='m3.5 8 3 3 6-6' fill='none' stroke='%2316202d' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / 12px no-repeat;`, " }", " .wl-opt > input:focus-visible, #fxCheap:focus-visible {", " outline: 2px solid var(--color-near);", " outline-offset: 2px;", " }", " .wl-opt > input:disabled {", " opacity: 0.5;", " cursor: default;", " }", " @media (max-width: 900px) {", " .wl-toolbar {", " grid-template-columns: minmax(0, 1fr);", " }", " }", " @media (max-width: 640px) {", " .wl-toolbar {", " padding: 12px;", " gap: 8px;", " }", " .wl-toolbar-controls {", " gap: 8px;", " }", " .wl-toolbar-search {", " width: 100%;", " }", " .wl-toolbar-filters {", " gap: 6px;", " }", " .wl-filter-face {", " padding: 0 10px;", " }", " }", " @media (max-width: 375px) {", " .wl-report-metrics {", " grid-template-columns: repeat(2, minmax(0, max-content));", " }", " }", " .wl-pop {", " background: var(--color-menu);", " border: 0;", " box-shadow: 0 8px 24px rgba(0, 0, 0, 0.55);", " }", " .wl-opt {", " border-radius: 0;", " color: var(--color-ink);", " }", " .wl-opt.is-on, .wl-opt:has(:checked) {", " background: transparent;", " color: #67c1f5;", " }", " .wl-opt:hover {", " background: #2a475e;", " }", " .wl-dialog-backdrop, .wl-dialog::backdrop {", " background: rgba(0, 0, 0, .75);", " }", " .wl-dialog-backdrop {", " position: fixed;", " inset: 0;", " z-index: 60;", " display: flex;", " align-items: center;", " justify-content: center;", " }", " .wl-dialog {", " width: min(var(--wl-dialog-width, 460px), calc(100vw - 32px));", " max-height: min(640px, calc(100dvh - 32px));", " overflow-x: hidden;", " overflow-y: auto;", " padding: 16px 18px 18px;", " border: 1px solid #314a60;", " border-top-color: #4e8aac;", " border-radius: 12px;", " background: linear-gradient(165deg, #213040 0%, #17222f 100%);", " color: var(--color-ink);", " box-shadow: 0 20px 50px rgba(0, 0, 0, 0.75);", " }", " .wl-dialog-header {", " display: flex;", " align-items: center;", " justify-content: space-between;", " gap: 12px;", " padding-bottom: 12px;", " border-bottom: 1px solid rgba(102, 192, 244, 0.14);", " }", " .wl-dialog-title {", " margin: 0;", " font-size: 16px;", " font-weight: 600;", " color: #f0f6fc;", " line-height: 1.3;", " overflow-wrap: anywhere;", " }", " .wl-dialog-close {", " display: inline-flex;", " flex: none;", " align-items: center;", " justify-content: center;", " width: 28px;", " height: 28px;", " padding: 0;", " border: 0;", " border-radius: 5px;", " background: transparent;", " color: #8f98a0;", " cursor: pointer;", " transition: background 120ms, color 120ms;", " }", " .wl-dialog-close:hover:not(:disabled) {", " background: rgba(102, 192, 244, 0.14);", " color: #e5edf5;", " }", " .wl-dialog-close:focus-visible {", " outline: 2px solid var(--color-near);", " outline-offset: 1px;", " }", " .wl-dialog-close svg {", " width: 16px;", " height: 16px;", " }", " .wl-dialog-body {", " padding-top: 14px;", " }", " .wl-dialog-footer {", " display: flex;", " flex-wrap: wrap;", " justify-content: flex-end;", " gap: 8px;", " margin-top: 16px;", " padding-top: 12px;", " border-top: 1px solid rgba(102, 192, 244, .14);", " }", " .wl-dialog-button {", " min-height: 38px;", " padding: 6px 12px;", " border: 1px solid #355066;", " border-radius: 5px;", " background: var(--color-surface);", " color: var(--color-ink);", " font-size: 13px;", " cursor: pointer;", " }", " .wl-dialog-button:hover:not(:disabled) {", " filter: brightness(1.16);", " }", " .wl-dialog-button:focus-visible {", " outline: 2px solid var(--color-near);", " outline-offset: 2px;", " }", " .wl-dialog-button.is-primary {", " border-color: transparent;", " background: linear-gradient(90deg, #4dabf3 0%, #2a7de1 100%);", " color: #fff;", " font-weight: 600;", " }", " .wl-dialog-button.is-danger {", " border-color: #a66164;", " background: #664149;", " color: #ffe0d9;", " }", " .wl-dialog :is(button, .wl-dialog-input):disabled {", " opacity: .55;", " cursor: not-allowed;", " }", " .wl-transfer-dialog {", " --wl-dialog-width: 540px;", " margin: auto;", " }", " .wl-transfer {", " display: grid;", " gap: 14px;", " }", " .wl-transfer form {", " display: grid;", " gap: 8px;", " }", " .wl-transfer .wl-dialog-button {", " justify-self: start;", " }", " .wl-transfer textarea.wl-dialog-input {", " height: auto;", " padding: 8px 10px;", " resize: vertical;", " }", " .wl-transfer #wl-transfer-export {", " height: min(320px, 45dvh);", " }", " .wl-transfer-prompt {", " padding: 8px 10px;", " border: 1px solid #355066;", " border-radius: 5px;", " background: var(--color-surface);", " }", " .wl-transfer-prompt summary {", " color: var(--color-near);", " font-size: 13px;", " cursor: pointer;", " }", " .wl-transfer-prompt[open] > :not(summary) {", " margin-top: 8px;", " }", " .wl-transfer-status {", " white-space: pre-wrap;", " overflow-wrap: anywhere;", " }", " .wl-transfer-status:empty {", " display: none;", " }", " .wl-setup-section {", " margin-top: 16px;", " }", " .wl-setup-section-head {", " display: flex;", " align-items: baseline;", " justify-content: space-between;", " gap: 8px;", " margin-bottom: 8px;", " }", " .wl-setup-label {", " margin: 0;", " font-size: 13px;", " font-weight: 600;", " color: #dbe7f2;", " line-height: 1.4;", " }", " .wl-setup-hint {", " margin: 0;", " font-size: 12px;", " color: #8fa3b5;", " font-variant-numeric: tabular-nums;", " }", " .wl-setup-hint.is-over {", " color: #ff9b8a;", " }", " .wl-setup-grid {", " display: grid;", " grid-template-columns: repeat(3, minmax(0, 1fr));", " gap: 6px;", " }", " @media (max-width: 480px) {", " .wl-setup-grid {", " grid-template-columns: repeat(2, minmax(0, 1fr));", " }", " }", " .wl-setup-chip {", " position: relative;", " display: flex;", " align-items: center;", " justify-content: space-between;", " gap: 6px;", " min-height: 34px;", " padding: 5px 10px;", " border: 1px solid #2b4257;", " border-radius: 5px;", " background: rgba(16, 26, 38, 0.65);", " color: #b8c7d4;", " font-size: 13px;", " line-height: 1.25;", " cursor: pointer;", " user-select: none;", " transition: border-color 120ms, background 120ms, color 120ms;", " }", " .wl-setup-chip > input {", " position: absolute;", " width: 1px;", " height: 1px;", " margin: -1px;", " padding: 0;", " overflow: hidden;", " clip-path: inset(50%);", " }", " .wl-setup-chip-text {", " min-width: 0;", " overflow: hidden;", " text-overflow: ellipsis;", " white-space: nowrap;", " }", " .wl-setup-chip:hover:not(:has(:disabled)) {", " border-color: #466a87;", " background: #203447;", " color: #e5edf5;", " }", " .wl-setup-chip:has(:checked) {", " border-color: #4d94c4;", " background: rgba(38, 86, 120, 0.55);", " color: #ecf7ff;", " font-weight: 500;", " }", " .wl-setup-chip:has(:focus-visible) {", " outline: 2px solid var(--color-near);", " outline-offset: 1px;", " }", " .wl-setup-chip:has(input:checked:disabled) {", " cursor: default;", " border-color: #3d7399;", " background: rgba(34, 73, 102, 0.42);", " }", " .wl-setup-chip:has(input:not(:checked):disabled) {", " opacity: 0.38;", " cursor: not-allowed;", " }", " .wl-setup-dot {", " flex: none;", " width: 8px;", " height: 8px;", " border: 1.5px solid #5a748a;", " border-radius: 999px;", " background: transparent;", " transition: border-color 120ms, background 120ms, box-shadow 120ms;", " }", " .wl-setup-chip:has(:checked) .wl-setup-dot {", " border-color: #66c0f4;", " background: #66c0f4;", " box-shadow: 0 0 6px rgba(102, 192, 244, 0.6);", " }", " .wl-setup-check {", " flex: none;", " display: inline-flex;", " align-items: center;", " justify-content: center;", " width: 14px;", " height: 14px;", " border: 1px solid #526b80;", " border-radius: 3px;", " background: rgba(12, 20, 29, 0.6);", " color: transparent;", " transition: border-color 120ms, background 120ms, color 120ms;", " }", " .wl-setup-check svg {", " width: 10px;", " height: 10px;", " }", " .wl-setup-chip:has(:checked) .wl-setup-check {", " border-color: #66c0f4;", " background: #66c0f4;", " color: #13202d;", " }", " .wl-setup-prefs {", " display: flex;", " flex-direction: column;", " gap: 14px;", " padding-top: 14px;", " border-top: 1px solid rgba(102, 192, 244, 0.14);", " }", " .wl-setup-field {", " display: flex;", " flex-direction: column;", " gap: 6px;", " }", " .wl-dialog-input {", " height: 34px;", " width: 100%;", " min-width: 0;", " padding: 0 10px;", " border: 1px solid #355066;", " border-radius: 5px;", " background: #101a26;", " color: #e5edf5;", " font-size: 13px;", " outline: none;", " transition: border-color 120ms, box-shadow 120ms;", " }", " .wl-dialog-input:focus {", " border-color: #66c0f4;", " box-shadow: 0 0 0 2px rgba(102, 192, 244, 0.18);", " }", " .wl-setup-desc {", " margin: 0;", " font-size: 12px;", " line-height: 1.5;", " color: #8fa3b5;", " }", " .wl-setup-link {", " color: #66c0f4;", " text-decoration: underline;", " text-underline-offset: 2px;", " }", " .wl-setup-link:hover {", " color: #9ad8fb;", " }", " .wl-setup-switch-row {", " position: relative;", " display: flex;", " align-items: center;", " justify-content: space-between;", " gap: 12px;", " padding: 10px 12px;", " border: 1px solid #2b4257;", " border-radius: 6px;", " background: rgba(16, 26, 38, 0.55);", " cursor: pointer;", " transition: border-color 120ms, background 120ms;", " }", " .wl-setup-switch-row:hover {", " border-color: #436582;", " background: rgba(24, 38, 54, 0.75);", " }", " .wl-setup-switch-input {", " position: absolute;", " width: 1px;", " height: 1px;", " margin: -1px;", " padding: 0;", " overflow: hidden;", " clip-path: inset(50%);", " }", " .wl-setup-switch {", " position: relative;", " display: flex;", " align-items: center;", " flex: none;", " box-sizing: border-box;", " width: 36px;", " height: 20px;", " padding: 2px;", " border: 1px solid #455d73;", " border-radius: 999px;", " background: #2b3d4f;", " transition: background 150ms, border-color 150ms;", " }", " .wl-setup-switch::after {", ' content: "";', " display: block;", " flex: none;", " width: 14px;", " height: 14px;", " border-radius: 999px;", " background: #b8c7d4;", " transition: transform 150ms, background 150ms;", " }", " .wl-setup-switch-input:checked + .wl-setup-switch {", " border-color: #66c0f4;", " background: #2b6ca3;", " }", " .wl-setup-switch-input:checked + .wl-setup-switch::after {", " transform: translateX(16px);", " background: #fff;", " }", " .wl-setup-switch-input:focus-visible + .wl-setup-switch {", " outline: 2px solid var(--color-near);", " outline-offset: 2px;", " }", " #list {", " display: flex;", " flex: 1;", " min-height: 0;", " flex-direction: column;", " gap: 8px;", " overflow: auto;", " padding-bottom: 52px;", " scroll-padding-bottom: 52px;", " }", " .wl-row {", " display: flex;", " gap: 12px;", " padding: 10px 12px;", " background: rgba(0, 0, 0, 0.2);", " }", " .wl-row:hover {", " background: #2a475e;", " }", " .wl-cap {", " flex: none;", " width: 184px;", " height: 69px;", " background: #000;", " }", " .wl-cap img {", " display: block;", " width: 184px;", " height: 69px;", " object-fit: cover;", " }", " .wl-row-body {", " min-width: 0;", " flex: 1;", " }", " .wl-row-heading {", " display: flex;", " flex-wrap: wrap;", " align-items: baseline;", " gap: 4px 10px;", " }", " .wl-release-date {", " color: #8f98a0;", " font-size: 12px;", " white-space: nowrap;", " }", " .wl-title {", " color: #fff;", " font-size: 15px;", " font-weight: 500;", " text-decoration: none;", " }", " .wl-title:hover {", " color: #66c0f4;", " }", " .wl-wishlist-remove {", " display: inline-flex;", " flex: none;", " align-self: center;", " align-items: center;", " justify-content: center;", " width: 24px;", " height: 24px;", " padding: 0;", " border: 0;", " border-radius: 3px;", " background: transparent;", " color: #a8bbca;", " cursor: pointer;", " }", " .wl-wishlist-remove svg {", " width: 14px;", " height: 14px;", " }", " .wl-wishlist-remove:hover, .wl-wishlist-remove:focus-visible {", " color: #ffd1c9;", " background: #493037;", " }", " .wl-wishlist-remove:focus-visible {", " outline: 1px solid #ffd1c9;", " }", " .wl-wishlist-removal {", " --wl-dialog-width: 390px;", " margin: auto;", " font-size: 13px;", " }", " .wl-wishlist-removal-game {", " margin-bottom: 4px;", " color: #e1edf5;", " font-weight: 600;", " overflow-wrap: anywhere;", " }", " .wl-wishlist-removal-error {", " margin-top: 8px;", " color: #ffb5a7;", " }", " .wl-wishlist-removal-error:empty {", " display: none;", " }", " .wl-row-status, .wl-row-history, .wl-row-stats {", " margin-top: 4px;", " color: #8f98a0;", " font-size: 12px;", " }", " .wl-row-history a {", " color: #66c0f4;", " }", " .wl-row-stats {", " display: flex;", " flex-wrap: wrap;", " gap: 10px;", " color: #c7d5e0;", " }", " .wl-row-chips {", " display: flex;", " flex-wrap: wrap;", " gap: 6px;", " margin-top: 8px;", " }", " .wl-disc {", " max-width: 100%;", " display: inline-flex;", " align-items: stretch;", " overflow: hidden;", " background: #000;", " color: #fff;", " font-size: 12px;", " line-height: 1.2;", " }", " .wl-disc.is-cheap {", " outline: 1px solid #a4d007;", " }", " .wl-disc.is-near {", " outline: 1px solid #66c0f4;", " }", " .wl-disc-region {", " display: flex;", " align-items: center;", " padding: 0 8px;", " background: #3d4450;", " color: #c7d5e0;", " white-space: nowrap;", " }", " .wl-disc-pct {", " display: flex;", " align-items: center;", " padding: 0 6px;", " background: #4c6b22;", " color: #fff;", " font-size: 16px;", " font-weight: 700;", " white-space: nowrap;", " }", " .wl-disc-prices {", " min-width: 0;", " display: flex;", " flex-direction: column;", " justify-content: center;", " padding: 3px 8px;", " white-space: nowrap;", " }", " .wl-disc-price-line {", " display: flex;", " align-items: center;", " gap: 4px;", " }", " .wl-disc-low {", " padding: 2px 3px;", " border-radius: 2px;", " background: #4c6b22;", " color: #beee32;", " font-size: 10px;", " font-weight: 700;", " }", " .wl-disc-low.is-new {", " background: #1b4d2c;", " color: #b9f6c9;", " }", " .wl-disc-bundle {", " padding: 2px 4px;", " border-radius: 2px;", " background: #5b3b16;", " color: #ffd080;", " font-size: 10px;", " font-weight: 700;", " white-space: nowrap;", " }", " .wl-row-cheapest, .wl-disc.is-cheap .wl-disc-cny {", " color: #beee32;", " }", " .wl-row-discount-time {", " color: #ffd080;", " }", " .wl-disc.is-near .wl-disc-cny {", " color: #66c0f4;", " }", " .wl-disc-cny {", " color: #fff;", " font-variant-numeric: tabular-nums;", " }", " .wl-disc-local {", " color: #738895;", " font-size: 10px;", " }", " .wl-disc-gift {", " display: flex;", " align-items: center;", " padding: 0 6px;", " background: #4c6b22;", " color: #fff;", " font-size: 10px;", " font-weight: 700;", " white-space: nowrap;", " }", "}", "@property --tw-rotate-x {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-rotate-y {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-rotate-z {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-skew-x {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-skew-y {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-border-style {", ' syntax: "*";', " inherits: false;", " initial-value: solid;", "}", "@property --tw-leading {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-font-weight {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-ordinal {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-slashed-zero {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-numeric-figure {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-numeric-spacing {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-numeric-fraction {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-shadow {", ' syntax: "*";', " inherits: false;", " initial-value: 0 0 #0000;", "}", "@property --tw-shadow-color {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-shadow-alpha {", ' syntax: "";', " inherits: false;", " initial-value: 100%;", "}", "@property --tw-inset-shadow {", ' syntax: "*";', " inherits: false;", " initial-value: 0 0 #0000;", "}", "@property --tw-inset-shadow-color {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-inset-shadow-alpha {", ' syntax: "";', " inherits: false;", " initial-value: 100%;", "}", "@property --tw-ring-color {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-ring-shadow {", ' syntax: "*";', " inherits: false;", " initial-value: 0 0 #0000;", "}", "@property --tw-inset-ring-color {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-inset-ring-shadow {", ' syntax: "*";', " inherits: false;", " initial-value: 0 0 #0000;", "}", "@property --tw-ring-inset {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-ring-offset-width {", ' syntax: "";', " inherits: false;", " initial-value: 0px;", "}", "@property --tw-ring-offset-color {", ' syntax: "*";', " inherits: false;", " initial-value: #fff;", "}", "@property --tw-ring-offset-shadow {", ' syntax: "*";', " inherits: false;", " initial-value: 0 0 #0000;", "}", "@property --tw-outline-style {", ' syntax: "*";', " inherits: false;", " initial-value: solid;", "}", "@property --tw-blur {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-brightness {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-contrast {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-grayscale {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-hue-rotate {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-invert {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-opacity {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-saturate {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-sepia {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-drop-shadow {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-drop-shadow-color {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-drop-shadow-alpha {", ' syntax: "";', " inherits: false;", " initial-value: 100%;", "}", "@property --tw-drop-shadow-size {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-backdrop-blur {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-backdrop-brightness {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-backdrop-contrast {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-backdrop-grayscale {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-backdrop-hue-rotate {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-backdrop-invert {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-backdrop-opacity {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-backdrop-saturate {", ' syntax: "*";', " inherits: false;", "}", "@property --tw-backdrop-sepia {", ' syntax: "*";', " inherits: false;", "}", "@layer properties {", " @supports ((-webkit-hyphens: none) and (not (margin-trim: block))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))) {", " *, ::before, ::after, ::backdrop {", " --tw-rotate-x: initial;", " --tw-rotate-y: initial;", " --tw-rotate-z: initial;", " --tw-skew-x: initial;", " --tw-skew-y: initial;", " --tw-border-style: solid;", " --tw-leading: initial;", " --tw-font-weight: initial;", " --tw-ordinal: initial;", " --tw-slashed-zero: initial;", " --tw-numeric-figure: initial;", " --tw-numeric-spacing: initial;", " --tw-numeric-fraction: initial;", " --tw-shadow: 0 0 #0000;", " --tw-shadow-color: initial;", " --tw-shadow-alpha: 100%;", " --tw-inset-shadow: 0 0 #0000;", " --tw-inset-shadow-color: initial;", " --tw-inset-shadow-alpha: 100%;", " --tw-ring-color: initial;", " --tw-ring-shadow: 0 0 #0000;", " --tw-inset-ring-color: initial;", " --tw-inset-ring-shadow: 0 0 #0000;", " --tw-ring-inset: initial;", " --tw-ring-offset-width: 0px;", " --tw-ring-offset-color: #fff;", " --tw-ring-offset-shadow: 0 0 #0000;", " --tw-outline-style: solid;", " --tw-blur: initial;", " --tw-brightness: initial;", " --tw-contrast: initial;", " --tw-grayscale: initial;", " --tw-hue-rotate: initial;", " --tw-invert: initial;", " --tw-opacity: initial;", " --tw-saturate: initial;", " --tw-sepia: initial;", " --tw-drop-shadow: initial;", " --tw-drop-shadow-color: initial;", " --tw-drop-shadow-alpha: 100%;", " --tw-drop-shadow-size: initial;", " --tw-backdrop-blur: initial;", " --tw-backdrop-brightness: initial;", " --tw-backdrop-contrast: initial;", " --tw-backdrop-grayscale: initial;", " --tw-backdrop-hue-rotate: initial;", " --tw-backdrop-invert: initial;", " --tw-backdrop-opacity: initial;", " --tw-backdrop-saturate: initial;", " --tw-backdrop-sepia: initial;", " }", " }", "}", "" ]; var report_generated_default = cssChunks.join("\n"); // src/scripts/steam-wishlist-prices/pricing/discount-time.ts var discountTimeCopy = { label: "折扣截止", timeZone: "北京时间", ascending: "早→晚", descending: "晚→早" }; var formatDiscountEnd = (endsAt) => { if (endsAt === null || !Number.isFinite(endsAt) || endsAt <= 0) return null; const date = new Date(endsAt); if (Number.isNaN(date.getTime())) return null; const when = date.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }); return { label: discountTimeCopy.label, when, timeZone: discountTimeCopy.timeZone }; }; var gameDiscountEnd = (prices, home) => { const validEnd = (price) => price && price.cut > 0 && Number.isFinite(price.discountEndsAt) && Number(price.discountEndsAt) > 0 ? price.discountEndsAt : null; const homeEnd = validEnd(prices[home]); if (homeEnd !== null) return homeEnd; const ends = Object.values(prices).map(validEnd).filter((end) => end !== null); return ends.length > 0 ? Math.min(...ends) : null; }; // node_modules/@bufbuild/protobuf/dist/esm/wire/varint.js function varint64read() { const buf = this.buf; let pos = this.pos; let lo = 0; let hi = 0; for (let shift = 0; shift < 28; shift += 7) { const b = buf[pos++]; lo |= (b & 127) << shift; if ((b & 128) == 0) { this.pos = pos; this.assertBounds(); this.varint64Lo = lo; this.varint64Hi = hi; return; } } const middleByte = buf[pos++]; lo |= (middleByte & 15) << 28; hi = (middleByte & 112) >> 4; if ((middleByte & 128) == 0) { this.pos = pos; this.assertBounds(); this.varint64Lo = lo; this.varint64Hi = hi; return; } for (let shift = 3; shift <= 31; shift += 7) { const b = buf[pos++]; hi |= (b & 127) << shift; if ((b & 128) == 0) { this.pos = pos; this.assertBounds(); this.varint64Lo = lo; this.varint64Hi = hi; return; } } throw new Error("invalid varint"); } var TWO_PWR_32_DBL = 4294967296; function int64FromString(dec) { const minus = dec[0] === "-"; if (minus) { dec = dec.slice(1); } const base = 1e6; let lowBits = 0; let highBits = 0; function add1e6digit(begin, end) { const digit1e6 = Number(dec.slice(begin, end)); highBits *= base; lowBits = lowBits * base + digit1e6; if (lowBits >= TWO_PWR_32_DBL) { highBits = highBits + (lowBits / TWO_PWR_32_DBL | 0); lowBits = lowBits % TWO_PWR_32_DBL; } } add1e6digit(-24, -18); add1e6digit(-18, -12); add1e6digit(-12, -6); add1e6digit(-6); return minus ? negate(lowBits, highBits) : newBits(lowBits, highBits); } function int64ToString(lo, hi) { let bits = newBits(lo, hi); const negative = bits.hi & 2147483648; if (negative) { bits = negate(bits.lo, bits.hi); } const result = uInt64ToString(bits.lo, bits.hi); return negative ? "-" + result : result; } function uInt64ToString(lo, hi) { ({ lo, hi } = toUnsigned(lo, hi)); if (hi <= 2097151) { return String(TWO_PWR_32_DBL * hi + lo); } const low = lo & 16777215; const mid = (lo >>> 24 | hi << 8) & 16777215; const high = hi >> 16 & 65535; let digitA = low + mid * 6777216 + high * 6710656; let digitB = mid + high * 8147497; let digitC = high * 2; const base = 1e7; if (digitA >= base) { digitB += Math.floor(digitA / base); digitA %= base; } if (digitB >= base) { digitC += Math.floor(digitB / base); digitB %= base; } return digitC.toString() + decimalFrom1e7WithLeadingZeros(digitB) + decimalFrom1e7WithLeadingZeros(digitA); } function toUnsigned(lo, hi) { return { lo: lo >>> 0, hi: hi >>> 0 }; } function newBits(lo, hi) { return { lo: lo | 0, hi: hi | 0 }; } function negate(lowBits, highBits) { highBits = ~highBits; if (lowBits) { lowBits = ~lowBits + 1; } else { highBits += 1; } return newBits(lowBits, highBits); } var decimalFrom1e7WithLeadingZeros = (digit1e7) => { const partial = String(digit1e7); return "0000000".slice(partial.length) + partial; }; function varint32read() { let b = this.buf[this.pos++]; if ((b & 128) === 0) { this.assertBounds(); return b; } let result = b & 127; b = this.buf[this.pos++]; result |= (b & 127) << 7; if ((b & 128) === 0) { this.assertBounds(); return result; } b = this.buf[this.pos++]; result |= (b & 127) << 14; if ((b & 128) === 0) { this.assertBounds(); return result; } b = this.buf[this.pos++]; result |= (b & 127) << 21; if ((b & 128) === 0) { this.assertBounds(); return result; } b = this.buf[this.pos++]; result |= (b & 15) << 28; for (let readBytes = 5; (b & 128) !== 0 && readBytes < 10; readBytes++) b = this.buf[this.pos++]; if ((b & 128) !== 0) throw new Error("invalid varint"); this.assertBounds(); return result >>> 0; } // node_modules/@bufbuild/protobuf/dist/esm/proto-int64.js var protoInt64 = /* @__PURE__ */ makeInt64Support(); function makeInt64Support() { const dv = new DataView(new ArrayBuffer(8)); const ok = typeof BigInt === "function" && typeof dv.getBigInt64 === "function" && typeof dv.getBigUint64 === "function" && typeof dv.setBigInt64 === "function" && typeof dv.setBigUint64 === "function" && (!!globalThis.Deno || !!globalThis.Bun || typeof process != "object" || typeof process.env != "object" || process.env.BUF_BIGINT_DISABLE !== "1"); if (ok) { const MIN = BigInt("-9223372036854775808"); const MAX = BigInt("9223372036854775807"); const UMIN = BigInt("0"); const UMAX = BigInt("18446744073709551615"); return { zero: BigInt(0), supported: true, parse(value) { const bi = typeof value == "bigint" ? value : BigInt(value); if (bi > MAX || bi < MIN) { throw new Error(`invalid int64: ${value}`); } return bi; }, uParse(value) { const bi = typeof value == "bigint" ? value : BigInt(value); if (bi > UMAX || bi < UMIN) { throw new Error(`invalid uint64: ${value}`); } return bi; }, enc(value) { dv.setBigInt64(0, this.parse(value), true); return { lo: dv.getInt32(0, true), hi: dv.getInt32(4, true) }; }, uEnc(value) { dv.setBigInt64(0, this.uParse(value), true); return { lo: dv.getInt32(0, true), hi: dv.getInt32(4, true) }; }, dec(lo, hi) { dv.setInt32(0, lo, true); dv.setInt32(4, hi, true); return dv.getBigInt64(0, true); }, uDec(lo, hi) { dv.setInt32(0, lo, true); dv.setInt32(4, hi, true); return dv.getBigUint64(0, true); } }; } return { zero: "0", supported: false, parse(value) { if (typeof value != "string") { value = value.toString(); } assertInt64String(value); return value; }, uParse(value) { if (typeof value != "string") { value = value.toString(); } assertUInt64String(value); return value; }, enc(value) { if (typeof value != "string") { value = value.toString(); } assertInt64String(value); return int64FromString(value); }, uEnc(value) { if (typeof value != "string") { value = value.toString(); } assertUInt64String(value); return int64FromString(value); }, dec(lo, hi) { return int64ToString(lo, hi); }, uDec(lo, hi) { return uInt64ToString(lo, hi); } }; } function assertInt64String(value) { if (!/^-?[0-9]+$/.test(value)) { throw new Error("invalid int64: " + value); } } function assertUInt64String(value) { if (!/^[0-9]+$/.test(value)) { throw new Error("invalid uint64: " + value); } } // node_modules/@bufbuild/protobuf/dist/esm/wire/text-encoding.js var te; function configureTextEncoding(textEncoding) { var _a; te = Object.assign(Object.assign({}, textEncoding), { encodeUtf8Into: (_a = textEncoding.encodeUtf8Into) !== null && _a !== void 0 ? _a : emulateEncodeInto(textEncoding.encodeUtf8.bind(textEncoding)) }); } function getTextEncoding() { if (!te) { const globals = globalThis; if (!globals.TextEncoder || !globals.TextDecoder) { throw new Error("encoding API missing: install TextEncoder and TextDecoder on globalThis"); } const textEncoder = new globals.TextEncoder(); const textDecoder = new globals.TextDecoder("utf-8", { ignoreBOM: true }); let textDecoderStrict; const config = { encodeUtf8(text) { return textEncoder.encode(text); }, decodeUtf8(bytes, strict) { if (strict) { if (!textDecoderStrict) { textDecoderStrict = new globals.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); } return textDecoderStrict.decode(bytes); } return textDecoder.decode(bytes); }, checkUtf8(text) { try { encodeURIComponent(text); return true; } catch (_) { return false; } } }; if (textEncoder.encodeInto) { config.encodeUtf8Into = textEncoder.encodeInto.bind(textEncoder); } const nativeStringIsWellFormed = String.prototype.isWellFormed; if (nativeStringIsWellFormed) { config.checkUtf8 = (text) => { return nativeStringIsWellFormed.call(text); }; } configureTextEncoding(config); } return te; } function emulateEncodeInto(encodeUtf8) { return (text, dest) => { const bytes = encodeUtf8(text); dest.set(bytes); return { written: bytes.byteLength }; }; } // node_modules/@bufbuild/protobuf/dist/esm/wire/binary-encoding.js var WireType; (function(WireType2) { WireType2[WireType2["Varint"] = 0] = "Varint"; WireType2[WireType2["Bit64"] = 1] = "Bit64"; WireType2[WireType2["LengthDelimited"] = 2] = "LengthDelimited"; WireType2[WireType2["StartGroup"] = 3] = "StartGroup"; WireType2[WireType2["EndGroup"] = 4] = "EndGroup"; WireType2[WireType2["Bit32"] = 5] = "Bit32"; })(WireType || (WireType = {})); var UINT32_MAX = 4294967295; var INT32_MAX = 2147483647; var INT32_MIN = -2147483648; var BinaryWriter = class { constructor(encodeUtf8) { this.stackPos = []; this.encodeUtf8Into = encodeUtf8 ? emulateEncodeInto(encodeUtf8) : getTextEncoding().encodeUtf8Into; this.buffer = EMPTY_BUFFER; this.viewCache = EMPTY_VIEW; this.pos = 0; } ensureCapacity(size) { const required = this.pos + size; if (required > this.buffer.length) { let newLen = this.buffer.length || INITIAL_SIZE; while (newLen < required) newLen *= 2; const newBuf = new Uint8Array(newLen); if (this.pos > 0) newBuf.set(this.buffer); this.buffer = newBuf; } } /** * The DataView over `buffer`, rebuilt only if the buffer has grown since it * was last used. */ view() { const bytes = this.buffer; const view = this.viewCache; if (view.byteLength === bytes.byteLength) return view; const newView = new DataView(bytes.buffer); this.viewCache = newView; return newView; } /** * Return all bytes written and reset this writer. */ finish() { const result = this.buffer.slice(0, this.pos); this.pos = 0; this.stackPos = []; return result; } /** * Start a new fork for length-delimited data like a message * or a packed repeated field. * * Must be joined later with `join()`. */ fork() { this.stackPos.push(this.pos); this.ensureCapacity(DEFAULT_LEN_PREFIX_SIZE); this.buffer[this.pos++] = 0; return this; } /** * Join the last fork. Write its length and bytes, then * return to the previous state. */ join() { const forkPos = this.stackPos.pop(); if (forkPos === void 0) throw new Error("invalid state, fork stack empty"); const len = this.pos - forkPos - DEFAULT_LEN_PREFIX_SIZE; const lenPrefixSize = varint32Size(len); if (lenPrefixSize > DEFAULT_LEN_PREFIX_SIZE) { this.ensureCapacity(lenPrefixSize - DEFAULT_LEN_PREFIX_SIZE); this.buffer.copyWithin(forkPos + lenPrefixSize, forkPos + DEFAULT_LEN_PREFIX_SIZE, this.pos); } this.pos = forkPos; this.uint32(len); this.pos += len; return this; } /** * Writes a tag (field number and wire type). * * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`. * * Generated code should compute the tag ahead of time and call `uint32()`. */ tag(fieldNo, type) { return this.uint32((fieldNo << 3 | type) >>> 0); } /** * Write a chunk of raw bytes. */ raw(chunk) { this.ensureCapacity(chunk.length); this.buffer.set(chunk, this.pos); this.pos += chunk.length; return this; } /** * Write a `uint32` value, an unsigned 32 bit varint. */ uint32(value) { assertUInt32(value); this.ensureCapacity(5); if (value < 128) { this.buffer[this.pos++] = value; return this; } while (value > 127) { this.buffer[this.pos++] = value & 127 | 128; value >>>= 7; } this.buffer[this.pos++] = value; return this; } /** * Write a `int32` value, a signed 32 bit varint. */ int32(value) { assertInt32(value); if (value >= 0) { return this.uint32(value); } this.ensureCapacity(10); for (let i = 0; i < 9; i++) { this.buffer[this.pos++] = value & 127 | 128; value >>= 7; } this.buffer[this.pos++] = 1; return this; } /** * Write a `bool` value, a varint. */ bool(value) { this.ensureCapacity(1); this.buffer[this.pos++] = value ? 1 : 0; return this; } /** * Write a `bytes` value, length-delimited arbitrary data. */ bytes(value) { this.uint32(value.byteLength); return this.raw(value); } /** * Write a `string` value, length-delimited data converted to UTF-8 text. */ string(value) { if (typeof value !== "string") { value = String(value); } const len = value.length; if (len <= ASCII_MAX_LENGTH) { this.ensureCapacity(len + 1); const ascii = this.buffer; let pos = this.pos; ascii[pos++] = len; let i = 0; for (; i < len; i++) { const code = value.charCodeAt(i); if (code > 127) break; ascii[pos++] = code; } if (i == len) { this.pos = pos; return this; } } this.ensureCapacity(len * 3 + 5); const lenPrefixSizeGuess = varint32Size(len); const buf = this.buffer; const start = this.pos; const { written } = this.encodeUtf8Into(value, buf.subarray(start + lenPrefixSizeGuess)); const lenPrefixSize = varint32Size(written); if (lenPrefixSize != lenPrefixSizeGuess) { buf.copyWithin(start + lenPrefixSize, start + lenPrefixSizeGuess, start + lenPrefixSizeGuess + written); } this.uint32(written); this.pos += written; return this; } /** * Write a `float` value, 32-bit floating point number. */ float(value) { assertFloat32(value); this.ensureCapacity(4); this.view().setFloat32(this.pos, value, true); this.pos += 4; return this; } /** * Write a `double` value, a 64-bit floating point number. */ double(value) { this.ensureCapacity(8); this.view().setFloat64(this.pos, value, true); this.pos += 8; return this; } /** * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer. */ fixed32(value) { assertUInt32(value); this.ensureCapacity(4); this.view().setUint32(this.pos, value, true); this.pos += 4; return this; } /** * Write a `sfixed32` value, a signed, fixed-length 32-bit integer. */ sfixed32(value) { assertInt32(value); this.ensureCapacity(4); this.view().setInt32(this.pos, value, true); this.pos += 4; return this; } /** * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint. */ sint32(value) { assertInt32(value); return this.uint32((value << 1 ^ value >> 31) >>> 0); } /** * Write a `sfixed64` value, a signed, fixed-length 64-bit integer. */ sfixed64(value) { const tc = protoInt64.enc(value); this.ensureCapacity(8); const view = this.view(); view.setInt32(this.pos, tc.lo, true); view.setInt32(this.pos + 4, tc.hi, true); this.pos += 8; return this; } /** * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer. */ fixed64(value) { const tc = protoInt64.uEnc(value); this.ensureCapacity(8); const view = this.view(); view.setInt32(this.pos, tc.lo, true); view.setInt32(this.pos + 4, tc.hi, true); this.pos += 8; return this; } /** * Write a `int64` value, a signed 64-bit varint. */ int64(value) { const tc = protoInt64.enc(value); return this.writeVarint64(tc.lo, tc.hi); } /** * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint. */ sint64(value) { const tc = protoInt64.enc(value), sign = tc.hi >> 31, lo = tc.lo << 1 ^ sign, hi = (tc.hi << 1 | tc.lo >>> 31) ^ sign; return this.writeVarint64(lo, hi); } /** * Write a `uint64` value, an unsigned 64-bit varint. */ uint64(value) { const tc = protoInt64.uEnc(value); return this.writeVarint64(tc.lo, tc.hi); } /** * Write a 64-bit varint directly into the buffer. Accepts the value as * split low/high 32-bit words. * * Ported from varint64write() to avoid the intermediate number[] buffer. * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344 */ writeVarint64(lo, hi) { this.ensureCapacity(10); const buf = this.buffer; let pos = this.pos; for (let i = 0; i < 28; i = i + 7) { const shift = lo >>> i; const hasNext = !(shift >>> 7 == 0 && hi == 0); buf[pos++] = (hasNext ? shift | 128 : shift) & 255; if (!hasNext) { this.pos = pos; return this; } } const splitBits = lo >>> 28 & 15 | (hi & 7) << 4; const hasMoreBits = !(hi >> 3 == 0); buf[pos++] = (hasMoreBits ? splitBits | 128 : splitBits) & 255; if (!hasMoreBits) { this.pos = pos; return this; } for (let i = 3; i < 31; i = i + 7) { const shift = hi >>> i; const hasNext = !(shift >>> 7 == 0); buf[pos++] = (hasNext ? shift | 128 : shift) & 255; if (!hasNext) { this.pos = pos; return this; } } buf[pos++] = hi >>> 31 & 1; this.pos = pos; return this; } }; var INITIAL_SIZE = 128; var DEFAULT_LEN_PREFIX_SIZE = 1; var EMPTY_BUFFER = new Uint8Array(0); var EMPTY_VIEW = new DataView(EMPTY_BUFFER.buffer); var ASCII_MAX_LENGTH = 32; function varint32Size(value) { if (value < 128) return 1; if (value < 16384) return 2; if (value < 2097152) return 3; if (value < 268435456) return 4; return 5; } var BinaryReader = class { constructor(buf, decodeUtf8 = getTextEncoding().decodeUtf8) { this.decodeUtf8 = decodeUtf8; this.varint64Lo = 0; this.varint64Hi = 0; this.varint64 = varint64read; this.uint32 = varint32read; this.buf = buf; this.len = buf.length; this.pos = 0; this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); } /** * Reads a tag - field number and wire type. Tags are uint32 varints; values * that do not fit in uint32 are rejected. */ tag() { const start = this.pos; const tag = this.uint32(); const bytesRead = this.pos - start; if (bytesRead > 5 || bytesRead == 5 && this.buf[this.pos - 1] > 15) { throw new Error("illegal tag: varint overflows uint32"); } const fieldNo = tag >>> 3; const wireType2 = tag & 7; if (fieldNo <= 0 || wireType2 > 5) { throw new Error("illegal tag: field no " + fieldNo + " wire type " + wireType2); } return [fieldNo, wireType2]; } /** * Skip one element and return the skipped data. * * When skipping StartGroup, provide the tags field number to check for * matching field number in the EndGroup tag. Recursion into nested groups * is guarded by the `recursionLimit` argument: When the limit is reached, * this method throws. */ skip(wireType2, fieldNo, recursionLimit = 100) { let start = this.pos; switch (wireType2) { case WireType.Varint: while (this.buf[this.pos++] & 128) { } break; // @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true case WireType.Bit64: this.pos += 4; case WireType.Bit32: this.pos += 4; break; case WireType.LengthDelimited: let len = this.uint32(); this.pos += len; break; case WireType.StartGroup: if (recursionLimit <= 0) { throw new Error("maximum recursion depth reached"); } for (; ; ) { const [fn, wt] = this.tag(); if (wt === WireType.EndGroup) { if (fieldNo !== void 0 && fn !== fieldNo) { throw new Error("invalid end group tag"); } break; } this.skip(wt, fn, recursionLimit - 1); } break; default: throw new Error("cant skip wire type " + wireType2); } this.assertBounds(); return this.buf.subarray(start, this.pos); } /** * Throws error if position in byte array is out of range. */ assertBounds() { if (this.pos > this.len) throw new RangeError("premature EOF"); } /** * Read a `int32` field, a signed 32 bit varint. */ int32() { return this.uint32() | 0; } /** * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint. */ sint32() { let zze = this.uint32(); return zze >>> 1 ^ -(zze & 1); } /** * Read a `int64` field, a signed 64-bit varint. */ int64() { this.varint64(); return protoInt64.dec(this.varint64Lo, this.varint64Hi); } /** * Read a `uint64` field, an unsigned 64-bit varint. */ uint64() { this.varint64(); return protoInt64.uDec(this.varint64Lo, this.varint64Hi); } /** * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint. */ sint64() { this.varint64(); let lo = this.varint64Lo; let hi = this.varint64Hi; let s = -(lo & 1); lo = (lo >>> 1 | (hi & 1) << 31) ^ s; hi = hi >>> 1 ^ s; return protoInt64.dec(lo, hi); } /** * Read a `bool` field, a variant. */ bool() { const b = this.buf[this.pos]; if (b < 128) { this.pos++; return b !== 0; } this.varint64(); return this.varint64Lo !== 0 || this.varint64Hi !== 0; } /** * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer. */ fixed32() { return this.view.getUint32((this.pos += 4) - 4, true); } /** * Read a `sfixed32` field, a signed, fixed-length 32-bit integer. */ sfixed32() { return this.view.getInt32((this.pos += 4) - 4, true); } /** * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer. */ fixed64() { return protoInt64.uDec(this.sfixed32(), this.sfixed32()); } /** * Read a `fixed64` field, a signed, fixed-length 64-bit integer. */ sfixed64() { return protoInt64.dec(this.sfixed32(), this.sfixed32()); } /** * Read a `float` field, 32-bit floating point number. */ float() { return this.view.getFloat32((this.pos += 4) - 4, true); } /** * Read a `double` field, a 64-bit floating point number. */ double() { return this.view.getFloat64((this.pos += 8) - 8, true); } /** * Read a `bytes` field, length-delimited arbitrary data. */ bytes() { let len = this.uint32(), start = this.pos; this.pos += len; this.assertBounds(); return this.buf.subarray(start, start + len); } /** * Read a `string` field, length-delimited data converted to UTF-8 text. If * `strict` is true, throw on invalid UTF-8 instead of substituting U+FFFD. */ string(strict) { const len = this.uint32(); const start = this.pos; this.pos += len; this.assertBounds(); const buf = this.buf; if (len <= ASCII_MAX_LENGTH) { const codes2 = new Array(len); for (let i = 0; i < len; i++) { const byte = buf[start + i]; if (byte > 127) { return this.decodeUtf8(buf.subarray(start, this.pos), strict); } codes2[i] = byte; } return String.fromCharCode.apply(String, codes2); } return this.decodeUtf8(buf.subarray(start, this.pos), strict); } }; function assertInt32(arg) { if (typeof arg == "string") { arg = Number(arg); } else if (typeof arg != "number") { throw new Error("invalid int32: " + typeof arg); } if (!Number.isInteger(arg) || arg > INT32_MAX || arg < INT32_MIN) throw new Error("invalid int32: " + arg); } function assertUInt32(arg) { if (typeof arg == "string") { arg = Number(arg); } else if (typeof arg != "number") { throw new Error("invalid uint32: " + typeof arg); } if (!Number.isInteger(arg) || arg > UINT32_MAX || arg < 0) throw new Error("invalid uint32: " + arg); } function assertFloat32(arg) { if (typeof arg == "string") { const o = arg; arg = Number(arg); if (Number.isNaN(arg) && o !== "NaN") { throw new Error("invalid float32: " + o); } } else if (typeof arg != "number") { throw new Error("invalid float32: " + typeof arg); } if (!Number.isFinite(Math.fround(arg)) && Number.isFinite(arg)) { throw new Error("invalid float32: " + arg); } } // src/scripts/steam-wishlist-prices/steam/steam-protobuf.ts var wireType = (format) => { if (format === "fixed64") return WireType.Bit64; if (typeof format === "object" || format === "string") return WireType.LengthDelimited; return WireType.Varint; }; var encodeSteamMessage = (schema, input) => { const values = input; const writer = new BinaryWriter(); for (const [number, [name, format, repeated]] of Object.entries(schema)) { const value = values[name]; if (value == null) continue; for (const entry of repeated ? value : [value]) { writer.tag(Number(number), wireType(format)); if (typeof format === "object") writer.bytes(encodeSteamMessage(format, entry)); else if (format === "string") writer.string(entry); else if (format === "bool") writer.bool(entry); else if (format === "uint32" || format === "int32") writer[format](entry); else writer[format](entry); } } return writer.finish(); }; var decodeSteamMessage = (schema, data) => { const reader = new BinaryReader(data); const output = {}; while (reader.pos < reader.len) { const [number, wire] = reader.tag(); const field = schema[number]; if (!field) { reader.skip(wire, number); continue; } const [name, format, repeated] = field; if (repeated && (format === "uint64" || format === "uint32") && wire === WireType.LengthDelimited) { const packed = new BinaryReader(reader.bytes()); const values = output[name] ?? (output[name] = []); while (packed.pos < packed.len) values.push(format === "uint64" ? packed.uint64().toString() : packed.uint32()); continue; } if (wire !== wireType(format)) throw new Error("Steam protobuf 字段格式异常"); const value = typeof format === "object" ? decodeSteamMessage(format, reader.bytes()) : format === "uint64" || format === "int64" || format === "fixed64" ? reader[format]().toString() : reader[format](); if (repeated) (output[name] ?? (output[name] = [])).push(value); else output[name] = value; } return output; }; var context = { 1: ["language", "string"], 3: ["country_code", "string"] }; var dataRequest = { 1: ["include_assets", "bool"], 2: ["include_release", "bool"], 4: ["include_all_purchase_options", "bool"], 10: ["include_basic_info", "bool"] }; var assets = { 1: ["asset_url_format", "string"], 2: ["main_capsule", "string"], 3: ["small_capsule", "string"], 4: ["header", "string"] }; var release = { 1: ["steam_release_date", "uint32"], 2: ["original_release_date", "uint32"], 4: ["is_coming_soon", "bool"] }; var discount = { 3: ["discount_end_date", "uint32"] }; var purchaseOption = { 1: ["packageid", "int32"], 2: ["bundleid", "int32"], 3: ["purchase_option_name", "string"], 5: ["final_price_in_cents", "int64"], 6: ["original_price_in_cents", "int64"], 8: ["formatted_final_price", "string"], 10: ["discount_pct", "int32"], 20: ["active_discounts", discount, true], 43: ["included_game_count", "int32"] }; var storeItem = { 2: ["id", "uint32"], 3: ["success", "uint32"], 4: ["visible", "bool"], 5: ["unvailable_for_country_restriction", "bool"], 6: ["name", "string"], 9: ["appid", "uint32"], 13: ["is_free", "bool"], 30: ["assets", assets], 31: ["release", release], 40: ["best_purchase_option", purchaseOption], 41: ["purchase_options", purchaseOption, true] }; var app = { 1: ["appid", "uint32"] }; var sortedItem = { ...app, 4: ["store_item", storeItem], 5: ["category_ids", "uint64", true] }; var wishlistOwner = { 1: ["steamid", "fixed64"] }; var category = { 1: ["categoryid", "uint64"], 2: ["name", "string"] }; var categoryItem = { ...app, 2: ["categoryid", "uint64"] }; var categories = { 1: ["categories", category, true] }; var steamRpcs = { "Wishlist/GetWishlist": { request: wishlistOwner, response: { 1: ["items", app, true] } }, "Wishlist/AddToWishlist": { request: app, response: { 1: ["wishlist_count", "uint32"] }, write: true }, "Wishlist/RemoveFromWishlist": { request: app, response: { 1: ["wishlist_count", "uint32"] }, write: true }, "Wishlist/GetWishlistSortedFiltered": { request: { ...wishlistOwner, 2: ["context", context], 3: ["data_request", dataRequest], 6: ["start_index", "int32"], 7: ["page_size", "int32"], 8: ["share_token", "string"] }, response: { 1: ["items", sortedItem, true] } }, "StoreBrowse/GetItems": { request: { 1: ["ids", app, true], 2: ["context", context], 3: ["data_request", dataRequest] }, response: { 1: ["store_items", storeItem, true] } }, "Wishlist/GetWishlistCategories": { request: {}, response: categories }, "Wishlist/GetSharedWishlistCategories": { request: { ...wishlistOwner, 2: ["share_token", "string"] }, response: categories }, "Wishlist/AddWishlistItemCategory": { request: { ...categoryItem, 3: ["category_name", "string"] }, response: category, write: true }, "Wishlist/RemoveWishlistItemCategory": { request: categoryItem, response: category, write: true }, "Wishlist/RenameWishlistCategory": { request: category, response: { 1: ["appids", "uint32", true] }, write: true } }; // src/scripts/steam-wishlist-prices/steam/steam-http.ts var MAX_ATTEMPTS = 8; var INITIAL_MS = 1e3; var MAX_MS = 6e4; var RETRY_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]); var backoffMs = (attempt) => { const exp = Math.min(INITIAL_MS * 2 ** attempt, MAX_MS); return exp + Math.floor(Math.random() * 250); }; var STORE_ORIGIN = "https://store.steampowered.com"; var GET_ITEMS = "StoreBrowse/GetItems"; var MAX_GET_URL = 7800; var MAX_GET_ITEMS = 250; var parseSortedAppIds = (items) => items.map((item) => item.appid).filter((appid) => Number.isFinite(appid)); var hasStoreItem = (item) => Boolean(item.store_item && Object.keys(item.store_item).length > 0); var fetchWishlistSortedPage = async (steamId2, country, dataRequest2, { startIndex = 0, pageSize = WISHLIST_STORE_PAGE_SIZE, shareToken = "", retry = true } = {}) => { const data = await steamRequest("Wishlist/GetWishlistSortedFiltered", { steamid: steamId2, context: { language: "schinese", country_code: country }, data_request: dataRequest2, start_index: startIndex, page_size: pageSize, share_token: shareToken || void 0 }, { details: { country, offset: startIndex, limit: pageSize }, session: Boolean(loggedInSteamId()), retry }); return data.items ?? []; }; var fillWishlistStoreItems = async (steamId2, country, dataRequest2, needed, knownCount = 0, shareToken = "") => { const storeItems = /* @__PURE__ */ new Map(); const appids = []; const listed = /* @__PURE__ */ new Set(); const tagIds = {}; let start = 0; for (let page = 0; page < 100; page++) { const remain = listed.size > 0 ? listed.size - start : 0; const pageSize = remain > 0 ? Math.min(WISHLIST_STORE_FILL_MAX, remain) : Math.min(Math.max(knownCount, WISHLIST_STORE_PAGE_SIZE), WISHLIST_STORE_FILL_MAX); if (listed.size > 0 && start >= listed.size) { break; } const items = await fetchWishlistSortedPage(steamId2, country, dataRequest2, { startIndex: start, pageSize, shareToken }); const pageIds = parseSortedAppIds(items); if (pageIds.length === 0) { break; } for (const appid of pageIds) { if (!listed.has(appid)) { listed.add(appid); appids.push(appid); } } let filled = 0; for (const item of items) { if (item.appid && (item.category_ids === void 0 || Array.isArray(item.category_ids) && item.category_ids.every((id) => typeof id === "string" && /^[1-9]\d*$/.test(id)))) { tagIds[item.appid] = [...new Set(item.category_ids ?? [])]; } if (item.appid && hasStoreItem(item) && item.store_item && !storeItems.has(item.appid)) { storeItems.set(item.appid, item.store_item); filled += 1; } } if (needed && [...needed].every((appid) => storeItems.has(appid) || listed.size > 0 && !listed.has(appid))) { break; } if (listed.size > 0 && storeItems.size >= listed.size) { break; } if (listed.size > 0 && listed.size <= pageSize) { break; } if (start > 0 && filled === 0) { break; } start += pageSize; if (start >= listed.size) { break; } } return { appids, storeItems, resolved: listed, tagIds }; }; var getItemsInput = (appids, context2, dataRequest2) => ({ ids: appids.map((appid) => ({ appid })), context: context2, data_request: dataRequest2 }); var PRICE_DATA_REQUEST = { include_all_purchase_options: true }; var chunkGetItems = (appids, context2, dataRequest2) => { const groups = []; let current = []; for (const appid of appids) { const next = current.concat(appid); const fits = next.length <= MAX_GET_ITEMS && steamUrl( GET_ITEMS, encodeSteamMessage(steamRpcs[GET_ITEMS].request, getItemsInput(next, context2, dataRequest2)) ).length <= MAX_GET_URL; if (current.length > 0 && !fits) { groups.push(current); current = [appid]; } else { current = next; } } if (current.length > 0) groups.push(current); return groups; }; var fetchStoreItems = async (appids, context2, dataRequest2) => { const response = await steamRequest( GET_ITEMS, getItemsInput(appids, context2, dataRequest2), { details: { country: context2.country_code, appCount: appids.length } } ); return response.store_items ?? []; }; var steamUrl = (method, payload) => { const url = new URL(`/um/${method}/`, STORE_ORIGIN); if (payload) url.searchParams.set("input_protobuf_encoded", btoa(String.fromCharCode(...payload))); return url.href; }; var dataSummary = (data) => { const { items, store_items, categories: categories2, wishlist_count } = data; if (wishlist_count !== void 0) return { wishlistCount: wishlist_count }; const catalog = store_items ?? items?.flatMap((item) => item.store_item ? [item.store_item] : []); const records = items ?? store_items; if (!records) return { records: categories2?.length ?? 0 }; return { records: records.length, ...catalog?.length ? { storeRecords: catalog.length } : {}, sample: (catalog?.length ? catalog : records).slice(0, 3).map((item) => ({ appid: item.appid, price: "best_purchase_option" in item ? item.best_purchase_option?.formatted_final_price : void 0 })) }; }; var steamRequest = async (method, input, { details = {}, session = false, retry = true } = {}) => { const rpc = steamRpcs[method]; const payload = encodeSteamMessage(rpc.request, input); const url = steamUrl(method, rpc.write ? void 0 : payload); const label = `${rpc.write ? "POST" : "GET"} /um/${method}/`; const attempts = rpc.write || !retry ? 1 : MAX_ATTEMPTS; for (let attempt = 0; attempt < attempts; attempt++) { const result = await queueApiRequest(url, async () => { if (attempt === 0) noteRequest(); const started = performance.now(); logWishlist("Steam 请求", { method: label, attempt: attempt + 1, ...details }); let response; try { response = await fetch(url, { method: rpc.write ? "POST" : "GET", mode: "same-origin", credentials: session ? "same-origin" : "omit", redirect: "manual", signal: AbortSignal.timeout(2e4), headers: { Accept: "application/octet-stream", ...rpc.write && { "Content-Type": "application/octet-stream" } }, ...rpc.write && { body: payload } }); } catch { logWishlist("Steam 请求失败", { method: label, elapsedMs: Math.round(performance.now() - started) }); return { retry: true, error: new Error(`Steam ${method} 请求失败或超时`) }; } const eresult = response.headers.get("x-eresult"); const status = { method: label, http: response.status, eresult, elapsedMs: Math.round(performance.now() - started), ...details }; if (!response.ok || eresult !== null && eresult !== "1" || rpc.write && eresult !== "1") { logWishlist("Steam 请求失败", status); const login = response.status === 401 || response.type === "opaqueredirect" || response.status === 302; return { retry: RETRY_STATUSES.has(response.status), error: new Error(login ? "Steam 会话不可用,请在商店登录后重试" : `Steam ${method} 失败,HTTP ${response.status}${eresult ? `,结果 ${eresult}` : ""}`) }; } try { if (!response.headers.get("content-type")?.startsWith("application/octet-stream")) { throw new Error("Steam 响应格式异常"); } const data = decodeSteamMessage(rpc.response, new Uint8Array(await response.arrayBuffer())); logWishlist("Steam 响应数据", { ...status, ...dataSummary(data) }); return { data }; } catch (error) { logWishlist("Steam 响应解析失败", status); throw error; } }); if (result.data) return result.data; if (!result.retry || attempt + 1 === attempts) throw result.error; const wait = backoffMs(attempt); logWishlist("Steam 请求重试", { method: label, waitMs: Math.round(wait) }); await sleep(wait); } throw new Error(`Steam ${method} 请求失败`); }; // src/scripts/steam-wishlist-prices/steam/wishlist-links.ts var STORE_ORIGIN2 = "https://store.steampowered.com"; var isSteamAppId = (appid) => Number.isInteger(appid) && appid > 0 && appid <= 4294967295; var steamAppUrl = (appid) => `${STORE_ORIGIN2}/app/${appid}`; var parseWishlistLinks = (input) => { const appids = /* @__PURE__ */ new Set(); const invalid = []; for (const [index, value] of input.split(/\r\n?|\n/).entries()) { const text = value.trim(); if (!text) continue; let appid = 0; try { const url = new URL(text); if (url.origin === STORE_ORIGIN2 && !url.username && !url.password) { appid = Number(url.pathname.match(/^\/app\/([1-9]\d*)(?:\/[^/]+)?\/?$/)?.[1]); } } catch { } if (isSteamAppId(appid)) appids.add(appid); else invalid.push({ line: index + 1, text }); } return { appids: [...appids], invalid }; }; // src/scripts/steam-wishlist-prices/steam/wishlist-tags.ts var cacheKey = (steamId2) => `wishlist-tags-v1:${steamId2}`; var TAG_CACHE_TTL_MS = 5 * 60 * 1e3; var categoryId = (id) => typeof id === "string" && /^[1-9]\d*$/.test(id); var parseCategories = (raw) => { if (!Array.isArray(raw)) throw new Error("Steam 标签数据格式异常"); return raw.map((item) => { if (!categoryId(item?.categoryid) || typeof item.name !== "string") throw new Error("Steam 标签数据格式异常"); return { id: item.categoryid, name: item.name }; }); }; var requireOwner = (steamId2, tags) => { if (!tags.editable || loggedInSteamId() !== steamId2) throw new Error("只能编辑当前登录账号自己的愿望单标签"); }; var persistWishlistTags = (steamId2, tags, shareToken = "", fetchedAt) => { if (tags.available && !shareToken) { fetchedAt ?? (fetchedAt = loadValue(cacheKey(steamId2), null)?.fetchedAt); saveValue(cacheKey(steamId2), { categories: tags.categories, items: tags.items, fetchedAt }); } }; var removeCachedWishlistGameTags = (steamId2, appid) => { const key = cacheKey(steamId2); const cached = loadValue(key, null); if (!cached || cached.items[appid] === void 0) return; delete cached.items[appid]; saveValue(key, cached); }; var loadWishlistTags = async (steamId2, country, shareToken = "", memberships, options = {}) => { const empty = { available: false, editable: false, categories: [], items: {}, warning: null }; let own = false; try { const viewer = loggedInSteamId(); own = !shareToken && viewer === steamId2; if (!own && !shareToken) { logWishlist("跳过愿望单标签", { reason: viewer ? "非当前账号的愿望单" : "未识别到 Steam 登录账号" }); return empty; } const cached = own ? loadValue(cacheKey(steamId2), null) : null; const age = cached?.fetchedAt == null ? Infinity : Date.now() - cached.fetchedAt; if (cached && !options.force && !memberships && age >= 0 && age < TAG_CACHE_TTL_MS) { return { ...empty, categories: cached.categories, items: cached.items, available: true, editable: true }; } const [definitions, wishlist] = await Promise.all([ steamRequest( own ? "Wishlist/GetWishlistCategories" : "Wishlist/GetSharedWishlistCategories", own ? {} : { steamid: steamId2, share_token: shareToken }, { session: Boolean(viewer), retry: false } ), // Reuse memberships from the catalog request within the same access scope. memberships ? Promise.resolve(Object.entries(memberships).map(([appid, category_ids]) => ({ appid: Number(appid), category_ids }))) : fetchWishlistSortedPage(steamId2, country, {}, { shareToken, retry: false }) ]); const categories2 = parseCategories(definitions.categories ?? []); const items = {}; for (const item of wishlist) { if (!item.appid || !Number.isSafeInteger(item.appid) || item.appid < 0 || item.category_ids !== void 0 && !item.category_ids.every(categoryId)) { throw new Error("Steam 愿望单标签数据格式异常"); } items[item.appid] = [...new Set(item.category_ids ?? [])]; } const tags = { available: true, editable: own, categories: categories2, items, warning: null }; persistWishlistTags(steamId2, tags, own ? "" : shareToken, Date.now()); return tags; } catch (error) { const cached = own ? loadValue(cacheKey(steamId2), null) : null; return { ...empty, ...cached ? { categories: cached.categories, items: cached.items, available: true } : {}, warning: error instanceof Error ? error.message : "标签读取失败" }; } }; var matchesWishlistTags = (ids, selected, excluded) => { if (selected.size === 0 && !excluded?.size) return true; if (ids === void 0) return false; if (excluded?.has("0") && ids.length === 0 || ids.some((id) => excluded?.has(id))) return false; return selected.size === 0 || selected.has("0") && ids.length === 0 || ids.some((id) => selected.has(id)); }; var saveGameTags = async (steamId2, appid, tags, edits) => { requireOwner(steamId2, tags); if (!Number.isSafeInteger(appid) || appid <= 0 || ![...edits.add, ...edits.remove].every(categoryId) || edits.create.some((name) => !name.trim() || name.length > 500)) throw new Error("标签修改内容无效"); const failures = []; const ids = new Set(tags.items[appid] ?? []); for (const id of edits.remove) { try { await steamRequest("Wishlist/RemoveWishlistItemCategory", { appid, categoryid: id }, { details: { appid }, session: true }); ids.delete(id); } catch (error) { failures.push(`移除 ${tags.categories.find((tag) => tag.id === id)?.name ?? id}:${error.message}`); } } for (const input of [...edits.add.map((id) => ({ categoryid: id })), ...edits.create.map((name) => ({ category_name: name }))]) { try { const result = await steamRequest("Wishlist/AddWishlistItemCategory", { appid, ...input }, { details: { appid }, session: true }); const [category2] = parseCategories([result]); ids.add(category2.id); const existing = tags.categories.find((tag) => tag.id === category2.id); if (existing) existing.name = category2.name; else tags.categories.push(category2); } catch (error) { failures.push(`添加 ${"category_name" in input ? input.category_name : tags.categories.find((tag) => tag.id === input.categoryid)?.name ?? input.categoryid}:${error.message}`); } } tags.items[appid] = [...ids]; persistWishlistTags(steamId2, tags); return failures; }; var renameWishlistTag = async (steamId2, tags, id, name) => { if (!categoryId(id) || !name.trim() || name.length > 500) throw new Error("标签名称无效"); requireOwner(steamId2, tags); await steamRequest("Wishlist/RenameWishlistCategory", { categoryid: id, name }, { session: true }); const category2 = tags.categories.find((tag) => tag.id === id); if (category2) category2.name = name; persistWishlistTags(steamId2, tags); }; // src/scripts/steam-wishlist-prices/steam/steam-wishlist.ts var ASSET_CDN = "https://shared.akamai.steamstatic.com/store_item_assets/"; var CATALOG_REQUEST = { include_basic_info: true, include_release: true, include_assets: true, include_all_purchase_options: true }; var unixTime = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null; var assetUrl = (assets2, file) => { if (!assets2?.asset_url_format || !file) return ""; return `${ASSET_CDN}${assets2.asset_url_format.replace("${FILENAME}", file)}`; }; var hashedCapsule = (url) => /store_item_assets\/steam\/apps\/\d+\/[a-f0-9]{8,}\//i.test(url); var capsuleOf = (_appid, assets2) => assetUrl(assets2, assets2?.small_capsule) || assetUrl(assets2, assets2?.header) || assetUrl(assets2, assets2?.main_capsule) || ""; var parseAppIds = (items) => (items ?? []).map((item) => item.appid).filter((appid) => Number.isFinite(appid)); var catalogFromStoreItem = (appid, item) => { const id = item.appid && item.appid > 0 ? item.appid : appid; const restricted = item.unvailable_for_country_restriction === true; const delisted = !restricted && (item.visible === false || !item.appid || item.success !== 1); return { title: item.name?.trim() || `App ${id}`, comingSoon: item.release?.is_coming_soon === true, releasedAt: unixTime(item.release?.steam_release_date) ?? unixTime(item.release?.original_release_date), free: item.is_free === true, delisted, capsule: capsuleOf(id, item.assets) }; }; var fetchWishlistIds = async (steamId2) => { const data = await steamRequest( "Wishlist/GetWishlist", { steamid: steamId2 }, { session: Boolean(loggedInSteamId()) } ); return parseAppIds(data.items); }; var fetchWishlistAppIds = async (steamId2, shareToken = "") => { if (shareToken) { const { appids: appids2 } = await fillWishlistStoreItems(steamId2, wishlistPageCountry(), {}, void 0, 0, shareToken); return appids2; } const appids = await fetchWishlistIds(steamId2); if (appids.length === 0 && loggedInSteamId() !== steamId2) throw new Error("愿望单为空或未公开"); return appids; }; var importWishlistGames = async (steamId2, appids, progress) => { const requireOwner2 = () => { if (loggedInSteamId() !== steamId2) throw new Error("只能导入到当前登录账号的愿望单"); }; requireOwner2(); const requested = [...new Set(appids)]; if (!requested.every(isSteamAppId)) throw new Error("Steam 游戏 ID 无效"); const existing = new Set(await fetchWishlistIds(steamId2)); const added = []; const failed = []; let skipped = 0; let wishlistCount = existing.size; for (const [index, appid] of requested.entries()) { if (existing.has(appid)) { skipped += 1; } else { try { requireOwner2(); const result = await steamRequest("Wishlist/AddToWishlist", { appid }, { session: true, details: { appid } }); wishlistCount = result.wishlist_count ?? wishlistCount + 1; added.push(appid); } catch (error) { failed.push({ appid, reason: error instanceof Error ? error.message : String(error) }); } } progress(index + 1); } if (added.length) { try { expireCachedWishlist(steamId2); } catch { logWishlist("愿望单缓存更新失败"); } } return { added, skipped, failed, wishlistCount }; }; var removeWishlistGame = async (steamId2, appid) => { if (loggedInSteamId() !== steamId2) throw new Error("只能从当前登录账号的愿望单移除游戏"); if (!isSteamAppId(appid)) throw new Error("Steam 游戏 ID 无效"); const result = await steamRequest("Wishlist/RemoveFromWishlist", { appid }, { session: true, details: { appid } }); try { removeCachedWishlistGame(steamId2, appid); removeCachedWishlistGameTags(steamId2, appid); } catch { logWishlist("愿望单缓存更新失败", { appid }); } return result.wishlist_count; }; var mergeCatalog = (base, extra) => { for (const [appid, item] of extra) { const current = base.get(appid); if (!current) { base.set(appid, item); continue; } if (current.delisted && !item.delisted) { base.set(appid, { title: current.title === `App ${appid}` ? item.title : current.title, comingSoon: current.comingSoon || item.comingSoon, releasedAt: current.releasedAt ?? item.releasedAt, free: current.free || item.free, delisted: false, capsule: hashedCapsule(current.capsule) ? current.capsule : item.capsule || current.capsule }); continue; } if (!current.delisted && item.delisted) { continue; } base.set(appid, { title: current.title === `App ${appid}` ? item.title : current.title, comingSoon: current.comingSoon || item.comingSoon, releasedAt: current.releasedAt ?? item.releasedAt, free: current.free || item.free, delisted: current.delisted && item.delisted, capsule: hashedCapsule(current.capsule) ? current.capsule : item.capsule || current.capsule }); } }; var mergeAppIds = (appids, extra) => { const seen = new Set(appids); for (const appid of extra) { if (!seen.has(appid)) { seen.add(appid); appids.push(appid); } } }; var isPricedGame = (game) => !game.delisted && !game.comingSoon && !game.free; var loadSteamWishlist = async (steamId2, home, pageCount = null, countries = [home], knownAppids, shareToken = "") => { const viewer = loggedInSteamId(); const key = wishlistCacheKey(steamId2, home, viewer); const state = shareToken ? { games: null, refresh: true } : wishlistCacheState(steamId2, home, pageCount, viewer); if (!state.refresh && state.games) { return { games: state.games, refreshed: false, addedAppids: [], countryItems: /* @__PURE__ */ new Map() }; } const appids = knownAppids ? [...knownAppids] : shareToken ? [] : await fetchWishlistAppIds(steamId2); if (appids.length === 0 && !shareToken && viewer === steamId2) { cacheSet(key, []); return { games: [], refreshed: true, countryItems: /* @__PURE__ */ new Map(), addedAppids: [] }; } const filled = await fillWishlistStoreItems(steamId2, home, CATALOG_REQUEST, void 0, pageCount ?? appids.length, shareToken); mergeAppIds(appids, filled.appids); const countryItems = /* @__PURE__ */ new Map([[home, filled.storeItems]]); const catalog = new Map([...filled.storeItems].map(([appid, item]) => [appid, catalogFromStoreItem(appid, item)])); const missingMetadata = appids.some((appid) => { const item = catalog.get(appid); return !item || item.delisted || item.title === `App ${appid}` || !item.capsule || item.releasedAt === null && !item.comingSoon; }); if (missingMetadata) { const regions = [...new Set(countries)].filter((country) => country !== home); const extras = await Promise.all(regions.map((country) => fillWishlistStoreItems(steamId2, country, CATALOG_REQUEST, void 0, appids.length, shareToken))); for (const [index, extra] of extras.entries()) { countryItems.set(regions[index], extra.storeItems); mergeCatalog(catalog, new Map([...extra.storeItems].map(([appid, item]) => [appid, catalogFromStoreItem(appid, item)]))); } } const games = appids.map((appid) => { const item = catalog.get(appid); return { appid, title: item?.title ?? `App ${appid}`, comingSoon: item?.comingSoon ?? false, releasedAt: item?.releasedAt ?? null, free: item?.free ?? false, delisted: item?.delisted ?? true, capsule: item?.capsule ?? capsuleOf(appid) }; }); const previousIds = new Set(state.games?.map((game) => game.appid)); if (!shareToken) cacheSet(key, games); return { games, refreshed: true, countryItems, tagIds: filled.tagIds, addedAppids: games.filter((game) => isPricedGame(game) && !previousIds.has(game.appid)).map((game) => game.appid) }; }; // src/scripts/steam-wishlist-prices/ui/icons.ts var closeIcon = ``; // src/scripts/steam-wishlist-prices/ui/dialog.ts var dialogHeader = (id, titleHtml) => `

${titleHtml}

`; // src/scripts/steam-wishlist-prices/ui/wishlist-removal.ts var copy = { title: "移除愿望单游戏", action: "从愿望单移除", question: "确定将这款游戏从 Steam 愿望单移除吗?", cancel: "取消", remove: "移除", removing: "移除中…", failed: "移除失败,请重试" }; var wishlistRemoveLabel = copy.action; var wishlistRemovalDialogHtml = () => `
${dialogHeader("wishlist-removal-title", copy.title)}

${copy.question}

`; var mountWishlistRemoval = (root, payload, render) => { const dialog = root.querySelector("#wishlist-removal"); if (!dialog) return; const form = dialog.querySelector("form"); const gameTitle = dialog.querySelector("#wishlist-removal-game"); const errorText = dialog.querySelector(".wl-wishlist-removal-error"); const confirm = dialog.querySelector("[data-dialog-confirm]"); const cancel = dialog.querySelector("[autofocus]"); const close = dialog.querySelector("[data-dialog-close]"); let appid = 0; close.addEventListener("click", () => dialog.close()); root.querySelector("#list")?.addEventListener("click", (event) => { const trigger = event.target.closest("[data-wishlist-remove-appid]"); if (!trigger || dialog.open) return; const game = payload.rows.find((row) => row.appid === Number(trigger.dataset.wishlistRemoveAppid)); if (!game) return; appid = game.appid; gameTitle.textContent = game.title; errorText.textContent = ""; dialog.showModal(); cancel.focus(); }); dialog.addEventListener("cancel", (event) => { if (confirm.disabled) event.preventDefault(); }); form.addEventListener("submit", async (event) => { if (event.submitter !== confirm) return; event.preventDefault(); if (!dialog.open || confirm.disabled) return; confirm.disabled = cancel.disabled = close.disabled = true; confirm.textContent = copy.removing; errorText.textContent = ""; try { const remaining = await removeWishlistGame(payload.steamId, appid); payload.rows = payload.rows.filter((row) => row.appid !== appid); payload.wishlistCount = remaining ?? payload.rows.length; if (payload.tags) delete payload.tags.items[appid]; } catch (error) { errorText.textContent = error instanceof Error ? error.message : copy.failed; return; } finally { confirm.disabled = cancel.disabled = close.disabled = false; confirm.textContent = copy.remove; } dialog.close(); render(); root.querySelector("#q")?.focus(); }); }; // src/scripts/steam-wishlist-prices/ui/wishlist-tags.ts var tagEscape = (text) => text.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); var filterIcon = (kind) => ``; var toggleTagFilter = (selected, excluded, id, exclude) => { const active = exclude ? excluded : selected; const other = exclude ? selected : excluded; other.delete(id); if (active.has(id)) active.delete(id); else active.add(id); }; var tagControlsHtml = () => `
`; var mountWishlistTagControls = (root, payload, changed) => { const find = (id) => root.querySelector(`#${id}`); const selected = /* @__PURE__ */ new Set(); const excluded = /* @__PURE__ */ new Set(); let busy = false; let dialog = null; const names = () => payload.tags?.categories ?? []; const renderMenu = () => { const tags = payload.tags; find("tags-controls").classList.toggle("hidden", !tags?.available && !tags?.warning); find("tags-manage").classList.toggle("hidden", !tags?.editable); const query = find("tags-search").value.trim().toLocaleLowerCase(); const options = [{ id: "0", name: "未分类" }, ...names()]; const counts = /* @__PURE__ */ new Map(); for (const row of payload.rows) { const ids = tags?.items[row.appid]; if (!ids) continue; for (const id of ids.length ? ids : ["0"]) counts.set(id, (counts.get(id) ?? 0) + 1); } find("tags-options").innerHTML = tags?.available ? options.filter((tag) => tag.name.toLocaleLowerCase().includes(query)).map((tag) => `
`).join("") || `

没有匹配的标签

` : ""; find("tags-menu-btn").textContent = excluded.size > 0 ? `标签:${selected.size ? `含 ${selected.size} / ` : ""}排除 ${excluded.size} ▾` : selected.size === 0 ? "标签:全部 ▾" : selected.size === 1 ? `标签:${options.find((tag) => selected.has(tag.id))?.name ?? "已选择"} ▾` : `标签:${selected.size} 个 ▾`; find("tags-message").textContent = tags?.warning ? `${tags.warning}${tags.available ? ",当前显示缓存;刷新成功后可编辑。" : ""}` : ""; }; const close = () => { dialog?.remove(); dialog = null; find("tags-menu-btn").focus(); }; const open = (title) => { close(); find("tags-menu-panel").classList.add("hidden"); find("tags-menu-btn").setAttribute("aria-expanded", "false"); dialog = document.createElement("div"); dialog.className = "wl-dialog-backdrop"; dialog.innerHTML = ``; find("tags-controls").appendChild(dialog); dialog.querySelector("[data-dialog-close]").addEventListener("click", () => { if (!busy) close(); }); dialog.addEventListener("click", (event) => { if (event.target === dialog && !busy) close(); }); dialog.addEventListener("keydown", (event) => { if (event.key === "Escape") { event.stopPropagation(); if (!busy) close(); } if (event.key === "Tab") { const targets = Array.from(dialog.querySelectorAll("button:not(:disabled), input:not(:disabled)")); const focused = dialog.getRootNode() instanceof ShadowRoot ? dialog.getRootNode().activeElement : document.activeElement; if (event.shiftKey && focused === targets[0]) { event.preventDefault(); targets[targets.length - 1]?.focus(); } else if (!event.shiftKey && focused === targets[targets.length - 1]) { event.preventDefault(); targets[0]?.focus(); } } }); return dialog.querySelector("#tag-dialog-body"); }; const setBusy = (value) => { busy = value; for (const control of Array.from(dialog.querySelectorAll("input, button"))) control.disabled = value; }; const editGame = (appid) => { const tags = payload.tags; if (!tags?.editable || tags.items[appid] === void 0 || busy) return; const row = payload.rows.find((item) => item.appid === appid); const body = open(`管理“${row?.title ?? appid}”的类别`); let original = new Set(tags.items[appid]); let picked = new Set(original); let created = []; body.innerHTML = `

当前类别

我的其他类别

`; body.parentElement.insertAdjacentHTML("beforeend", `
`); const get = (id) => body.querySelector(`#${id}`); const message = () => dialog.querySelector("#tag-dialog-message"); const sync = () => { const name = get("tag-edit-search").value.trim(); const query = name.toLocaleLowerCase(); get("tag-current").innerHTML = names().filter((tag) => picked.has(tag.id)).map((tag) => ``).join("") + created.map((name2, index) => ``).join("") || `

无

`; get("tag-edit-options").innerHTML = names().filter((tag) => !picked.has(tag.id) && tag.name.toLocaleLowerCase().includes(query)).map((tag) => ``).join("") || `

${query ? "没有匹配的类别" : "暂无其他类别"}

`; get("tag-create").classList.toggle("hidden", !name || names().some((tag) => tag.name.toLocaleLowerCase() === query) || created.some((value) => value.toLocaleLowerCase() === query)); get("tag-create").textContent = `+ 添加“${name}”`; }; get("tag-edit-search").addEventListener("input", sync); body.addEventListener("click", (event) => { const button = event.target.closest("[data-tag-pick], [data-new-remove]"); if (!button || busy) return; if (button.dataset.newRemove !== void 0) created.splice(Number(button.dataset.newRemove), 1); else { const id = button.dataset.tagPick; if (picked.has(id)) picked.delete(id); else { picked.add(id); get("tag-edit-search").value = ""; } } sync(); }); const addName = () => { const input = get("tag-edit-search"); const name = input.value.trim(); if (!name || busy) return; const existing = names().find((tag) => tag.name.toLocaleLowerCase() === name.toLocaleLowerCase()); if (existing) picked.add(existing.id); else if (!created.some((value) => value.toLocaleLowerCase() === name.toLocaleLowerCase())) created.push(name); input.value = ""; sync(); }; get("tag-create").addEventListener("click", addName); get("tag-edit-search").addEventListener("keydown", (event) => { if (event.key === "Enter" && !event.isComposing) { event.preventDefault(); addName(); } }); dialog.querySelector("#tag-save").addEventListener("click", async () => { if (busy) return; if (picked.size + created.length > 16) { message().textContent = "每款游戏最多 16 个标签"; return; } setBusy(true); message().textContent = "正在保存…"; try { const failures = await saveGameTags(payload.steamId, appid, tags, { add: [...picked].filter((id) => !original.has(id)), remove: [...original].filter((id) => !picked.has(id)), create: created }); renderMenu(); changed(); if (!failures.length) close(); else { original = new Set(tags.items[appid]); picked = new Set(original); created = []; sync(); message().textContent = `部分修改未保存:${failures.join(";")}`; } } catch (error) { message().textContent = error.message; } finally { if (dialog) setBusy(false); else busy = false; } }); sync(); get("tag-edit-search").focus(); }; const refreshTags = async () => { const button = find("tags-refresh"); button.disabled = true; button.textContent = "读取中…"; try { payload.tags = await loadWishlistTags(payload.steamId, payload.home, payload.tagShareToken, void 0, { force: true }); if (payload.tags.available) for (const filters of [selected, excluded]) { for (const id of filters) if (id !== "0" && !names().some((tag) => tag.id === id)) filters.delete(id); } renderMenu(); changed(); } finally { button.disabled = false; button.textContent = "刷新"; } }; find("tags-manage").addEventListener("click", () => { if (!payload.tags?.editable || busy) return; const body = open("管理标签"); body.innerHTML = names().map((tag) => `
`).join("") || `

先在游戏的编辑标签中创建标签

`; body.addEventListener("submit", async (event) => { event.preventDefault(); const form = event.target; const id = form.dataset.tagRename; const name = form.querySelector("input").value.trim(); if (!id || !name || busy) return; setBusy(true); const message = dialog.querySelector("#tag-dialog-message"); message.textContent = "正在保存…"; try { await renameWishlistTag(payload.steamId, payload.tags, id, name); renderMenu(); changed(); message.textContent = ""; } catch (error) { message.textContent = error.message; } finally { setBusy(false); } }); body.querySelector("input")?.focus(); }); find("tags-menu-btn").addEventListener("click", (event) => { event.stopPropagation(); const panel = find("tags-menu-panel"); panel.classList.toggle("hidden"); find("tags-menu-btn").setAttribute("aria-expanded", String(!panel.classList.contains("hidden"))); if (!panel.classList.contains("hidden")) find("tags-search").focus(); }); find("tags-menu-panel").addEventListener("click", (event) => event.stopPropagation()); root.addEventListener("click", () => { find("tags-menu-panel").classList.add("hidden"); find("tags-menu-btn").setAttribute("aria-expanded", "false"); }); find("tags-search").addEventListener("input", renderMenu); find("tags-options").addEventListener("click", (event) => { const button = event.target.closest("[data-tag-filter], [data-tag-exclude]"); if (!button) return; const id = button.dataset.tagExclude ?? button.dataset.tagFilter; toggleTagFilter(selected, excluded, id, button.dataset.tagExclude !== void 0); renderMenu(); changed(); }); find("tags-clear").addEventListener("click", () => { selected.clear(); excluded.clear(); renderMenu(); changed(); }); find("tags-refresh").addEventListener("click", async () => { if (busy) return; busy = true; try { await refreshTags(); } finally { busy = false; } }); find("list").addEventListener("click", (event) => { const button = event.target.closest("[data-game-tag], [data-edit-tags]"); if (!button) return; if (button.dataset.editTags) editGame(Number(button.dataset.editTags)); else { toggleTagFilter(selected, excluded, button.dataset.gameTag, false); renderMenu(); changed(); } }); renderMenu(); return { matches: (appid) => matchesWishlistTags(payload.tags?.items[appid], selected, excluded) }; }; // src/scripts/steam-wishlist-prices/ui/wishlist-transfer.ts var promptExample = [17410, 220, 620].map(steamAppUrl).join("\n\n"); var wishlistTransferCopy = { importEntry: "导入", exportEntry: "导出", exportDialog: "导出愿望单", importTitle: "导入到我的愿望单", importAction: "导入愿望单", aiPrompt: "AI 提示词", copyPrompt: "复制提示词", prompt: `根据我提供的游戏名称、文字清单、已有链接或截图,整理 Steam 商店游戏链接。 请核对游戏名称和版本,先确认每个 App ID 对应正确的 Steam 商店页面。不确定的游戏直接跳过,不要猜测或编造链接。对相同的 App ID 去重,保留首次出现的顺序。 回复只包含纯文本链接。每个完整的 https://store.steampowered.com/app/ 链接独占一行,相邻链接之间留一个空行。回复直接从第一条链接开始,到最后一条链接结束。 下面三条链接仅用于演示输出格式: ${promptExample}`, exportTitle: "导出愿望单链接", copyLinks: "复制链接", copyFallback: "已选中文本,可手动复制。", noLinks: "请粘贴至少一条 Steam 商店链接。", invalidLines: (lines) => `无法识别第 ${lines} 行。`, progress: (done, total) => `正在导入 ${done} / ${total}…`, result: (added, skipped, failed) => `已导入 ${added} 款,已在愿望单 ${skipped} 款,失败 ${failed} 款。`, close: "关闭", done: "完成并刷新" }; var copy2 = wishlistTransferCopy; var openWishlistTransfer = (trigger, payload, mode, onImported) => { const importing = mode === "import"; if (importing && !payload.canEditWishlist) return; const dialog = document.createElement("dialog"); dialog.className = "wl-dialog wl-transfer-dialog"; dialog.setAttribute("aria-labelledby", "wl-transfer-title"); dialog.innerHTML = ` ${dialogHeader("wl-transfer-title", importing ? copy2.importAction : copy2.exportDialog)}
${importing ? `

${copy2.aiPrompt}
` : ` `}

`; const get = (selector) => dialog.querySelector(selector); const closeIcon2 = get("[data-dialog-close]"); const closeButton = get("#wl-transfer-close"); let busy = false; let importedCount; closeIcon2.addEventListener("click", () => dialog.close()); dialog.addEventListener("cancel", (event) => { if (busy) event.preventDefault(); }); dialog.addEventListener("close", () => { dialog.remove(); trigger.focus(); if (importedCount !== void 0) onImported?.(importedCount); }); dialog.querySelectorAll("[data-copy]").forEach((button) => { button.addEventListener("click", async () => { const textarea = get(`#wl-transfer-${button.dataset.copy}`); const status = get("#wl-transfer-copy-status"); try { await navigator.clipboard.writeText(textarea.value); status.textContent = ""; } catch { textarea.focus(); textarea.select(); status.textContent = copy2.copyFallback; } }); }); if (importing) { const form = get("#wl-transfer-import"); const input = get("#wl-transfer-input"); const submit = get("#wl-transfer-submit"); const status = form.querySelector("[role=status]"); const invalidLines = (rows) => rows.length ? copy2.invalidLines(rows.map((row) => row.line).join(", ")) : ""; const syncActions = () => { const parsed = parseWishlistLinks(input.value); const readyToRefresh = importedCount !== void 0 && parsed.appids.length === 0 && !busy; submit.disabled = busy || parsed.appids.length === 0; submit.hidden = readyToRefresh; closeButton.classList.toggle("is-primary", readyToRefresh); return parsed; }; get("#wl-transfer-prompt").value = copy2.prompt; input.addEventListener("input", () => { const { appids, invalid } = syncActions(); status.textContent = appids.length ? "" : invalidLines(invalid); }); form.addEventListener("submit", async (event) => { event.preventDefault(); if (busy) return; const { appids: requested, invalid } = syncActions(); const invalidMessage = invalidLines(invalid); if (!requested.length) { status.textContent = invalidMessage || copy2.noLinks; return; } busy = input.readOnly = submit.disabled = closeIcon2.disabled = closeButton.disabled = true; status.textContent = copy2.progress(0, requested.length); try { const result = await importWishlistGames(payload.steamId, requested, (done) => { status.textContent = copy2.progress(done, requested.length); }); if (result.added.length) { importedCount = result.wishlistCount; closeButton.textContent = copy2.done; } input.value = [...invalid.map((row) => row.text), ...result.failed.map((row) => steamAppUrl(row.appid))].join("\n"); status.textContent = [ copy2.result(result.added.length, result.skipped, result.failed.length), invalidMessage, ...result.failed.map(({ appid, reason }) => `${appid} · ${reason}`) ].filter(Boolean).join("\n"); } catch (error) { status.textContent = error instanceof Error ? error.message : String(error); } finally { busy = input.readOnly = closeIcon2.disabled = closeButton.disabled = false; syncActions(); } }); } else { const appids = [...new Set(payload.rows.map((row) => row.appid))]; get("#wl-transfer-export").value = appids.map(steamAppUrl).join("\n"); get('[data-copy="export"]').disabled = appids.length === 0; } trigger.closest(".wl-app").appendChild(dialog); dialog.showModal(); }; // src/scripts/steam-wishlist-prices/ui/report-html.ts var fmtWhen = (iso) => { const date = new Date(iso); if (Number.isNaN(date.getTime())) { return iso; } return date.toLocaleString("zh-CN", { hour12: false, timeZone: "Asia/Shanghai" }); }; var escapeHtml = (value) => value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); var reportSummaryCopy = { group: "比价统计", games: "显示游戏", current: "本区总价", regular: "原价总额", history: "史低总价", missingPrice: (count) => `${count} 款无价格`, missingHistory: (count) => `${count} 款无史低`, itadDisabled: "ITAD 未启用" }; var renderReportMetrics = (metrics) => ({ html: metrics.map(({ kind, value, suffix, detail }) => `
${reportSummaryCopy[kind]}
${escapeHtml(value)}${suffix ? ` ${escapeHtml(suffix)}` : ""}
${detail ? `
${escapeHtml(detail)}
` : ""}
`).join(""), text: metrics.map(({ kind, value, suffix, detail }) => [reportSummaryCopy[kind], value, suffix, detail ? `· ${detail}` : ""].filter(Boolean).join(" ")).join(" · ") }); var filterToggle = (id, label, tip = "") => `${tip ? `${escapeHtml(tip)}` : ""}`; var renderReportShell = (payload) => { const fetched = new Set(payload.countries.map((country) => country.code)); const regionItems = COUNTRIES.map((country) => { const locked = country.code === payload.home; const on = fetched.has(country.code) || locked; return ``; }).join(""); const name = escapeHtml(payload.steamName || payload.steamId); const href = `https://store.steampowered.com/wishlist/profiles/${encodeURIComponent(payload.steamId)}/`; return `

Steam ${name}${escapeHtml(payload.steamId)} 愿望单 当前账户区域
${payload.canEditWishlist ? `` : ""}

生成于 ${fmtWhen(payload.generatedAt)} · 汇率 ${fmtWhen(payload.fxAt)}

绿色最低价 · 浅蓝最低价 +≤10% · 可送礼相对当前账户区域差价 ≤10%

${payload.tags ? tagControlsHtml() : ""}
${filterToggle("sale", "折扣")} ${payload.itad?.enabled ? filterToggle("history-low", "史低", "本区已达史低,包含新史低。ITAD 的新史低识别不完全准确,部分新史低可能仅标记为史低。") + filterToggle("new-low", "新史低", "本区现价低于 ITAD 史低,或 ITAD 报价标记为新史低且与现价一致。识别结果不完全准确,部分新史低可能仅标记为史低,不会出现在此筛选中。") : ""}
${filterToggle("missing", "锁区")} ${filterToggle("gift", "可赠礼")} ${filterToggle("soon", "屏蔽未发售")}
${payload.canEditWishlist ? wishlistRemovalDialogHtml() : ""}
`; }; // src/scripts/steam-wishlist-prices/pricing/itad-prices.ts var API = "https://api.isthereanydeal.com"; var STEAM_SHOP = 61; var BATCH_SIZE = 200; var HOUR = 60 * 60 * 1e3; var ID_CACHE_KEY = "wishlist-itad-ids-v1"; var LOW_CACHE_PREFIX = "wishlist-itad-steam-low-v1:"; var DEAL_CACHE_PREFIX = "wishlist-itad-steam-deal-v1:"; var API_KEY_STORAGE = "wishlist-itad-api-key-v1"; var HOME_STORAGE = "wishlist-itad-home-v1"; var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; var loadItadApiKey = () => loadValue(API_KEY_STORAGE, "").trim(); var saveItadApiKey = (key) => saveValue(API_KEY_STORAGE, key.trim()); var syncItadHome = (home) => { const previous = loadValue(HOME_STORAGE, null); if (previous === home) return; if (previous !== null) { for (const country of [previous, home]) { saveValue(`${LOW_CACHE_PREFIX}${country}`, {}); saveValue(`${DEAL_CACHE_PREFIX}${country}`, {}); } } saveValue(HOME_STORAGE, home); }; var fresh = (hit, ttl) => !!hit && Date.now() - hit.savedAt >= 0 && Date.now() - hit.savedAt < ttl; var needsRefresh = (hit, current) => !fresh(hit, HOUR) || !!current && (hit.checkedPrice?.currency !== current.currency || hit.checkedPrice.amount !== current.amount); var checkedPrice = (current) => current ? { amount: current.amount, currency: current.currency, discountEndsAt: current.discountEndsAt } : void 0; var sameOffer = (previous, current) => previous.currency === current.currency && previous.amount === current.amount && (previous.discountEndsAt === void 0 || current.discountEndsAt === void 0 || previous.discountEndsAt === current.discountEndsAt) && (current.discountEndsAt == null || current.discountEndsAt > Date.now()); var clearChangedQuotes = (country, prices) => { const key = `${DEAL_CACHE_PREFIX}${country}`; const bucket = loadValue(key, {}); let changed = false; for (const [id, current] of prices) { const hit = bucket[id]; const previous = hit?.checkedPrice ?? hit?.value; if (previous && !sameOffer(previous, current)) { delete bucket[id]; changed = true; } } if (changed) saveValue(key, bucket); }; var chunks = (items) => { const result = []; for (let i = 0; i < items.length; i += BATCH_SIZE) result.push(items.slice(i, i + BATCH_SIZE)); return result; }; var ItadError = class extends Error { constructor(status, message) { super(message); this.status = status; } }; var apiPost = (path, body, apiKey) => queueApiRequest(`${API}${path}`, () => sendItadPost(path, body, apiKey)); var sendItadPost = async (path, body, apiKey) => { noteRequest(); const options = { method: "POST", url: `${API}${path}`, headers: { "Content-Type": "application/json", "ITAD-API-Key": apiKey }, data: JSON.stringify(body) }; let response; const details = { method: `POST ${path.split("?")[0]}`, records: body.length }; logWishlist("ITAD 请求", details); try { if (typeof GM_xmlhttpRequest === "function") { response = await new Promise((resolve, reject) => { GM_xmlhttpRequest({ ...options, anonymous: true, timeout: 2e4, onload: resolve, onerror: () => reject(new Error()), ontimeout: () => reject(new Error()), onabort: () => reject(new Error()) }); }); } else { const res = await fetch(options.url, { method: options.method, headers: options.headers, body: options.data, credentials: "omit", signal: AbortSignal.timeout(2e4) }); response = { status: res.status, responseText: await res.text() }; } } catch { logWishlist("ITAD 请求失败", details); throw new ItadError(0, "ITAD 请求失败或超时"); } if (response.status < 200 || response.status >= 300) { logWishlist("ITAD 请求失败", { ...details, http: response.status }); const message = response.status === 401 || response.status === 403 ? "ITAD API Key 无效或无权访问,请检查设置" : response.status === 429 ? "ITAD 请求已达限额,请稍后重试" : `ITAD 请求失败(HTTP ${response.status})`; throw new ItadError(response.status, message); } try { const data = JSON.parse(response.responseText); logWishlist("ITAD 响应数据", { method: details.method, http: response.status, records: data && typeof data === "object" ? Object.keys(data).length : 0 }); return data; } catch { logWishlist("ITAD 响应解析失败", { ...details, http: response.status }); throw new ItadError(0, "ITAD 返回的数据格式异常"); } }; var lookupIds = async (appids, apiKey, plan) => { const bucket = loadValue(ID_CACHE_KEY, {}); const pending = appids.filter((appid) => { const hit = bucket[appid]; return !fresh(hit, hit?.value ? 30 * 24 * HOUR : 24 * HOUR); }); const batches = chunks(pending); plan(batches.length); for (const batch of batches) { const raw = await apiPost(`/lookup/id/shop/${STEAM_SHOP}/v1`, batch.map((id) => `app/${id}`), apiKey); if (!raw || typeof raw !== "object" || Array.isArray(raw)) { throw new ItadError(0, "ITAD 游戏映射格式异常"); } const data = raw; for (const appid of batch) { const id = data[`app/${appid}`]; if (id !== null && (typeof id !== "string" || !UUID.test(id))) { throw new ItadError(0, "ITAD 游戏映射缺失或格式异常"); } } for (const appid of batch) { const value = data[`app/${appid}`]; bucket[appid] = { savedAt: Date.now(), value: value ?? bucket[appid]?.value ?? null }; } saveValue(ID_CACHE_KEY, bucket); } return new Map(appids.map((appid) => [appid, bucket[appid]?.value ?? null])); }; var parseLow = (raw, country) => { if (!raw || typeof raw !== "object") return null; const low = raw; if (low.shop?.id !== STEAM_SHOP || typeof low.price?.amount !== "number" || !Number.isFinite(low.price.amount) || low.price.amount < 0 || typeof low.price.currency !== "string" || !/^[A-Z]{3}$/.test(low.price.currency)) return null; return { amount: low.price.amount, currency: low.price.currency, recordedAt: typeof low.timestamp === "string" && Number.isFinite(Date.parse(low.timestamp)) ? low.timestamp : null, country }; }; var readLows = (ids, country) => { const bucket = loadValue(`${LOW_CACHE_PREFIX}${country}`, {}); return new Map(ids.map((id) => [id, bucket[id]?.value ?? null])); }; var fetchLows = async (ids, country, apiKey, plan, currentPrices) => { const key = `${LOW_CACHE_PREFIX}${country}`; const bucket = loadValue(key, {}); const batches = chunks(ids.filter((id) => needsRefresh(bucket[id], currentPrices.get(id)))); plan(batches.length); for (const batch of batches) { const raw = await apiPost(`/games/storelow/v2?country=${encodeURIComponent(country)}&shops=${STEAM_SHOP}`, batch, apiKey); if (!Array.isArray(raw) || raw.some((item) => !item || typeof item.id !== "string" || !Array.isArray(item.lows))) { throw new ItadError(0, "ITAD 史低数据格式异常"); } const data = new Map(raw.map((item) => [item.id, item.lows])); for (const id of batch) { const value = (data.get(id) ?? []).map((low) => parseLow(low, country)).find((low) => low !== null) ?? null; const previous = bucket[id]?.value; const minimum = previous && (!value || previous.currency === value.currency && previous.amount <= value.amount) ? previous : value; bucket[id] = { savedAt: Date.now(), value: minimum, checkedPrice: checkedPrice(currentPrices.get(id)) }; } saveValue(key, bucket); } }; var parseDeal = (raw, country) => { const price = parseLow(raw, country); if (!price) return null; const flag = raw.flag; return { amount: price.amount, currency: price.currency, country, flag: flag === "N" || flag === "H" || flag === "S" ? flag : null }; }; var fetchDeals = async (ids, country, apiKey, plan, currentPrices) => { const key = `${DEAL_CACHE_PREFIX}${country}`; const bucket = loadValue(key, {}); const batches = chunks(ids.filter((id) => needsRefresh(bucket[id], currentPrices.get(id)))); plan(batches.length); for (const batch of batches) { const raw = await apiPost(`/games/prices/v3?country=${encodeURIComponent(country)}&shops=${STEAM_SHOP}`, batch, apiKey); if (!Array.isArray(raw) || raw.some((item) => !item || typeof item.id !== "string" || !Array.isArray(item.deals))) { throw new ItadError(0, "ITAD 报价标记格式异常"); } const data = new Map(raw.map((item) => [item.id, item.deals])); for (const id of batch) { const value = (data.get(id) ?? []).map((deal) => parseDeal(deal, country)).find((deal) => deal !== null) ?? null; bucket[id] = { savedAt: Date.now(), value, checkedPrice: checkedPrice(currentPrices.get(id)) }; } saveValue(key, bucket); } }; var loadItadSteamLows = async (appids, home, apiKey = loadItadApiKey(), plan = () => { }, currentPrices = /* @__PURE__ */ new Map()) => { syncItadHome(home); const result = { enabled: !!apiKey, home, lows: /* @__PURE__ */ new Map(), deals: /* @__PURE__ */ new Map(), warning: null }; if (!apiKey || appids.length === 0) return result; const warnings = /* @__PURE__ */ new Set(); let blocked = false; const handle = (error) => { warnings.add(error instanceof Error ? error.message : "ITAD 查询失败"); if (error instanceof ItadError && [401, 403, 429].includes(error.status)) blocked = true; }; const unique = [...new Set(appids)]; const cachedMapping = loadValue(ID_CACHE_KEY, {}); const cachedLows = loadValue(`${LOW_CACHE_PREFIX}${home}`, {}); const pending = unique.filter((appid) => { const id = cachedMapping[appid]?.value; const low = id ? cachedLows[id]?.value : null; const current = currentPrices.get(appid); return !low || !current || current.currency !== low.currency || current.amount < low.amount; }); let mapping; try { const queried = await lookupIds(pending, apiKey, plan); mapping = new Map(unique.map((appid) => [appid, queried.has(appid) ? queried.get(appid) : cachedMapping[appid]?.value ?? null])); } catch (error) { handle(error); const cached = loadValue(ID_CACHE_KEY, {}); mapping = new Map(unique.map((appid) => [appid, cached[appid]?.value ?? null])); } const ids = [...new Set([...mapping.values()].filter((id) => id !== null))]; const pendingIds2 = [...new Set(pending.map((appid) => mapping.get(appid)).filter((id) => !!id))]; const pricesById = /* @__PURE__ */ new Map(); for (const appid of unique) { const id = mapping.get(appid); const current = currentPrices.get(appid); if (id && current) pricesById.set(id, current); } clearChangedQuotes(home, pricesById); if (!blocked) { try { await fetchLows(pendingIds2, home, apiKey, plan, pricesById); } catch (error) { handle(error); } } if (!blocked) { try { await fetchDeals(pendingIds2, home, apiKey, plan, pricesById); } catch (error) { handle(error); } } const homeLows = readLows(ids, home); const homeDeals = loadValue(`${DEAL_CACHE_PREFIX}${home}`, {}); for (const [appid, id] of mapping) { const low = id ? homeLows.get(id) : null; if (low) result.lows.set(appid, low); const hit = id ? homeDeals[id] : void 0; const current = currentPrices.get(appid); const confirmedNewLow = hit?.value?.flag === "N" && current && sameOffer(hit.value, current) && (!hit.checkedPrice || sameOffer(hit.checkedPrice, current)); if (hit?.value && (fresh(hit, HOUR) || confirmedNewLow)) result.deals.set(appid, hit.value); } result.warning = warnings.size ? [...warnings].join(";") : null; return result; }; // src/scripts/steam-wishlist-prices/ui/region-settings.ts var SETUP_KEY = "wishlist-setup-v1"; var SETUP_VERSION = 1; var GUIDE_KEY = "wishlist-guide-done"; var GUIDE_VERSION = "v2"; var TAGS_KEY = "wishlist-tags-enabled"; var DEFAULT_HOME = "CN"; var DEFAULT_COMPARE = ["CN", "US"]; var codes = COUNTRIES.map((country) => country.code); var escapeHtml2 = (value) => value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); var uniqueCodes = (home, shown) => { const picked = [home, ...shown].filter((code) => codes.includes(code)); return [...new Set(picked)]; }; var loadRegionSetup = () => { try { const parsed = JSON.parse(localStorage.getItem(SETUP_KEY) || "null"); if (!parsed || parsed.v !== SETUP_VERSION) return null; if (!parsed.home || !codes.includes(parsed.home) || !Array.isArray(parsed.shown)) return null; const shown = uniqueCodes(parsed.home, parsed.shown); if (shown.length === 0) return null; return { home: parsed.home, shown }; } catch { return null; } }; var loadTagsEnabled = () => localStorage.getItem(TAGS_KEY) !== "off"; var saveTagsEnabled = (enabled) => { localStorage.setItem(TAGS_KEY, enabled ? "on" : "off"); }; var needsGuideSetup = () => localStorage.getItem(GUIDE_KEY) !== GUIDE_VERSION; var saveRegionSetup = (setup) => { syncItadHome(setup.home); const shown = uniqueCodes(setup.home, setup.shown); localStorage.setItem( SETUP_KEY, JSON.stringify({ v: SETUP_VERSION, home: setup.home, shown }) ); localStorage.setItem(GUIDE_KEY, GUIDE_VERSION); }; var countriesForSetup = (setup) => { const wanted = new Set(uniqueCodes(setup.home, setup.shown)); return COUNTRIES.filter((country) => wanted.has(country.code)); }; var compareRegionLimit = (wishlistCount) => wishlistCount > 4e3 ? 5 : 9; var needsRegionSetup = (setup, wishlistCount, force = false) => force || !setup || countriesForSetup(setup).length > compareRegionLimit(wishlistCount); var withPreferences = (setup) => ({ ...setup, itadKey: loadItadApiKey(), tagsEnabled: loadTagsEnabled() }); var readLegacyShown = () => { try { const saved = JSON.parse(localStorage.getItem("wishlist-regions") || "null"); if (!saved) return null; const picked = Array.isArray(saved) ? saved : saved.shown; if (!Array.isArray(picked)) return null; const shown = picked.filter((code) => typeof code === "string" && codes.includes(code)); return shown.length ? shown : null; } catch { return null; } }; var legacyRegionSetup = () => { const homeRaw = localStorage.getItem("wishlist-home-region"); const home = homeRaw && codes.includes(homeRaw) ? homeRaw : DEFAULT_HOME; const shown = readLegacyShown(); if (!shown && !(homeRaw && codes.includes(homeRaw))) return null; return { home, shown: uniqueCodes(home, shown ?? DEFAULT_COMPARE) }; }; var draftRegionSetup = (saved) => withPreferences(saved ?? legacyRegionSetup() ?? { home: DEFAULT_HOME, shown: DEFAULT_COMPARE.filter((code) => codes.includes(code)) }); var renderSetupShell = (initial) => { const setup = draftRegionSetup(initial); const homeItems = COUNTRIES.map((country) => { const on = country.code === setup.home; return ``; }).join(""); const compareItems = COUNTRIES.map((country) => { const on = setup.shown.includes(country.code) || country.code === setup.home; const locked = country.code === setup.home; return ``; }).join(""); return ` ${dialogHeader("setup-title", "选择比价区域")}

当前账户区域

${homeItems}

要比价的区域

${compareItems}

在 ITAD 注册应用后复制。留空则不查询史低

`; }; var mountSetup = (root, initial, onStart, wishlistCount = 0) => { const setup = draftRegionSetup(initial); const home = { current: setup.home }; const shown = new Set(uniqueCodes(setup.home, setup.shown)); const limit = compareRegionLimit(wishlistCount); const el = (id) => root.querySelector(`#${id}`); const syncCompare = () => { for (const input of Array.from(el("setup-compare-list").querySelectorAll("input[data-compare]"))) { const box = input; const code = box.dataset.compare || ""; box.checked = shown.has(code); box.disabled = code === home.current || !box.checked && shown.size >= limit; } const over = shown.size > limit; const hint = el("setup-limit-hint"); hint.textContent = over ? `已选 ${shown.size} 个区域,请减少至 ${limit} 个以内。` : `已选 ${shown.size} / ${limit} 个区域`; hint.classList?.toggle("is-over", over); const start = el("setup-start"); start.disabled = over; }; el("setup-home-list").addEventListener("change", (event) => { const input = event.target; if (input.name !== "wl-home" || !input.checked) return; home.current = input.value; shown.add(home.current); syncCompare(); }); el("setup-compare-list").addEventListener("change", (event) => { const input = event.target.closest("input[data-compare]"); if (!input || input.disabled) return; const code = input.dataset.compare || ""; if (input.checked && shown.size < limit) shown.add(code); else shown.delete(code); syncCompare(); }); const itadKey = el("setup-itad-key"); const tags = el("setup-tags"); itadKey.value = setup.itadKey; tags.checked = setup.tagsEnabled; el("setup-start").addEventListener("click", () => { shown.add(home.current); if (shown.size > limit) { syncCompare(); return; } onStart({ home: home.current, shown: uniqueCodes(home.current, [...shown]), itadKey: itadKey.value, tagsEnabled: tags.checked }); }); syncCompare(); }; // src/scripts/steam-wishlist-prices/ui/steam-list.ts var escapeHtml3 = (value) => value.replace(/&/g, "&").replace(//g, ">"); var chipHtml = (chip) => { const pct = chip.cut > 0 ? `-${chip.cut}%` : ""; const gift = chip.gift ? `可送礼` : ""; const local = chip.local ? `${escapeHtml3(chip.local)}` : ""; const low = chip.newLow ? `新史低` : chip.atLow ? `史低` : ""; const bundle = chip.bundle ? `捆绑包 ${escapeHtml3(chip.bundle.cny)}` : ""; return `
${escapeHtml3(chip.label)}${pct}${escapeHtml3(chip.cny)}${low}${bundle}${local}${gift}
`; }; var steamListHtml = (cards) => { if (cards.length === 0) { return `

没有匹配的游戏

`; } return cards.map((card) => { const href = steamAppUrl(card.appid); const end = card.discountEnd ? `${escapeHtml3(card.discountEnd.label)} ${escapeHtml3(card.discountEnd.when)}` : ""; const history = card.history ? `

ITAD ${escapeHtml3(card.history.label)} · ${escapeHtml3(card.history.price)}${card.history.date ? ` · ${escapeHtml3(card.history.date)}` : ""}

` : ""; const body = card.status ? `

${escapeHtml3(card.status)}

` : `
${escapeHtml3(card.cheapestLabel)} ${escapeHtml3(card.cheapest)}${escapeHtml3(card.vsHome)}${end}
${history}
${card.chips.map(chipHtml).join("")}
`; const cap = card.capsule ? `` : ""; const released = card.released ? `${escapeHtml3(card.released)}` : ""; const remove = card.removeGame ? `` : ""; const tags = card.tags?.length || card.editTags ? `
${(card.tags ?? []).map((tag) => ``).join("")}${card.editTags ? `` : ""}
` : ""; return ``; }).join(""); }; // node_modules/modern-screenshot/dist/index.mjs var _P = "p".charCodeAt(0); var _H = "H".charCodeAt(0); var _Y = "Y".charCodeAt(0); var _S = "s".charCodeAt(0); var PREFIX = "[modern-screenshot]"; var IN_BROWSER = typeof window !== "undefined"; var SUPPORT_WEB_WORKER = IN_BROWSER && "Worker" in window; var SUPPORT_ATOB = IN_BROWSER && "atob" in window; var SUPPORT_BTOA = IN_BROWSER && "btoa" in window; var USER_AGENT = IN_BROWSER ? window.navigator?.userAgent : ""; var IN_CHROME = USER_AGENT.includes("Chrome"); var IN_SAFARI = USER_AGENT.includes("AppleWebKit") && !IN_CHROME; var IN_FIREFOX = USER_AGENT.includes("Firefox"); var isContext = (value) => value && "__CONTEXT__" in value; var isCssFontFaceRule = (rule) => rule.constructor.name === "CSSFontFaceRule"; var isCSSImportRule = (rule) => rule.constructor.name === "CSSImportRule"; var isLayerBlockRule = (rule) => rule.constructor.name === "CSSLayerBlockRule"; var isElementNode = (node) => node.nodeType === 1; var isSVGElementNode = (node) => typeof node.className === "object"; var isSVGImageElementNode = (node) => node.tagName === "image"; var isSVGUseElementNode = (node) => node.tagName === "use"; var isHTMLElementNode = (node) => isElementNode(node) && typeof node.style !== "undefined" && !isSVGElementNode(node); var isCommentNode = (node) => node.nodeType === 8; var isTextNode = (node) => node.nodeType === 3; var isImageElement = (node) => node.tagName === "IMG"; var isVideoElement = (node) => node.tagName === "VIDEO"; var isCanvasElement = (node) => node.tagName === "CANVAS"; var isTextareaElement = (node) => node.tagName === "TEXTAREA"; var isInputElement = (node) => node.tagName === "INPUT"; var isStyleElement = (node) => node.tagName === "STYLE"; var isScriptElement = (node) => node.tagName === "SCRIPT"; var isSelectElement = (node) => node.tagName === "SELECT"; var isSlotElement = (node) => node.tagName === "SLOT"; var isIFrameElement = (node) => node.tagName === "IFRAME"; var consoleWarn = (...args) => console.warn(PREFIX, ...args); function supportWebp(ownerDocument) { const canvas = ownerDocument?.createElement?.("canvas"); if (canvas) { canvas.height = canvas.width = 1; } return Boolean(canvas) && "toDataURL" in canvas && Boolean(canvas.toDataURL("image/webp").includes("image/webp")); } var isDataUrl = (url) => url.startsWith("data:"); function resolveUrl(url, baseUrl) { if (url.match(/^[a-z]+:\/\//i)) return url; if (IN_BROWSER && url.match(/^\/\//)) return window.location.protocol + url; if (url.match(/^[a-z]+:/i)) return url; if (!IN_BROWSER) return url; const doc = getDocument().implementation.createHTMLDocument(); const base = doc.createElement("base"); const a = doc.createElement("a"); doc.head.appendChild(base); doc.body.appendChild(a); if (baseUrl) base.href = baseUrl; a.href = url; return a.href; } function getDocument(target) { return (target && isElementNode(target) ? target?.ownerDocument : target) ?? window.document; } var XMLNS = "http://www.w3.org/2000/svg"; function createSvg(width, height, ownerDocument) { const svg = getDocument(ownerDocument).createElementNS(XMLNS, "svg"); svg.setAttributeNS(null, "width", width.toString()); svg.setAttributeNS(null, "height", height.toString()); svg.setAttributeNS(null, "viewBox", `0 0 ${width} ${height}`); return svg; } function svgToDataUrl(svg, removeControlCharacter) { let xhtml = new XMLSerializer().serializeToString(svg); if (removeControlCharacter) { xhtml = xhtml.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu, ""); } return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(xhtml)}`; } function readBlob(blob, type) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = () => reject(reader.error); reader.onabort = () => reject(new Error(`Failed read blob to ${type}`)); if (type === "dataUrl") { reader.readAsDataURL(blob); } else if (type === "arrayBuffer") { reader.readAsArrayBuffer(blob); } }); } var blobToDataUrl = (blob) => readBlob(blob, "dataUrl"); function createImage(url, ownerDocument) { const img = getDocument(ownerDocument).createElement("img"); img.decoding = "sync"; img.loading = "eager"; img.src = url; return img; } function loadMedia(media, options) { return new Promise((resolve) => { const { timeout, ownerDocument, onError: userOnError, onWarn } = options ?? {}; const node = typeof media === "string" ? createImage(media, getDocument(ownerDocument)) : media; let timer = null; let removeEventListeners = null; function onResolve() { resolve(node); timer && clearTimeout(timer); removeEventListeners?.(); } if (timeout) { timer = setTimeout(onResolve, timeout); } if (isVideoElement(node)) { const currentSrc = node.currentSrc || node.src; if (!currentSrc) { if (node.poster) { return loadMedia(node.poster, options).then(resolve); } return onResolve(); } if (node.readyState >= 2) { return onResolve(); } const onLoadeddata = onResolve; const onError = (error) => { onWarn?.( "Failed video load", currentSrc, error ); userOnError?.(error); onResolve(); }; removeEventListeners = () => { node.removeEventListener("loadeddata", onLoadeddata); node.removeEventListener("error", onError); }; node.addEventListener("loadeddata", onLoadeddata, { once: true }); node.addEventListener("error", onError, { once: true }); } else { const currentSrc = isSVGImageElementNode(node) ? node.href.baseVal : node.currentSrc || node.src; if (!currentSrc) { return onResolve(); } const onLoad = async () => { if (isImageElement(node) && "decode" in node) { try { await node.decode(); } catch (error) { onWarn?.( "Failed to decode image, trying to render anyway", node.dataset.originalSrc || currentSrc, error ); } } onResolve(); }; const onError = (error) => { onWarn?.( "Failed image load", node.dataset.originalSrc || currentSrc, error ); onResolve(); }; if (isImageElement(node) && node.complete) { return onLoad(); } removeEventListeners = () => { node.removeEventListener("load", onLoad); node.removeEventListener("error", onError); }; node.addEventListener("load", onLoad, { once: true }); node.addEventListener("error", onError, { once: true }); } }); } async function waitUntilLoad(node, options) { if (isHTMLElementNode(node)) { if (isImageElement(node) || isVideoElement(node)) { await loadMedia(node, options); } else { await Promise.all( ["img", "video"].flatMap((selectors) => { return Array.from(node.querySelectorAll(selectors)).map((el) => loadMedia(el, options)); }) ); } } } var uuid = /* @__PURE__ */ (function uuid2() { let counter = 0; const random = () => `0000${(Math.random() * 36 ** 4 << 0).toString(36)}`.slice(-4); return () => { counter += 1; return `u${random()}${counter}`; }; })(); function splitFontFamily(fontFamily) { return fontFamily?.split(",").map((val) => val.trim().replace(/"|'/g, "").toLowerCase()).filter(Boolean); } var uid = 0; function createLogger(debug) { const prefix = `${PREFIX}[#${uid}]`; uid++; return { // eslint-disable-next-line no-console time: (label) => debug && console.time(`${prefix} ${label}`), // eslint-disable-next-line no-console timeEnd: (label) => debug && console.timeEnd(`${prefix} ${label}`), warn: (...args) => debug && consoleWarn(...args) }; } function getDefaultRequestInit(bypassingCache) { return { cache: bypassingCache ? "no-cache" : "force-cache" }; } async function orCreateContext(node, options) { return isContext(node) ? node : createContext(node, { ...options, autoDestruct: true }); } async function createContext(node, options) { const { scale = 1, workerUrl, workerNumber = 1 } = options || {}; const debug = Boolean(options?.debug); const features = options?.features ?? true; const ownerDocument = node.ownerDocument ?? (IN_BROWSER ? window.document : void 0); const ownerWindow = node.ownerDocument?.defaultView ?? (IN_BROWSER ? window : void 0); const requests = /* @__PURE__ */ new Map(); const context2 = { // Options width: 0, height: 0, quality: 1, type: "image/png", scale, backgroundColor: null, style: null, filter: null, maximumCanvasSize: 0, timeout: 3e4, progress: null, debug, fetch: { requestInit: getDefaultRequestInit(options?.fetch?.bypassingCache), placeholderImage: "data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", bypassingCache: false, ...options?.fetch }, fetchFn: null, font: {}, drawImageInterval: 100, workerUrl: null, workerNumber, onCloneEachNode: null, onCloneNode: null, onEmbedNode: null, onCreateForeignObjectSvg: null, includeStyleProperties: null, autoDestruct: false, ...options, // InternalContext __CONTEXT__: true, log: createLogger(debug), node, ownerDocument, ownerWindow, dpi: scale === 1 ? null : 96 * scale, svgStyleElement: createStyleElement(ownerDocument), svgDefsElement: ownerDocument?.createElementNS(XMLNS, "defs"), svgStyles: /* @__PURE__ */ new Map(), defaultComputedStyles: /* @__PURE__ */ new Map(), workers: [ ...Array.from({ length: SUPPORT_WEB_WORKER && workerUrl && workerNumber ? workerNumber : 0 }) ].map(() => { try { const worker = new Worker(workerUrl); worker.onmessage = async (event) => { const { url, result } = event.data; if (result) { requests.get(url)?.resolve?.(result); } else { requests.get(url)?.reject?.(new Error(`Error receiving message from worker: ${url}`)); } }; worker.onmessageerror = (event) => { const { url } = event.data; requests.get(url)?.reject?.(new Error(`Error receiving message from worker: ${url}`)); }; return worker; } catch (error) { context2.log.warn("Failed to new Worker", error); return null; } }).filter(Boolean), fontFamilies: /* @__PURE__ */ new Map(), fontCssTexts: /* @__PURE__ */ new Map(), acceptOfImage: `${[ supportWebp(ownerDocument) && "image/webp", "image/svg+xml", "image/*", "*/*" ].filter(Boolean).join(",")};q=0.8`, requests, drawImageCount: 0, tasks: [], features, isEnable: (key) => { if (key === "restoreScrollPosition") { return typeof features === "boolean" ? false : features[key] ?? false; } if (typeof features === "boolean") { return features; } return features[key] ?? true; }, shadowRoots: [] }; context2.log.time("wait until load"); await waitUntilLoad(node, { timeout: context2.timeout, onWarn: context2.log.warn }); context2.log.timeEnd("wait until load"); const { width, height } = resolveBoundingBox(node, context2); context2.width = width; context2.height = height; return context2; } function createStyleElement(ownerDocument) { if (!ownerDocument) return void 0; const style = ownerDocument.createElement("style"); const cssText = style.ownerDocument.createTextNode(` .______background-clip--text { background-clip: text; -webkit-background-clip: text; } `); style.appendChild(cssText); return style; } function resolveBoundingBox(node, context2) { let { width, height } = context2; if (isElementNode(node) && (!width || !height)) { const box = node.getBoundingClientRect(); width = width || box.width || Number(node.getAttribute("width")) || 0; height = height || box.height || Number(node.getAttribute("height")) || 0; } return { width, height }; } async function imageToCanvas(image, context2) { const { log, timeout, drawImageCount, drawImageInterval } = context2; log.time("image to canvas"); const loaded = await loadMedia(image, { timeout, onWarn: context2.log.warn }); const { canvas, context2d } = createCanvas(image.ownerDocument, context2); const drawImage = () => { try { context2d?.drawImage(loaded, 0, 0, canvas.width, canvas.height); } catch (error) { context2.log.warn("Failed to drawImage", error); } }; drawImage(); if (context2.isEnable("fixSvgXmlDecode")) { for (let i = 0; i < drawImageCount; i++) { await new Promise((resolve) => { setTimeout(() => { context2d?.clearRect(0, 0, canvas.width, canvas.height); drawImage(); resolve(); }, i + drawImageInterval); }); } } context2.drawImageCount = 0; log.timeEnd("image to canvas"); return canvas; } function createCanvas(ownerDocument, context2) { const { width, height, scale, backgroundColor, maximumCanvasSize: max } = context2; const canvas = ownerDocument.createElement("canvas"); canvas.width = Math.floor(width * scale); canvas.height = Math.floor(height * scale); canvas.style.width = `${width}px`; canvas.style.height = `${height}px`; if (max) { if (canvas.width > max || canvas.height > max) { if (canvas.width > max && canvas.height > max) { if (canvas.width > canvas.height) { canvas.height *= max / canvas.width; canvas.width = max; } else { canvas.width *= max / canvas.height; canvas.height = max; } } else if (canvas.width > max) { canvas.height *= max / canvas.width; canvas.width = max; } else { canvas.width *= max / canvas.height; canvas.height = max; } } } const context2d = canvas.getContext("2d"); if (context2d && backgroundColor) { context2d.fillStyle = backgroundColor; context2d.fillRect(0, 0, canvas.width, canvas.height); } return { canvas, context2d }; } function cloneCanvas(canvas, context2) { if (canvas.ownerDocument) { try { const dataURL = canvas.toDataURL(); if (dataURL !== "data:,") { return createImage(dataURL, canvas.ownerDocument); } } catch (error) { context2.log.warn("Failed to clone canvas", error); } } const cloned = canvas.cloneNode(false); const ctx = canvas.getContext("2d"); const clonedCtx = cloned.getContext("2d"); try { if (ctx && clonedCtx) { clonedCtx.putImageData( ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0 ); } return cloned; } catch (error) { context2.log.warn("Failed to clone canvas", error); } return cloned; } function cloneIframe(iframe, context2) { try { if (iframe?.contentDocument?.documentElement) { return cloneNode(iframe.contentDocument.documentElement, context2); } } catch (error) { context2.log.warn("Failed to clone iframe", error); } return iframe.cloneNode(false); } function cloneImage(image) { const cloned = image.cloneNode(false); if (image.currentSrc && image.currentSrc !== image.src) { cloned.src = image.currentSrc; cloned.srcset = ""; } if (cloned.loading === "lazy") { cloned.loading = "eager"; } return cloned; } async function cloneVideo(video, context2) { if (video.ownerDocument && !video.currentSrc && video.poster) { return createImage(video.poster, video.ownerDocument); } const cloned = video.cloneNode(false); cloned.crossOrigin = "anonymous"; if (video.currentSrc && video.currentSrc !== video.src) { cloned.src = video.currentSrc; } const ownerDocument = cloned.ownerDocument; if (ownerDocument) { let canPlay = true; await loadMedia(cloned, { onError: () => canPlay = false, onWarn: context2.log.warn }); if (!canPlay) { if (video.poster) { return createImage(video.poster, video.ownerDocument); } return cloned; } cloned.currentTime = video.currentTime; await new Promise((resolve) => { cloned.addEventListener("seeked", resolve, { once: true }); }); const canvas = ownerDocument.createElement("canvas"); canvas.width = video.offsetWidth; canvas.height = video.offsetHeight; try { const ctx = canvas.getContext("2d"); if (ctx) ctx.drawImage(cloned, 0, 0, canvas.width, canvas.height); } catch (error) { context2.log.warn("Failed to clone video", error); if (video.poster) { return createImage(video.poster, video.ownerDocument); } return cloned; } return cloneCanvas(canvas, context2); } return cloned; } function cloneElement(node, context2) { if (isCanvasElement(node)) { return cloneCanvas(node, context2); } if (isIFrameElement(node)) { return cloneIframe(node, context2); } if (isImageElement(node)) { return cloneImage(node); } if (isVideoElement(node)) { return cloneVideo(node, context2); } return node.cloneNode(false); } function getSandBox(context2) { let sandbox = context2.sandbox; if (!sandbox) { const { ownerDocument } = context2; try { if (ownerDocument) { sandbox = ownerDocument.createElement("iframe"); sandbox.id = `__SANDBOX__${uuid()}`; sandbox.width = "0"; sandbox.height = "0"; sandbox.style.visibility = "hidden"; sandbox.style.position = "fixed"; ownerDocument.body.appendChild(sandbox); sandbox.srcdoc = ''; context2.sandbox = sandbox; } } catch (error) { context2.log.warn("Failed to getSandBox", error); } } return sandbox; } var ignoredStyles = [ "width", "height", "-webkit-text-fill-color" ]; var includedAttributes = [ "stroke", "fill" ]; function getDefaultStyle(node, pseudoElement, context2) { const { defaultComputedStyles } = context2; const nodeName = node.nodeName.toLowerCase(); const isSvgNode = isSVGElementNode(node) && nodeName !== "svg"; const attributes = isSvgNode ? includedAttributes.map((name) => [name, node.getAttribute(name)]).filter(([, value]) => value !== null) : []; const key = [ isSvgNode && "svg", nodeName, attributes.map((name, value) => `${name}=${value}`).join(","), pseudoElement ].filter(Boolean).join(":"); if (defaultComputedStyles.has(key)) return defaultComputedStyles.get(key); const sandbox = getSandBox(context2); const sandboxWindow = sandbox?.contentWindow; if (!sandboxWindow) return /* @__PURE__ */ new Map(); const sandboxDocument = sandboxWindow?.document; let root; let el; if (isSvgNode) { root = sandboxDocument.createElementNS(XMLNS, "svg"); el = root.ownerDocument.createElementNS(root.namespaceURI, nodeName); attributes.forEach(([name, value]) => { el.setAttributeNS(null, name, value); }); root.appendChild(el); } else { root = el = sandboxDocument.createElement(nodeName); } el.textContent = " "; sandboxDocument.body.appendChild(root); const computedStyle = sandboxWindow.getComputedStyle(el, pseudoElement); const styles = /* @__PURE__ */ new Map(); for (let len = computedStyle.length, i = 0; i < len; i++) { const name = computedStyle.item(i); if (ignoredStyles.includes(name)) continue; styles.set(name, computedStyle.getPropertyValue(name)); } sandboxDocument.body.removeChild(root); defaultComputedStyles.set(key, styles); return styles; } function getDiffStyle(style, defaultStyle, includeStyleProperties) { const diffStyle = /* @__PURE__ */ new Map(); const prefixs = []; const prefixTree = /* @__PURE__ */ new Map(); if (includeStyleProperties) { for (const name of includeStyleProperties) { applyTo(name); } } else { for (let len = style.length, i = 0; i < len; i++) { const name = style.item(i); applyTo(name); } } for (let len = prefixs.length, i = 0; i < len; i++) { prefixTree.get(prefixs[i])?.forEach((value, name) => diffStyle.set(name, value)); } function applyTo(name) { const value = style.getPropertyValue(name); const priority = style.getPropertyPriority(name); const subIndex = name.lastIndexOf("-"); const prefix = subIndex > -1 ? name.substring(0, subIndex) : void 0; if (prefix) { let map = prefixTree.get(prefix); if (!map) { map = /* @__PURE__ */ new Map(); prefixTree.set(prefix, map); } map.set(name, [value, priority]); } if (defaultStyle.get(name) === value && !priority) return; if (prefix) { prefixs.push(prefix); } else { diffStyle.set(name, [value, priority]); } } return diffStyle; } function copyCssStyles(node, cloned, isRoot, context2) { const { ownerWindow, includeStyleProperties, currentParentNodeStyle } = context2; const clonedStyle = cloned.style; const computedStyle = ownerWindow.getComputedStyle(node); const defaultStyle = getDefaultStyle(node, null, context2); currentParentNodeStyle?.forEach((_, key) => { defaultStyle.delete(key); }); const style = getDiffStyle(computedStyle, defaultStyle, includeStyleProperties); style.delete("transition-property"); style.delete("all"); style.delete("d"); style.delete("content"); if (isRoot) { style.delete("position"); style.delete("margin-top"); style.delete("margin-right"); style.delete("margin-bottom"); style.delete("margin-left"); style.delete("margin-block-start"); style.delete("margin-block-end"); style.delete("margin-inline-start"); style.delete("margin-inline-end"); style.set("box-sizing", ["border-box", ""]); } if (style.get("background-clip")?.[0] === "text") { cloned.classList.add("______background-clip--text"); } if (IN_CHROME) { if (!style.has("font-kerning")) style.set("font-kerning", ["normal", ""]); if ((style.get("overflow-x")?.[0] === "hidden" || style.get("overflow-y")?.[0] === "hidden") && style.get("text-overflow")?.[0] === "ellipsis" && node.scrollWidth === node.clientWidth) { style.set("text-overflow", ["clip", ""]); } } for (let len = clonedStyle.length, i = 0; i < len; i++) { clonedStyle.removeProperty(clonedStyle.item(i)); } style.forEach(([value, priority], name) => { clonedStyle.setProperty(name, value, priority); }); return style; } function copyInputValue(node, cloned) { if (isTextareaElement(node) || isInputElement(node) || isSelectElement(node)) { cloned.setAttribute("value", node.value); } } var pseudoClasses = [ "::before", "::after" // '::placeholder', TODO ]; var scrollbarPseudoClasses = [ "::-webkit-scrollbar", "::-webkit-scrollbar-button", // '::-webkit-scrollbar:horizontal', TODO "::-webkit-scrollbar-thumb", "::-webkit-scrollbar-track", "::-webkit-scrollbar-track-piece", // '::-webkit-scrollbar:vertical', TODO "::-webkit-scrollbar-corner", "::-webkit-resizer" ]; function copyPseudoClass(node, cloned, copyScrollbar, context2, addWordToFontFamilies) { const { ownerWindow, svgStyleElement, svgStyles, currentNodeStyle } = context2; if (!svgStyleElement || !ownerWindow) return; function copyBy(pseudoClass) { const computedStyle = ownerWindow.getComputedStyle(node, pseudoClass); let content = computedStyle.getPropertyValue("content"); if (!content || content === "none") return; addWordToFontFamilies?.(content); content = content.replace(/(')|(")|(counter\(.+\))/g, ""); const klasses = [uuid()]; const defaultStyle = getDefaultStyle(node, pseudoClass, context2); currentNodeStyle?.forEach((_, key) => { defaultStyle.delete(key); }); const style = getDiffStyle(computedStyle, defaultStyle, context2.includeStyleProperties); style.delete("content"); style.delete("-webkit-locale"); if (style.get("background-clip")?.[0] === "text") { cloned.classList.add("______background-clip--text"); } const cloneStyle = [ `content: '${content}';` ]; style.forEach(([value, priority], name) => { cloneStyle.push(`${name}: ${value}${priority ? " !important" : ""};`); }); if (cloneStyle.length === 1) return; try { cloned.className = [cloned.className, ...klasses].join(" "); } catch (err) { context2.log.warn("Failed to copyPseudoClass", err); return; } const cssText = cloneStyle.join("\n "); let allClasses = svgStyles.get(cssText); if (!allClasses) { allClasses = []; svgStyles.set(cssText, allClasses); } allClasses.push(`.${klasses[0]}${pseudoClass}`); } pseudoClasses.forEach(copyBy); if (copyScrollbar) scrollbarPseudoClasses.forEach(copyBy); } var excludeParentNodes = /* @__PURE__ */ new Set([ "symbol" // test/fixtures/svg.symbol.html ]); async function appendChildNode(node, cloned, child, context2, addWordToFontFamilies) { if (isElementNode(child) && (isStyleElement(child) || isScriptElement(child))) return; if (context2.filter && !context2.filter(child)) return; if (excludeParentNodes.has(cloned.nodeName) || excludeParentNodes.has(child.nodeName)) { context2.currentParentNodeStyle = void 0; } else { context2.currentParentNodeStyle = context2.currentNodeStyle; } const childCloned = await cloneNode(child, context2, false, addWordToFontFamilies); if (context2.isEnable("restoreScrollPosition")) { restoreScrollPosition(node, childCloned); } cloned.appendChild(childCloned); } async function cloneChildNodes(node, cloned, context2, addWordToFontFamilies) { let firstChild = node.firstChild; if (isElementNode(node)) { if (node.shadowRoot) { firstChild = node.shadowRoot?.firstChild; context2.shadowRoots.push(node.shadowRoot); } } for (let child = firstChild; child; child = child.nextSibling) { if (isCommentNode(child)) continue; if (isElementNode(child) && isSlotElement(child) && typeof child.assignedNodes === "function") { const nodes = child.assignedNodes(); for (let i = 0; i < nodes.length; i++) { await appendChildNode(node, cloned, nodes[i], context2, addWordToFontFamilies); } } else { await appendChildNode(node, cloned, child, context2, addWordToFontFamilies); } } } function restoreScrollPosition(node, chlidCloned) { if (!isHTMLElementNode(node) || !isHTMLElementNode(chlidCloned)) return; const { scrollTop, scrollLeft } = node; if (!scrollTop && !scrollLeft) { return; } const { transform } = chlidCloned.style; const matrix = new DOMMatrix(transform); const { a, b, c, d } = matrix; matrix.a = 1; matrix.b = 0; matrix.c = 0; matrix.d = 1; matrix.translateSelf(-scrollLeft, -scrollTop); matrix.a = a; matrix.b = b; matrix.c = c; matrix.d = d; chlidCloned.style.transform = matrix.toString(); } function applyCssStyleWithOptions(cloned, context2) { const { backgroundColor, width, height, style: styles } = context2; const clonedStyle = cloned.style; if (backgroundColor) clonedStyle.setProperty("background-color", backgroundColor, "important"); if (width) clonedStyle.setProperty("width", `${width}px`, "important"); if (height) clonedStyle.setProperty("height", `${height}px`, "important"); if (styles) { for (const name in styles) clonedStyle[name] = styles[name]; } } var NORMAL_ATTRIBUTE_RE = /^[\w-:]+$/; async function cloneNode(node, context2, isRoot = false, addWordToFontFamilies) { const { ownerDocument, ownerWindow, fontFamilies, onCloneEachNode } = context2; if (ownerDocument && isTextNode(node)) { if (addWordToFontFamilies && /\S/.test(node.data)) { addWordToFontFamilies(node.data); } return ownerDocument.createTextNode(node.data); } if (ownerDocument && ownerWindow && isElementNode(node) && (isHTMLElementNode(node) || isSVGElementNode(node))) { const cloned2 = await cloneElement(node, context2); if (context2.isEnable("removeAbnormalAttributes")) { const names = cloned2.getAttributeNames(); for (let len = names.length, i = 0; i < len; i++) { const name = names[i]; if (!NORMAL_ATTRIBUTE_RE.test(name)) { cloned2.removeAttribute(name); } } } const style = context2.currentNodeStyle = copyCssStyles(node, cloned2, isRoot, context2); if (isRoot) applyCssStyleWithOptions(cloned2, context2); let copyScrollbar = false; if (context2.isEnable("copyScrollbar")) { const overflow = [ style.get("overflow-x")?.[0], style.get("overflow-y")?.[0] ]; copyScrollbar = overflow.includes("scroll") || (overflow.includes("auto") || overflow.includes("overlay")) && (node.scrollHeight > node.clientHeight || node.scrollWidth > node.clientWidth); } const textTransform = style.get("text-transform")?.[0]; const families = splitFontFamily(style.get("font-family")?.[0]); const addWordToFontFamilies2 = families ? (word) => { if (textTransform === "uppercase") { word = word.toUpperCase(); } else if (textTransform === "lowercase") { word = word.toLowerCase(); } else if (textTransform === "capitalize") { word = word[0].toUpperCase() + word.substring(1); } families.forEach((family) => { let fontFamily = fontFamilies.get(family); if (!fontFamily) { fontFamilies.set(family, fontFamily = /* @__PURE__ */ new Set()); } word.split("").forEach((text) => fontFamily.add(text)); }); } : void 0; copyPseudoClass( node, cloned2, copyScrollbar, context2, addWordToFontFamilies2 ); copyInputValue(node, cloned2); if (!isVideoElement(node)) { await cloneChildNodes( node, cloned2, context2, addWordToFontFamilies2 ); } await onCloneEachNode?.(cloned2); return cloned2; } const cloned = node.cloneNode(false); await cloneChildNodes(node, cloned, context2); await onCloneEachNode?.(cloned); return cloned; } function destroyContext(context2) { context2.ownerDocument = void 0; context2.ownerWindow = void 0; context2.svgStyleElement = void 0; context2.svgDefsElement = void 0; context2.svgStyles.clear(); context2.defaultComputedStyles.clear(); if (context2.sandbox) { try { context2.sandbox.remove(); } catch (err) { context2.log.warn("Failed to destroyContext", err); } context2.sandbox = void 0; } context2.workers = []; context2.fontFamilies.clear(); context2.fontCssTexts.clear(); context2.requests.clear(); context2.tasks = []; context2.shadowRoots = []; } function baseFetch(options) { const { url, timeout, responseType, ...requestInit } = options; const controller = new AbortController(); const timer = timeout ? setTimeout(() => controller.abort(), timeout) : void 0; return fetch(url, { signal: controller.signal, ...requestInit }).then((response) => { if (!response.ok) { throw new Error("Failed fetch, not 2xx response", { cause: response }); } switch (responseType) { case "arrayBuffer": return response.arrayBuffer(); case "dataUrl": return response.blob().then(blobToDataUrl); case "text": default: return response.text(); } }).finally(() => clearTimeout(timer)); } function contextFetch(context2, options) { const { url: rawUrl, requestType = "text", responseType = "text", imageDom } = options; let url = rawUrl; const { timeout, acceptOfImage, requests, fetchFn, fetch: { requestInit, bypassingCache, placeholderImage }, font, workers, fontFamilies } = context2; if (requestType === "image" && (IN_SAFARI || IN_FIREFOX)) { context2.drawImageCount++; } let request2 = requests.get(rawUrl); if (!request2) { if (bypassingCache) { if (bypassingCache instanceof RegExp && bypassingCache.test(url)) { url += (/\?/.test(url) ? "&" : "?") + (/* @__PURE__ */ new Date()).getTime(); } } const canFontMinify = requestType.startsWith("font") && font && font.minify; const fontTexts = /* @__PURE__ */ new Set(); if (canFontMinify) { const families = requestType.split(";")[1].split(","); families.forEach((family) => { if (!fontFamilies.has(family)) return; fontFamilies.get(family).forEach((text) => fontTexts.add(text)); }); } const needFontMinify = canFontMinify && fontTexts.size; const baseFetchOptions = { url, timeout, responseType: needFontMinify ? "arrayBuffer" : responseType, headers: requestType === "image" ? { accept: acceptOfImage } : void 0, ...requestInit }; request2 = { type: requestType, resolve: void 0, reject: void 0, response: null }; request2.response = (async () => { if (fetchFn && requestType === "image") { const result = await fetchFn(rawUrl); if (result) return result; } if (!IN_SAFARI && rawUrl.startsWith("http") && workers.length) { return new Promise((resolve, reject) => { const worker = workers[requests.size & workers.length - 1]; worker.postMessage({ rawUrl, ...baseFetchOptions }); request2.resolve = resolve; request2.reject = reject; }); } return baseFetch(baseFetchOptions); })().catch((error) => { requests.delete(rawUrl); if (requestType === "image" && placeholderImage) { context2.log.warn("Failed to fetch image base64, trying to use placeholder image", url); return typeof placeholderImage === "string" ? placeholderImage : placeholderImage(imageDom); } throw error; }); requests.set(rawUrl, request2); } return request2.response; } async function replaceCssUrlToDataUrl(cssText, baseUrl, context2, isImage) { if (!hasCssUrl(cssText)) return cssText; for (const [rawUrl, url] of parseCssUrls(cssText, baseUrl)) { try { const dataUrl = await contextFetch( context2, { url, requestType: isImage ? "image" : "text", responseType: "dataUrl" } ); cssText = cssText.replace(toRE(rawUrl), `$1${dataUrl}$3`); } catch (error) { context2.log.warn("Failed to fetch css data url", rawUrl, error); } } return cssText; } function hasCssUrl(cssText) { return /url\((['"]?)([^'"]+?)\1\)/.test(cssText); } var URL_RE = /url\((['"]?)([^'"]+?)\1\)/g; function parseCssUrls(cssText, baseUrl) { const result = []; cssText.replace(URL_RE, (raw, quotation, url) => { result.push([url, resolveUrl(url, baseUrl)]); return raw; }); return result.filter(([url]) => !isDataUrl(url)); } function toRE(url) { const escaped = url.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1"); return new RegExp(`(url\\(['"]?)(${escaped})(['"]?\\))`, "g"); } var properties = [ "background-image", "border-image-source", "-webkit-border-image", "-webkit-mask-image", "list-style-image" ]; function embedCssStyleImage(style, context2) { return properties.map((property) => { const value = style.getPropertyValue(property); if (!value || value === "none") { return null; } if (IN_SAFARI || IN_FIREFOX) { context2.drawImageCount++; } return replaceCssUrlToDataUrl(value, null, context2, true).then((newValue) => { if (!newValue || value === newValue) return; style.setProperty( property, newValue, style.getPropertyPriority(property) ); }); }).filter(Boolean); } function embedImageElement(cloned, context2) { if (isImageElement(cloned)) { const originalSrc = cloned.currentSrc || cloned.src; if (!isDataUrl(originalSrc)) { return [ contextFetch(context2, { url: originalSrc, imageDom: cloned, requestType: "image", responseType: "dataUrl" }).then((url) => { if (!url) return; cloned.srcset = ""; cloned.dataset.originalSrc = originalSrc; cloned.src = url || ""; }) ]; } if (IN_SAFARI || IN_FIREFOX) { context2.drawImageCount++; } } else if (isSVGElementNode(cloned) && !isDataUrl(cloned.href.baseVal)) { const originalSrc = cloned.href.baseVal; return [ contextFetch(context2, { url: originalSrc, imageDom: cloned, requestType: "image", responseType: "dataUrl" }).then((url) => { if (!url) return; cloned.dataset.originalSrc = originalSrc; cloned.href.baseVal = url || ""; }) ]; } return []; } function embedSvgUse(cloned, context2) { const { ownerDocument, svgDefsElement } = context2; const href = cloned.getAttribute("href") ?? cloned.getAttribute("xlink:href"); if (!href) return []; const [svgUrl, id] = href.split("#"); if (id) { const query = `#${id}`; const definition = context2.shadowRoots.reduce( (res, root) => { return res ?? root.querySelector(`svg ${query}`); }, ownerDocument?.querySelector(`svg ${query}`) ); if (svgUrl) { cloned.setAttribute("href", query); } if (svgDefsElement?.querySelector(query)) return []; if (definition) { svgDefsElement?.appendChild(definition.cloneNode(true)); return []; } else if (svgUrl) { return [ contextFetch(context2, { url: svgUrl, responseType: "text" }).then((svgData) => { svgDefsElement?.insertAdjacentHTML("beforeend", svgData); }) ]; } } return []; } function embedNode(cloned, context2) { const { tasks } = context2; if (isElementNode(cloned)) { if (isImageElement(cloned) || isSVGImageElementNode(cloned)) { tasks.push(...embedImageElement(cloned, context2)); } if (isSVGUseElementNode(cloned)) { tasks.push(...embedSvgUse(cloned, context2)); } } if (isHTMLElementNode(cloned)) { tasks.push(...embedCssStyleImage(cloned.style, context2)); } cloned.childNodes.forEach((child) => { embedNode(child, context2); }); } async function embedWebFont(clone, context2) { const { ownerDocument, svgStyleElement, fontFamilies, fontCssTexts, tasks, font } = context2; if (!ownerDocument || !svgStyleElement || !fontFamilies.size) { return; } if (font && font.cssText) { const cssText = filterPreferredFormat(font.cssText, context2); svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText} `)); } else { const styleSheets = Array.from(ownerDocument.styleSheets).filter((styleSheet) => { try { return "cssRules" in styleSheet && Boolean(styleSheet.cssRules.length); } catch (error) { context2.log.warn(`Error while reading CSS rules from ${styleSheet.href}`, error); return false; } }); const tempDoc = ownerDocument.implementation.createHTMLDocument(""); const tempStyleEl = tempDoc.createElement("style"); tempDoc.head.appendChild(tempStyleEl); const tempStyleSheet = tempStyleEl.sheet; await Promise.all( styleSheets.flatMap((styleSheet) => { return Array.from(styleSheet.cssRules).map(async (cssRule) => { if (isCSSImportRule(cssRule)) { const baseUrl = cssRule.href; let cssText = ""; try { cssText = await contextFetch(context2, { url: baseUrl, requestType: "text", responseType: "text" }); } catch (error) { context2.log.warn(`Error fetch remote css import from ${baseUrl}`, error); } const replacedCssText = cssText.replace( URL_RE, (raw, quotation, url) => raw.replace(url, resolveUrl(url, baseUrl)) ); for (const rule of parseCss(replacedCssText)) { try { tempStyleSheet.insertRule(rule, tempStyleSheet.cssRules.length); } catch (error) { context2.log.warn("Error inserting rule from remote css import", { rule, error }); } } } }); }) ); if (tempStyleSheet.cssRules.length) styleSheets.push(tempStyleSheet); const cssRules = []; styleSheets.forEach((sheet) => { unwrapCssLayers(sheet.cssRules, cssRules); }); cssRules.filter((cssRule) => isCssFontFaceRule(cssRule) && hasCssUrl(cssRule.style.getPropertyValue("src")) && splitFontFamily(cssRule.style.getPropertyValue("font-family"))?.some((val) => fontFamilies.has(val))).forEach((value) => { const rule = value; const cssText = fontCssTexts.get(rule.cssText); if (cssText) { svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText} `)); } else { tasks.push( replaceCssUrlToDataUrl( rule.cssText, rule.parentStyleSheet ? rule.parentStyleSheet.href : null, context2 ).then((cssText2) => { cssText2 = filterPreferredFormat(cssText2, context2); fontCssTexts.set(rule.cssText, cssText2); svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText2} `)); }) ); } }); } } var COMMENTS_RE = /(\/\*[\s\S]*?\*\/)/g; var KEYFRAMES_RE = /((@.*?keyframes [\s\S]*?){([\s\S]*?}\s*?)})/gi; function parseCss(source) { if (source == null) return []; const result = []; let cssText = source.replace(COMMENTS_RE, ""); while (true) { const matches = KEYFRAMES_RE.exec(cssText); if (!matches) break; result.push(matches[0]); } cssText = cssText.replace(KEYFRAMES_RE, ""); const IMPORT_RE = /@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi; const UNIFIED_RE = new RegExp( // eslint-disable-next-line "((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})", "gi" ); while (true) { let matches = IMPORT_RE.exec(cssText); if (!matches) { matches = UNIFIED_RE.exec(cssText); if (!matches) { break; } else { IMPORT_RE.lastIndex = UNIFIED_RE.lastIndex; } } else { UNIFIED_RE.lastIndex = IMPORT_RE.lastIndex; } result.push(matches[0]); } return result; } var URL_WITH_FORMAT_RE = /url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g; var FONT_SRC_RE = /src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g; function filterPreferredFormat(str, context2) { const { font } = context2; const preferredFormat = font ? font?.preferredFormat : void 0; return preferredFormat ? str.replace(FONT_SRC_RE, (match) => { while (true) { const [src, , format] = URL_WITH_FORMAT_RE.exec(match) || []; if (!format) return ""; if (format === preferredFormat) return `src: ${src};`; } }) : str; } function unwrapCssLayers(rules, out = []) { for (const rule of Array.from(rules)) { if (isLayerBlockRule(rule)) { out.push(...unwrapCssLayers(rule.cssRules)); } else if ("cssRules" in rule) { unwrapCssLayers(rule.cssRules, out); } else { out.push(rule); } } return out; } var SVG_EXTERNAL_RESOURCE_REGEX = /\bx?link:?href\s*=\s*["'](?!data:)[^"']+["']/i; function svgHasExternalResources(svg) { return SVG_EXTERNAL_RESOURCE_REGEX.test(svg.innerHTML); } async function domToForeignObjectSvg(node, options) { const context2 = await orCreateContext(node, options); if (isElementNode(context2.node) && isSVGElementNode(context2.node) && !svgHasExternalResources(context2.node)) return context2.node; const { ownerDocument, log, tasks, svgStyleElement, svgDefsElement, svgStyles, font, progress, autoDestruct, onCloneNode, onEmbedNode, onCreateForeignObjectSvg } = context2; log.time("clone node"); const clone = await cloneNode(context2.node, context2, true); if (svgStyleElement && ownerDocument) { let allCssText = ""; svgStyles.forEach((klasses, cssText) => { allCssText += `${klasses.join(",\n")} { ${cssText} } `; }); svgStyleElement.appendChild(ownerDocument.createTextNode(allCssText)); } log.timeEnd("clone node"); await onCloneNode?.(clone); if (font !== false && isElementNode(clone)) { log.time("embed web font"); await embedWebFont(clone, context2); log.timeEnd("embed web font"); } log.time("embed node"); embedNode(clone, context2); const count = tasks.length; let current = 0; const runTask = async () => { while (true) { const task = tasks.pop(); if (!task) break; try { await task; } catch (error) { context2.log.warn("Failed to run task", error); } progress?.(++current, count); } }; progress?.(current, count); await Promise.all([...Array.from({ length: 4 })].map(runTask)); log.timeEnd("embed node"); await onEmbedNode?.(clone); const svg = createForeignObjectSvg(clone, context2); svgDefsElement && svg.insertBefore(svgDefsElement, svg.children[0]); svgStyleElement && svg.insertBefore(svgStyleElement, svg.children[0]); autoDestruct && destroyContext(context2); await onCreateForeignObjectSvg?.(svg); return svg; } function createForeignObjectSvg(clone, context2) { const { width, height } = context2; const svg = createSvg(width, height, clone.ownerDocument); const foreignObject = svg.ownerDocument.createElementNS(svg.namespaceURI, "foreignObject"); foreignObject.setAttributeNS(null, "x", "0%"); foreignObject.setAttributeNS(null, "y", "0%"); foreignObject.setAttributeNS(null, "width", "100%"); foreignObject.setAttributeNS(null, "height", "100%"); foreignObject.append(clone); svg.appendChild(foreignObject); return svg; } async function domToCanvas(node, options) { const context2 = await orCreateContext(node, options); const svg = await domToForeignObjectSvg(context2); const dataUrl = svgToDataUrl(svg, context2.isEnable("removeControlCharacter")); if (!context2.autoDestruct) { context2.svgStyleElement = createStyleElement(context2.ownerDocument); context2.svgDefsElement = context2.ownerDocument?.createElementNS(XMLNS, "defs"); context2.svgStyles.clear(); } const image = createImage(dataUrl, svg.ownerDocument); return await imageToCanvas(image, context2); } // node_modules/qrcode-generator/dist/qrcode.mjs var qrcode = function(typeNumber, errorCorrectionLevel) { const PAD0 = 236; const PAD1 = 17; let _typeNumber = typeNumber; const _errorCorrectionLevel = QRErrorCorrectionLevel[errorCorrectionLevel]; let _modules = null; let _moduleCount = 0; let _dataCache = null; const _dataList = []; const _this = {}; const makeImpl = function(test, maskPattern) { _moduleCount = _typeNumber * 4 + 17; _modules = (function(moduleCount) { const modules = new Array(moduleCount); for (let row = 0; row < moduleCount; row += 1) { modules[row] = new Array(moduleCount); for (let col = 0; col < moduleCount; col += 1) { modules[row][col] = null; } } return modules; })(_moduleCount); setupPositionProbePattern(0, 0); setupPositionProbePattern(_moduleCount - 7, 0); setupPositionProbePattern(0, _moduleCount - 7); setupPositionAdjustPattern(); setupTimingPattern(); setupTypeInfo(test, maskPattern); if (_typeNumber >= 7) { setupTypeNumber(test); } if (_dataCache == null) { _dataCache = createData(_typeNumber, _errorCorrectionLevel, _dataList); } mapData(_dataCache, maskPattern); }; const setupPositionProbePattern = function(row, col) { for (let r = -1; r <= 7; r += 1) { if (row + r <= -1 || _moduleCount <= row + r) continue; for (let c = -1; c <= 7; c += 1) { if (col + c <= -1 || _moduleCount <= col + c) continue; if (0 <= r && r <= 6 && (c == 0 || c == 6) || 0 <= c && c <= 6 && (r == 0 || r == 6) || 2 <= r && r <= 4 && 2 <= c && c <= 4) { _modules[row + r][col + c] = true; } else { _modules[row + r][col + c] = false; } } } }; const getBestMaskPattern = function() { let minLostPoint = 0; let pattern = 0; for (let i = 0; i < 8; i += 1) { makeImpl(true, i); const lostPoint = QRUtil.getLostPoint(_this); if (i == 0 || minLostPoint > lostPoint) { minLostPoint = lostPoint; pattern = i; } } return pattern; }; const setupTimingPattern = function() { for (let r = 8; r < _moduleCount - 8; r += 1) { if (_modules[r][6] != null) { continue; } _modules[r][6] = r % 2 == 0; } for (let c = 8; c < _moduleCount - 8; c += 1) { if (_modules[6][c] != null) { continue; } _modules[6][c] = c % 2 == 0; } }; const setupPositionAdjustPattern = function() { const pos = QRUtil.getPatternPosition(_typeNumber); for (let i = 0; i < pos.length; i += 1) { for (let j = 0; j < pos.length; j += 1) { const row = pos[i]; const col = pos[j]; if (_modules[row][col] != null) { continue; } for (let r = -2; r <= 2; r += 1) { for (let c = -2; c <= 2; c += 1) { if (r == -2 || r == 2 || c == -2 || c == 2 || r == 0 && c == 0) { _modules[row + r][col + c] = true; } else { _modules[row + r][col + c] = false; } } } } } }; const setupTypeNumber = function(test) { const bits = QRUtil.getBCHTypeNumber(_typeNumber); for (let i = 0; i < 18; i += 1) { const mod = !test && (bits >> i & 1) == 1; _modules[Math.floor(i / 3)][i % 3 + _moduleCount - 8 - 3] = mod; } for (let i = 0; i < 18; i += 1) { const mod = !test && (bits >> i & 1) == 1; _modules[i % 3 + _moduleCount - 8 - 3][Math.floor(i / 3)] = mod; } }; const setupTypeInfo = function(test, maskPattern) { const data = _errorCorrectionLevel << 3 | maskPattern; const bits = QRUtil.getBCHTypeInfo(data); for (let i = 0; i < 15; i += 1) { const mod = !test && (bits >> i & 1) == 1; if (i < 6) { _modules[i][8] = mod; } else if (i < 8) { _modules[i + 1][8] = mod; } else { _modules[_moduleCount - 15 + i][8] = mod; } } for (let i = 0; i < 15; i += 1) { const mod = !test && (bits >> i & 1) == 1; if (i < 8) { _modules[8][_moduleCount - i - 1] = mod; } else if (i < 9) { _modules[8][15 - i - 1 + 1] = mod; } else { _modules[8][15 - i - 1] = mod; } } _modules[_moduleCount - 8][8] = !test; }; const mapData = function(data, maskPattern) { let inc = -1; let row = _moduleCount - 1; let bitIndex = 7; let byteIndex = 0; const maskFunc = QRUtil.getMaskFunction(maskPattern); for (let col = _moduleCount - 1; col > 0; col -= 2) { if (col == 6) col -= 1; while (true) { for (let c = 0; c < 2; c += 1) { if (_modules[row][col - c] == null) { let dark = false; if (byteIndex < data.length) { dark = (data[byteIndex] >>> bitIndex & 1) == 1; } const mask = maskFunc(row, col - c); if (mask) { dark = !dark; } _modules[row][col - c] = dark; bitIndex -= 1; if (bitIndex == -1) { byteIndex += 1; bitIndex = 7; } } } row += inc; if (row < 0 || _moduleCount <= row) { row -= inc; inc = -inc; break; } } } }; const createBytes = function(buffer, rsBlocks) { let offset = 0; let maxDcCount = 0; let maxEcCount = 0; const dcdata = new Array(rsBlocks.length); const ecdata = new Array(rsBlocks.length); for (let r = 0; r < rsBlocks.length; r += 1) { const dcCount = rsBlocks[r].dataCount; const ecCount = rsBlocks[r].totalCount - dcCount; maxDcCount = Math.max(maxDcCount, dcCount); maxEcCount = Math.max(maxEcCount, ecCount); dcdata[r] = new Array(dcCount); for (let i = 0; i < dcdata[r].length; i += 1) { dcdata[r][i] = 255 & buffer.getBuffer()[i + offset]; } offset += dcCount; const rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount); const rawPoly = qrPolynomial(dcdata[r], rsPoly.getLength() - 1); const modPoly = rawPoly.mod(rsPoly); ecdata[r] = new Array(rsPoly.getLength() - 1); for (let i = 0; i < ecdata[r].length; i += 1) { const modIndex = i + modPoly.getLength() - ecdata[r].length; ecdata[r][i] = modIndex >= 0 ? modPoly.getAt(modIndex) : 0; } } let totalCodeCount = 0; for (let i = 0; i < rsBlocks.length; i += 1) { totalCodeCount += rsBlocks[i].totalCount; } const data = new Array(totalCodeCount); let index = 0; for (let i = 0; i < maxDcCount; i += 1) { for (let r = 0; r < rsBlocks.length; r += 1) { if (i < dcdata[r].length) { data[index] = dcdata[r][i]; index += 1; } } } for (let i = 0; i < maxEcCount; i += 1) { for (let r = 0; r < rsBlocks.length; r += 1) { if (i < ecdata[r].length) { data[index] = ecdata[r][i]; index += 1; } } } return data; }; const createData = function(typeNumber2, errorCorrectionLevel2, dataList) { const rsBlocks = QRRSBlock.getRSBlocks(typeNumber2, errorCorrectionLevel2); const buffer = qrBitBuffer(); for (let i = 0; i < dataList.length; i += 1) { const data = dataList[i]; buffer.put(data.getMode(), 4); buffer.put(data.getLength(), QRUtil.getLengthInBits(data.getMode(), typeNumber2)); data.write(buffer); } let totalDataCount = 0; for (let i = 0; i < rsBlocks.length; i += 1) { totalDataCount += rsBlocks[i].dataCount; } if (buffer.getLengthInBits() > totalDataCount * 8) { throw "code length overflow. (" + buffer.getLengthInBits() + ">" + totalDataCount * 8 + ")"; } if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) { buffer.put(0, 4); } while (buffer.getLengthInBits() % 8 != 0) { buffer.putBit(false); } while (true) { if (buffer.getLengthInBits() >= totalDataCount * 8) { break; } buffer.put(PAD0, 8); if (buffer.getLengthInBits() >= totalDataCount * 8) { break; } buffer.put(PAD1, 8); } return createBytes(buffer, rsBlocks); }; _this.addData = function(data, mode) { mode = mode || "Byte"; let newData = null; switch (mode) { case "Numeric": newData = qrNumber(data); break; case "Alphanumeric": newData = qrAlphaNum(data); break; case "Byte": newData = qr8BitByte(data); break; case "Kanji": newData = qrKanji(data); break; default: throw "mode:" + mode; } _dataList.push(newData); _dataCache = null; }; _this.isDark = function(row, col) { if (row < 0 || _moduleCount <= row || col < 0 || _moduleCount <= col) { throw row + "," + col; } return _modules[row][col]; }; _this.getModuleCount = function() { return _moduleCount; }; _this.make = function() { if (_typeNumber < 1) { let typeNumber2 = 1; for (; typeNumber2 < 40; typeNumber2++) { const rsBlocks = QRRSBlock.getRSBlocks(typeNumber2, _errorCorrectionLevel); const buffer = qrBitBuffer(); for (let i = 0; i < _dataList.length; i++) { const data = _dataList[i]; buffer.put(data.getMode(), 4); buffer.put(data.getLength(), QRUtil.getLengthInBits(data.getMode(), typeNumber2)); data.write(buffer); } let totalDataCount = 0; for (let i = 0; i < rsBlocks.length; i++) { totalDataCount += rsBlocks[i].dataCount; } if (buffer.getLengthInBits() <= totalDataCount * 8) { break; } } _typeNumber = typeNumber2; } makeImpl(false, getBestMaskPattern()); }; _this.createTableTag = function(cellSize, margin) { cellSize = cellSize || 2; margin = typeof margin == "undefined" ? cellSize * 4 : margin; let qrHtml = ""; qrHtml += '' + escapeXml(title.text) + "" : ""; qrSvg += alt.text ? '' + escapeXml(alt.text) + "" : ""; qrSvg += ''; qrSvg += '": escaped += ">"; break; case "&": escaped += "&"; break; case '"': escaped += """; break; default: escaped += c; break; } } return escaped; }; const _createHalfASCII = function(margin) { const cellSize = 1; margin = typeof margin == "undefined" ? cellSize * 2 : margin; const size = _this.getModuleCount() * cellSize + margin * 2; const min = margin; const max = size - margin; let y, x, r1, r2, p; const blocks = { "██": "█", "█ ": "▀", " █": "▄", " ": " " }; const blocksLastLineNoMargin = { "██": "▀", "█ ": "▀", " █": " ", " ": " " }; let ascii = ""; for (y = 0; y < size; y += 2) { r1 = Math.floor((y - min) / cellSize); r2 = Math.floor((y + 1 - min) / cellSize); for (x = 0; x < size; x += 1) { p = "█"; if (min <= x && x < max && min <= y && y < max && _this.isDark(r1, Math.floor((x - min) / cellSize))) { p = " "; } if (min <= x && x < max && min <= y + 1 && y + 1 < max && _this.isDark(r2, Math.floor((x - min) / cellSize))) { p += " "; } else { p += "█"; } ascii += margin < 1 && y + 1 >= max ? blocksLastLineNoMargin[p] : blocks[p]; } ascii += "\n"; } if (size % 2 && margin > 0) { return ascii.substring(0, ascii.length - size - 1) + Array(size + 1).join("▀"); } return ascii.substring(0, ascii.length - 1); }; _this.createASCII = function(cellSize, margin) { cellSize = cellSize || 1; if (cellSize < 2) { return _createHalfASCII(margin); } cellSize -= 1; margin = typeof margin == "undefined" ? cellSize * 2 : margin; const size = _this.getModuleCount() * cellSize + margin * 2; const min = margin; const max = size - margin; let y, x, r, p; const white = Array(cellSize + 1).join("██"); const black = Array(cellSize + 1).join(" "); let ascii = ""; let line = ""; for (y = 0; y < size; y += 1) { r = Math.floor((y - min) / cellSize); line = ""; for (x = 0; x < size; x += 1) { p = 1; if (min <= x && x < max && min <= y && y < max && _this.isDark(r, Math.floor((x - min) / cellSize))) { p = 0; } line += p ? white : black; } for (r = 0; r < cellSize; r += 1) { ascii += line + "\n"; } } return ascii.substring(0, ascii.length - 1); }; _this.renderTo2dContext = function(context2, cellSize) { cellSize = cellSize || 2; const length = _this.getModuleCount(); for (let row = 0; row < length; row++) { for (let col = 0; col < length; col++) { context2.fillStyle = _this.isDark(row, col) ? "black" : "white"; context2.fillRect(col * cellSize, row * cellSize, cellSize, cellSize); } } }; return _this; }; qrcode.stringToBytes = function(s) { const bytes = []; for (let i = 0; i < s.length; i += 1) { const c = s.charCodeAt(i); bytes.push(c & 255); } return bytes; }; qrcode.createStringToBytes = function(unicodeData, numChars) { const unicodeMap = (function() { const bin = base64DecodeInputStream(unicodeData); const read = function() { const b = bin.read(); if (b == -1) throw "eof"; return b; }; let count = 0; const unicodeMap2 = {}; while (true) { const b0 = bin.read(); if (b0 == -1) break; const b1 = read(); const b2 = read(); const b3 = read(); const k = String.fromCharCode(b0 << 8 | b1); const v = b2 << 8 | b3; unicodeMap2[k] = v; count += 1; } if (count != numChars) { throw count + " != " + numChars; } return unicodeMap2; })(); const unknownChar = "?".charCodeAt(0); return function(s) { const bytes = []; for (let i = 0; i < s.length; i += 1) { const c = s.charCodeAt(i); if (c < 128) { bytes.push(c); } else { const b = unicodeMap[s.charAt(i)]; if (typeof b == "number") { if ((b & 255) == b) { bytes.push(b); } else { bytes.push(b >>> 8); bytes.push(b & 255); } } else { bytes.push(unknownChar); } } } return bytes; }; }; var QRMode = { MODE_NUMBER: 1 << 0, MODE_ALPHA_NUM: 1 << 1, MODE_8BIT_BYTE: 1 << 2, MODE_KANJI: 1 << 3 }; var QRErrorCorrectionLevel = { L: 1, M: 0, Q: 3, H: 2 }; var QRMaskPattern = { PATTERN000: 0, PATTERN001: 1, PATTERN010: 2, PATTERN011: 3, PATTERN100: 4, PATTERN101: 5, PATTERN110: 6, PATTERN111: 7 }; var QRUtil = (function() { const PATTERN_POSITION_TABLE = [ [], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34], [6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50], [6, 30, 54], [6, 32, 58], [6, 34, 62], [6, 26, 46, 66], [6, 26, 48, 70], [6, 26, 50, 74], [6, 30, 54, 78], [6, 30, 56, 82], [6, 30, 58, 86], [6, 34, 62, 90], [6, 28, 50, 72, 94], [6, 26, 50, 74, 98], [6, 30, 54, 78, 102], [6, 28, 54, 80, 106], [6, 32, 58, 84, 110], [6, 30, 58, 86, 114], [6, 34, 62, 90, 118], [6, 26, 50, 74, 98, 122], [6, 30, 54, 78, 102, 126], [6, 26, 52, 78, 104, 130], [6, 30, 56, 82, 108, 134], [6, 34, 60, 86, 112, 138], [6, 30, 58, 86, 114, 142], [6, 34, 62, 90, 118, 146], [6, 30, 54, 78, 102, 126, 150], [6, 24, 50, 76, 102, 128, 154], [6, 28, 54, 80, 106, 132, 158], [6, 32, 58, 84, 110, 136, 162], [6, 26, 54, 82, 110, 138, 166], [6, 30, 58, 86, 114, 142, 170] ]; const G15 = 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0; const G18 = 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0; const G15_MASK = 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1; const _this = {}; const getBCHDigit = function(data) { let digit = 0; while (data != 0) { digit += 1; data >>>= 1; } return digit; }; _this.getBCHTypeInfo = function(data) { let d = data << 10; while (getBCHDigit(d) - getBCHDigit(G15) >= 0) { d ^= G15 << getBCHDigit(d) - getBCHDigit(G15); } return (data << 10 | d) ^ G15_MASK; }; _this.getBCHTypeNumber = function(data) { let d = data << 12; while (getBCHDigit(d) - getBCHDigit(G18) >= 0) { d ^= G18 << getBCHDigit(d) - getBCHDigit(G18); } return data << 12 | d; }; _this.getPatternPosition = function(typeNumber) { return PATTERN_POSITION_TABLE[typeNumber - 1]; }; _this.getMaskFunction = function(maskPattern) { switch (maskPattern) { case QRMaskPattern.PATTERN000: return function(i, j) { return (i + j) % 2 == 0; }; case QRMaskPattern.PATTERN001: return function(i, j) { return i % 2 == 0; }; case QRMaskPattern.PATTERN010: return function(i, j) { return j % 3 == 0; }; case QRMaskPattern.PATTERN011: return function(i, j) { return (i + j) % 3 == 0; }; case QRMaskPattern.PATTERN100: return function(i, j) { return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 == 0; }; case QRMaskPattern.PATTERN101: return function(i, j) { return i * j % 2 + i * j % 3 == 0; }; case QRMaskPattern.PATTERN110: return function(i, j) { return (i * j % 2 + i * j % 3) % 2 == 0; }; case QRMaskPattern.PATTERN111: return function(i, j) { return (i * j % 3 + (i + j) % 2) % 2 == 0; }; default: throw "bad maskPattern:" + maskPattern; } }; _this.getErrorCorrectPolynomial = function(errorCorrectLength) { let a = qrPolynomial([1], 0); for (let i = 0; i < errorCorrectLength; i += 1) { a = a.multiply(qrPolynomial([1, QRMath.gexp(i)], 0)); } return a; }; _this.getLengthInBits = function(mode, type) { if (1 <= type && type < 10) { switch (mode) { case QRMode.MODE_NUMBER: return 10; case QRMode.MODE_ALPHA_NUM: return 9; case QRMode.MODE_8BIT_BYTE: return 8; case QRMode.MODE_KANJI: return 8; default: throw "mode:" + mode; } } else if (type < 27) { switch (mode) { case QRMode.MODE_NUMBER: return 12; case QRMode.MODE_ALPHA_NUM: return 11; case QRMode.MODE_8BIT_BYTE: return 16; case QRMode.MODE_KANJI: return 10; default: throw "mode:" + mode; } } else if (type < 41) { switch (mode) { case QRMode.MODE_NUMBER: return 14; case QRMode.MODE_ALPHA_NUM: return 13; case QRMode.MODE_8BIT_BYTE: return 16; case QRMode.MODE_KANJI: return 12; default: throw "mode:" + mode; } } else { throw "type:" + type; } }; _this.getLostPoint = function(qrcode2) { const moduleCount = qrcode2.getModuleCount(); let lostPoint = 0; for (let row = 0; row < moduleCount; row += 1) { for (let col = 0; col < moduleCount; col += 1) { let sameCount = 0; const dark = qrcode2.isDark(row, col); for (let r = -1; r <= 1; r += 1) { if (row + r < 0 || moduleCount <= row + r) { continue; } for (let c = -1; c <= 1; c += 1) { if (col + c < 0 || moduleCount <= col + c) { continue; } if (r == 0 && c == 0) { continue; } if (dark == qrcode2.isDark(row + r, col + c)) { sameCount += 1; } } } if (sameCount > 5) { lostPoint += 3 + sameCount - 5; } } } ; for (let row = 0; row < moduleCount - 1; row += 1) { for (let col = 0; col < moduleCount - 1; col += 1) { let count = 0; if (qrcode2.isDark(row, col)) count += 1; if (qrcode2.isDark(row + 1, col)) count += 1; if (qrcode2.isDark(row, col + 1)) count += 1; if (qrcode2.isDark(row + 1, col + 1)) count += 1; if (count == 0 || count == 4) { lostPoint += 3; } } } for (let row = 0; row < moduleCount; row += 1) { for (let col = 0; col < moduleCount - 6; col += 1) { if (qrcode2.isDark(row, col) && !qrcode2.isDark(row, col + 1) && qrcode2.isDark(row, col + 2) && qrcode2.isDark(row, col + 3) && qrcode2.isDark(row, col + 4) && !qrcode2.isDark(row, col + 5) && qrcode2.isDark(row, col + 6)) { lostPoint += 40; } } } for (let col = 0; col < moduleCount; col += 1) { for (let row = 0; row < moduleCount - 6; row += 1) { if (qrcode2.isDark(row, col) && !qrcode2.isDark(row + 1, col) && qrcode2.isDark(row + 2, col) && qrcode2.isDark(row + 3, col) && qrcode2.isDark(row + 4, col) && !qrcode2.isDark(row + 5, col) && qrcode2.isDark(row + 6, col)) { lostPoint += 40; } } } let darkCount = 0; for (let col = 0; col < moduleCount; col += 1) { for (let row = 0; row < moduleCount; row += 1) { if (qrcode2.isDark(row, col)) { darkCount += 1; } } } const ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5; lostPoint += ratio * 10; return lostPoint; }; return _this; })(); var QRMath = (function() { const EXP_TABLE = new Array(256); const LOG_TABLE = new Array(256); for (let i = 0; i < 8; i += 1) { EXP_TABLE[i] = 1 << i; } for (let i = 8; i < 256; i += 1) { EXP_TABLE[i] = EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ EXP_TABLE[i - 6] ^ EXP_TABLE[i - 8]; } for (let i = 0; i < 255; i += 1) { LOG_TABLE[EXP_TABLE[i]] = i; } const _this = {}; _this.glog = function(n) { if (n < 1) { throw "glog(" + n + ")"; } return LOG_TABLE[n]; }; _this.gexp = function(n) { while (n < 0) { n += 255; } while (n >= 256) { n -= 255; } return EXP_TABLE[n]; }; return _this; })(); var qrPolynomial = function(num, shift) { if (typeof num.length == "undefined") { throw num.length + "/" + shift; } const _num = (function() { let offset = 0; while (offset < num.length && num[offset] == 0) { offset += 1; } const _num2 = new Array(num.length - offset + shift); for (let i = 0; i < num.length - offset; i += 1) { _num2[i] = num[i + offset]; } return _num2; })(); const _this = {}; _this.getAt = function(index) { return _num[index]; }; _this.getLength = function() { return _num.length; }; _this.multiply = function(e) { const num2 = new Array(_this.getLength() + e.getLength() - 1); for (let i = 0; i < _this.getLength(); i += 1) { for (let j = 0; j < e.getLength(); j += 1) { num2[i + j] ^= QRMath.gexp(QRMath.glog(_this.getAt(i)) + QRMath.glog(e.getAt(j))); } } return qrPolynomial(num2, 0); }; _this.mod = function(e) { if (_this.getLength() - e.getLength() < 0) { return _this; } const ratio = QRMath.glog(_this.getAt(0)) - QRMath.glog(e.getAt(0)); const num2 = new Array(_this.getLength()); for (let i = 0; i < _this.getLength(); i += 1) { num2[i] = _this.getAt(i); } for (let i = 0; i < e.getLength(); i += 1) { num2[i] ^= QRMath.gexp(QRMath.glog(e.getAt(i)) + ratio); } return qrPolynomial(num2, 0).mod(e); }; return _this; }; var QRRSBlock = (function() { const RS_BLOCK_TABLE = [ // L // M // Q // H // 1 [1, 26, 19], [1, 26, 16], [1, 26, 13], [1, 26, 9], // 2 [1, 44, 34], [1, 44, 28], [1, 44, 22], [1, 44, 16], // 3 [1, 70, 55], [1, 70, 44], [2, 35, 17], [2, 35, 13], // 4 [1, 100, 80], [2, 50, 32], [2, 50, 24], [4, 25, 9], // 5 [1, 134, 108], [2, 67, 43], [2, 33, 15, 2, 34, 16], [2, 33, 11, 2, 34, 12], // 6 [2, 86, 68], [4, 43, 27], [4, 43, 19], [4, 43, 15], // 7 [2, 98, 78], [4, 49, 31], [2, 32, 14, 4, 33, 15], [4, 39, 13, 1, 40, 14], // 8 [2, 121, 97], [2, 60, 38, 2, 61, 39], [4, 40, 18, 2, 41, 19], [4, 40, 14, 2, 41, 15], // 9 [2, 146, 116], [3, 58, 36, 2, 59, 37], [4, 36, 16, 4, 37, 17], [4, 36, 12, 4, 37, 13], // 10 [2, 86, 68, 2, 87, 69], [4, 69, 43, 1, 70, 44], [6, 43, 19, 2, 44, 20], [6, 43, 15, 2, 44, 16], // 11 [4, 101, 81], [1, 80, 50, 4, 81, 51], [4, 50, 22, 4, 51, 23], [3, 36, 12, 8, 37, 13], // 12 [2, 116, 92, 2, 117, 93], [6, 58, 36, 2, 59, 37], [4, 46, 20, 6, 47, 21], [7, 42, 14, 4, 43, 15], // 13 [4, 133, 107], [8, 59, 37, 1, 60, 38], [8, 44, 20, 4, 45, 21], [12, 33, 11, 4, 34, 12], // 14 [3, 145, 115, 1, 146, 116], [4, 64, 40, 5, 65, 41], [11, 36, 16, 5, 37, 17], [11, 36, 12, 5, 37, 13], // 15 [5, 109, 87, 1, 110, 88], [5, 65, 41, 5, 66, 42], [5, 54, 24, 7, 55, 25], [11, 36, 12, 7, 37, 13], // 16 [5, 122, 98, 1, 123, 99], [7, 73, 45, 3, 74, 46], [15, 43, 19, 2, 44, 20], [3, 45, 15, 13, 46, 16], // 17 [1, 135, 107, 5, 136, 108], [10, 74, 46, 1, 75, 47], [1, 50, 22, 15, 51, 23], [2, 42, 14, 17, 43, 15], // 18 [5, 150, 120, 1, 151, 121], [9, 69, 43, 4, 70, 44], [17, 50, 22, 1, 51, 23], [2, 42, 14, 19, 43, 15], // 19 [3, 141, 113, 4, 142, 114], [3, 70, 44, 11, 71, 45], [17, 47, 21, 4, 48, 22], [9, 39, 13, 16, 40, 14], // 20 [3, 135, 107, 5, 136, 108], [3, 67, 41, 13, 68, 42], [15, 54, 24, 5, 55, 25], [15, 43, 15, 10, 44, 16], // 21 [4, 144, 116, 4, 145, 117], [17, 68, 42], [17, 50, 22, 6, 51, 23], [19, 46, 16, 6, 47, 17], // 22 [2, 139, 111, 7, 140, 112], [17, 74, 46], [7, 54, 24, 16, 55, 25], [34, 37, 13], // 23 [4, 151, 121, 5, 152, 122], [4, 75, 47, 14, 76, 48], [11, 54, 24, 14, 55, 25], [16, 45, 15, 14, 46, 16], // 24 [6, 147, 117, 4, 148, 118], [6, 73, 45, 14, 74, 46], [11, 54, 24, 16, 55, 25], [30, 46, 16, 2, 47, 17], // 25 [8, 132, 106, 4, 133, 107], [8, 75, 47, 13, 76, 48], [7, 54, 24, 22, 55, 25], [22, 45, 15, 13, 46, 16], // 26 [10, 142, 114, 2, 143, 115], [19, 74, 46, 4, 75, 47], [28, 50, 22, 6, 51, 23], [33, 46, 16, 4, 47, 17], // 27 [8, 152, 122, 4, 153, 123], [22, 73, 45, 3, 74, 46], [8, 53, 23, 26, 54, 24], [12, 45, 15, 28, 46, 16], // 28 [3, 147, 117, 10, 148, 118], [3, 73, 45, 23, 74, 46], [4, 54, 24, 31, 55, 25], [11, 45, 15, 31, 46, 16], // 29 [7, 146, 116, 7, 147, 117], [21, 73, 45, 7, 74, 46], [1, 53, 23, 37, 54, 24], [19, 45, 15, 26, 46, 16], // 30 [5, 145, 115, 10, 146, 116], [19, 75, 47, 10, 76, 48], [15, 54, 24, 25, 55, 25], [23, 45, 15, 25, 46, 16], // 31 [13, 145, 115, 3, 146, 116], [2, 74, 46, 29, 75, 47], [42, 54, 24, 1, 55, 25], [23, 45, 15, 28, 46, 16], // 32 [17, 145, 115], [10, 74, 46, 23, 75, 47], [10, 54, 24, 35, 55, 25], [19, 45, 15, 35, 46, 16], // 33 [17, 145, 115, 1, 146, 116], [14, 74, 46, 21, 75, 47], [29, 54, 24, 19, 55, 25], [11, 45, 15, 46, 46, 16], // 34 [13, 145, 115, 6, 146, 116], [14, 74, 46, 23, 75, 47], [44, 54, 24, 7, 55, 25], [59, 46, 16, 1, 47, 17], // 35 [12, 151, 121, 7, 152, 122], [12, 75, 47, 26, 76, 48], [39, 54, 24, 14, 55, 25], [22, 45, 15, 41, 46, 16], // 36 [6, 151, 121, 14, 152, 122], [6, 75, 47, 34, 76, 48], [46, 54, 24, 10, 55, 25], [2, 45, 15, 64, 46, 16], // 37 [17, 152, 122, 4, 153, 123], [29, 74, 46, 14, 75, 47], [49, 54, 24, 10, 55, 25], [24, 45, 15, 46, 46, 16], // 38 [4, 152, 122, 18, 153, 123], [13, 74, 46, 32, 75, 47], [48, 54, 24, 14, 55, 25], [42, 45, 15, 32, 46, 16], // 39 [20, 147, 117, 4, 148, 118], [40, 75, 47, 7, 76, 48], [43, 54, 24, 22, 55, 25], [10, 45, 15, 67, 46, 16], // 40 [19, 148, 118, 6, 149, 119], [18, 75, 47, 31, 76, 48], [34, 54, 24, 34, 55, 25], [20, 45, 15, 61, 46, 16] ]; const qrRSBlock = function(totalCount, dataCount) { const _this2 = {}; _this2.totalCount = totalCount; _this2.dataCount = dataCount; return _this2; }; const _this = {}; const getRsBlockTable = function(typeNumber, errorCorrectionLevel) { switch (errorCorrectionLevel) { case QRErrorCorrectionLevel.L: return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0]; case QRErrorCorrectionLevel.M: return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1]; case QRErrorCorrectionLevel.Q: return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2]; case QRErrorCorrectionLevel.H: return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3]; default: return void 0; } }; _this.getRSBlocks = function(typeNumber, errorCorrectionLevel) { const rsBlock = getRsBlockTable(typeNumber, errorCorrectionLevel); if (typeof rsBlock == "undefined") { throw "bad rs block @ typeNumber:" + typeNumber + "/errorCorrectionLevel:" + errorCorrectionLevel; } const length = rsBlock.length / 3; const list = []; for (let i = 0; i < length; i += 1) { const count = rsBlock[i * 3 + 0]; const totalCount = rsBlock[i * 3 + 1]; const dataCount = rsBlock[i * 3 + 2]; for (let j = 0; j < count; j += 1) { list.push(qrRSBlock(totalCount, dataCount)); } } return list; }; return _this; })(); var qrBitBuffer = function() { const _buffer = []; let _length = 0; const _this = {}; _this.getBuffer = function() { return _buffer; }; _this.getAt = function(index) { const bufIndex = Math.floor(index / 8); return (_buffer[bufIndex] >>> 7 - index % 8 & 1) == 1; }; _this.put = function(num, length) { for (let i = 0; i < length; i += 1) { _this.putBit((num >>> length - i - 1 & 1) == 1); } }; _this.getLengthInBits = function() { return _length; }; _this.putBit = function(bit) { const bufIndex = Math.floor(_length / 8); if (_buffer.length <= bufIndex) { _buffer.push(0); } if (bit) { _buffer[bufIndex] |= 128 >>> _length % 8; } _length += 1; }; return _this; }; var qrNumber = function(data) { const _mode = QRMode.MODE_NUMBER; const _data = data; const _this = {}; _this.getMode = function() { return _mode; }; _this.getLength = function(buffer) { return _data.length; }; _this.write = function(buffer) { const data2 = _data; let i = 0; while (i + 2 < data2.length) { buffer.put(strToNum(data2.substring(i, i + 3)), 10); i += 3; } if (i < data2.length) { if (data2.length - i == 1) { buffer.put(strToNum(data2.substring(i, i + 1)), 4); } else if (data2.length - i == 2) { buffer.put(strToNum(data2.substring(i, i + 2)), 7); } } }; const strToNum = function(s) { let num = 0; for (let i = 0; i < s.length; i += 1) { num = num * 10 + chatToNum(s.charAt(i)); } return num; }; const chatToNum = function(c) { if ("0" <= c && c <= "9") { return c.charCodeAt(0) - "0".charCodeAt(0); } throw "illegal char :" + c; }; return _this; }; var qrAlphaNum = function(data) { const _mode = QRMode.MODE_ALPHA_NUM; const _data = data; const _this = {}; _this.getMode = function() { return _mode; }; _this.getLength = function(buffer) { return _data.length; }; _this.write = function(buffer) { const s = _data; let i = 0; while (i + 1 < s.length) { buffer.put( getCode(s.charAt(i)) * 45 + getCode(s.charAt(i + 1)), 11 ); i += 2; } if (i < s.length) { buffer.put(getCode(s.charAt(i)), 6); } }; const getCode = function(c) { if ("0" <= c && c <= "9") { return c.charCodeAt(0) - "0".charCodeAt(0); } else if ("A" <= c && c <= "Z") { return c.charCodeAt(0) - "A".charCodeAt(0) + 10; } else { switch (c) { case " ": return 36; case "$": return 37; case "%": return 38; case "*": return 39; case "+": return 40; case "-": return 41; case ".": return 42; case "/": return 43; case ":": return 44; default: throw "illegal char :" + c; } } }; return _this; }; var qr8BitByte = function(data) { const _mode = QRMode.MODE_8BIT_BYTE; const _data = data; const _bytes = qrcode.stringToBytes(data); const _this = {}; _this.getMode = function() { return _mode; }; _this.getLength = function(buffer) { return _bytes.length; }; _this.write = function(buffer) { for (let i = 0; i < _bytes.length; i += 1) { buffer.put(_bytes[i], 8); } }; return _this; }; var qrKanji = function(data) { const _mode = QRMode.MODE_KANJI; const _data = data; const stringToBytes2 = qrcode.stringToBytes; !(function(c, code) { const test = stringToBytes2(c); if (test.length != 2 || (test[0] << 8 | test[1]) != code) { throw "sjis not supported."; } })("友", 38726); const _bytes = stringToBytes2(data); const _this = {}; _this.getMode = function() { return _mode; }; _this.getLength = function(buffer) { return ~~(_bytes.length / 2); }; _this.write = function(buffer) { const data2 = _bytes; let i = 0; while (i + 1 < data2.length) { let c = (255 & data2[i]) << 8 | 255 & data2[i + 1]; if (33088 <= c && c <= 40956) { c -= 33088; } else if (57408 <= c && c <= 60351) { c -= 49472; } else { throw "illegal char at " + (i + 1) + "/" + c; } c = (c >>> 8 & 255) * 192 + (c & 255); buffer.put(c, 13); i += 2; } if (i < data2.length) { throw "illegal char at " + (i + 1); } }; return _this; }; var byteArrayOutputStream = function() { const _bytes = []; const _this = {}; _this.writeByte = function(b) { _bytes.push(b & 255); }; _this.writeShort = function(i) { _this.writeByte(i); _this.writeByte(i >>> 8); }; _this.writeBytes = function(b, off, len) { off = off || 0; len = len || b.length; for (let i = 0; i < len; i += 1) { _this.writeByte(b[i + off]); } }; _this.writeString = function(s) { for (let i = 0; i < s.length; i += 1) { _this.writeByte(s.charCodeAt(i)); } }; _this.toByteArray = function() { return _bytes; }; _this.toString = function() { let s = ""; s += "["; for (let i = 0; i < _bytes.length; i += 1) { if (i > 0) { s += ","; } s += _bytes[i]; } s += "]"; return s; }; return _this; }; var base64EncodeOutputStream = function() { let _buffer = 0; let _buflen = 0; let _length = 0; let _base64 = ""; const _this = {}; const writeEncoded = function(b) { _base64 += String.fromCharCode(encode(b & 63)); }; const encode = function(n) { if (n < 0) { throw "n:" + n; } else if (n < 26) { return 65 + n; } else if (n < 52) { return 97 + (n - 26); } else if (n < 62) { return 48 + (n - 52); } else if (n == 62) { return 43; } else if (n == 63) { return 47; } else { throw "n:" + n; } }; _this.writeByte = function(n) { _buffer = _buffer << 8 | n & 255; _buflen += 8; _length += 1; while (_buflen >= 6) { writeEncoded(_buffer >>> _buflen - 6); _buflen -= 6; } }; _this.flush = function() { if (_buflen > 0) { writeEncoded(_buffer << 6 - _buflen); _buffer = 0; _buflen = 0; } if (_length % 3 != 0) { const padlen = 3 - _length % 3; for (let i = 0; i < padlen; i += 1) { _base64 += "="; } } }; _this.toString = function() { return _base64; }; return _this; }; var base64DecodeInputStream = function(str) { const _str = str; let _pos = 0; let _buffer = 0; let _buflen = 0; const _this = {}; _this.read = function() { while (_buflen < 8) { if (_pos >= _str.length) { if (_buflen == 0) { return -1; } throw "unexpected end of file./" + _buflen; } const c = _str.charAt(_pos); _pos += 1; if (c == "=") { _buflen = 0; return -1; } else if (c.match(/^\s$/)) { continue; } _buffer = _buffer << 6 | decode(c.charCodeAt(0)); _buflen += 6; } const n = _buffer >>> _buflen - 8 & 255; _buflen -= 8; return n; }; const decode = function(c) { if (65 <= c && c <= 90) { return c - 65; } else if (97 <= c && c <= 122) { return c - 97 + 26; } else if (48 <= c && c <= 57) { return c - 48 + 52; } else if (c == 43) { return 62; } else if (c == 47) { return 63; } else { throw "c:" + c; } }; return _this; }; var gifImage = function(width, height) { const _width = width; const _height = height; const _data = new Array(width * height); const _this = {}; _this.setPixel = function(x, y, pixel) { _data[y * _width + x] = pixel; }; _this.write = function(out) { out.writeString("GIF87a"); out.writeShort(_width); out.writeShort(_height); out.writeByte(128); out.writeByte(0); out.writeByte(0); out.writeByte(0); out.writeByte(0); out.writeByte(0); out.writeByte(255); out.writeByte(255); out.writeByte(255); out.writeString(","); out.writeShort(0); out.writeShort(0); out.writeShort(_width); out.writeShort(_height); out.writeByte(0); const lzwMinCodeSize = 2; const raster = getLZWRaster(lzwMinCodeSize); out.writeByte(lzwMinCodeSize); let offset = 0; while (raster.length - offset > 255) { out.writeByte(255); out.writeBytes(raster, offset, 255); offset += 255; } out.writeByte(raster.length - offset); out.writeBytes(raster, offset, raster.length - offset); out.writeByte(0); out.writeString(";"); }; const bitOutputStream = function(out) { const _out = out; let _bitLength = 0; let _bitBuffer = 0; const _this2 = {}; _this2.write = function(data, length) { if (data >>> length != 0) { throw "length over"; } while (_bitLength + length >= 8) { _out.writeByte(255 & (data << _bitLength | _bitBuffer)); length -= 8 - _bitLength; data >>>= 8 - _bitLength; _bitBuffer = 0; _bitLength = 0; } _bitBuffer = data << _bitLength | _bitBuffer; _bitLength = _bitLength + length; }; _this2.flush = function() { if (_bitLength > 0) { _out.writeByte(_bitBuffer); } }; return _this2; }; const getLZWRaster = function(lzwMinCodeSize) { const clearCode = 1 << lzwMinCodeSize; const endCode = (1 << lzwMinCodeSize) + 1; let bitLength = lzwMinCodeSize + 1; const table = lzwTable(); for (let i = 0; i < clearCode; i += 1) { table.add(String.fromCharCode(i)); } table.add(String.fromCharCode(clearCode)); table.add(String.fromCharCode(endCode)); const byteOut = byteArrayOutputStream(); const bitOut = bitOutputStream(byteOut); bitOut.write(clearCode, bitLength); let dataIndex = 0; let s = String.fromCharCode(_data[dataIndex]); dataIndex += 1; while (dataIndex < _data.length) { const c = String.fromCharCode(_data[dataIndex]); dataIndex += 1; if (table.contains(s + c)) { s = s + c; } else { bitOut.write(table.indexOf(s), bitLength); if (table.size() < 4095) { if (table.size() == 1 << bitLength) { bitLength += 1; } table.add(s + c); } s = c; } } bitOut.write(table.indexOf(s), bitLength); bitOut.write(endCode, bitLength); bitOut.flush(); return byteOut.toByteArray(); }; const lzwTable = function() { const _map = {}; let _size = 0; const _this2 = {}; _this2.add = function(key) { if (_this2.contains(key)) { throw "dup key:" + key; } _map[key] = _size; _size += 1; }; _this2.size = function() { return _size; }; _this2.indexOf = function(key) { return _map[key]; }; _this2.contains = function(key) { return typeof _map[key] != "undefined"; }; return _this2; }; return _this; }; var createDataURL = function(width, height, getPixel) { const gif = gifImage(width, height); for (let y = 0; y < height; y += 1) { for (let x = 0; x < width; x += 1) { gif.setPixel(x, y, getPixel(x, y)); } } const b = byteArrayOutputStream(); gif.write(b); const base64 = base64EncodeOutputStream(); const bytes = b.toByteArray(); for (let i = 0; i < bytes.length; i += 1) { base64.writeByte(bytes[i]); } base64.flush(); return "data:image/gif;base64," + base64; }; var qrcode_default = qrcode; var stringToBytes = qrcode.stringToBytes; // src/scripts/steam-wishlist-prices/ui/screenshot-export.ts var SCREENSHOT_WIDTHS = { mobile: 480, pc: 1280 }; var SCREENSHOT_SCALE = 2; var JPEG_MAX_HEIGHT = 65e3; var JPEG_QUALITY = 0.86; var OPTIONS_KEY = "wishlist-screenshot-options-v1"; var PLUGIN_URL = "https://greasyfork.org/zh-CN/scripts/595010"; var EMPTY_IMAGE = "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='184' height='69'/%3E"; var IMAGE_CONCURRENCY = 16; var COVER_JPEG_QUALITY = 0.92; var capsuleCache = /* @__PURE__ */ new Map(); var imageQueue = []; var activeImages = 0; var SCREENSHOT_STYLE_PROPERTIES = [ "display", "position", "box-sizing", "min-width", "min-height", "max-width", "max-height", "margin", "padding", "border", "border-radius", "background", "color", "opacity", "visibility", "font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-align", "text-decoration", "text-transform", "white-space", "overflow-wrap", "word-break", "overflow", "text-overflow", "object-fit", "box-shadow", "outline", "outline-offset", "flex", "flex-direction", "flex-wrap", "align-items", "align-self", "justify-content", "gap", "row-gap", "column-gap" ]; var escapeHtml4 = (value) => value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); var wishlistQrSvg = (url) => { const code = qrcode_default(0, "M"); code.addData(url); code.make(); return code.createSvgTag({ margin: 0, scalable: true }).replace(" { const pages = []; let page = []; let height = 0; for (let index = 0; index < heights.length; index++) { const next = Math.ceil(heights[index]); if (next > availableHeight) throw new Error("单款游戏内容过长,请选择 PC 版导出"); if (page.length && height + 8 + next > availableHeight) { pages.push(page); page = []; height = 0; } height += (page.length ? 8 : 0) + next; page.push(index); } if (page.length || pages.length === 0) pages.push(page); return pages; }; var screenshotHtml = (snapshot, options) => `

Steam ${escapeHtml4(snapshot.steamName)} 愿望单

账户区:${escapeHtml4(snapshot.home)} 比价区:${snapshot.countries.map(escapeHtml4).join(" / ")}
${options.includeWishlistQr ? wishlistQrSvg(snapshot.wishlistUrl) : ""}

${escapeHtml4(snapshot.summary)}

${escapeHtml4(snapshot.generatedAt)}

${snapshot.listHtml}
${options.includeIntro ? `` : ""}`; var blobDataUrl = (blob) => new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(String(reader.result)); reader.onerror = () => reject(new Error("封面读取失败")); reader.readAsDataURL(blob); }); var copyDecodedImage = (img) => { const canvas = document.createElement("canvas"); canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; try { const context2 = canvas.getContext("2d"); if (!context2) return ""; context2.drawImage(img, 0, 0); const data = canvas.toDataURL("image/jpeg", COVER_JPEG_QUALITY); return data.startsWith("data:image/jpeg") ? data : ""; } catch { return ""; } finally { canvas.width = 0; canvas.height = 0; } }; var loadedReportCapsules = (root) => { const capsules = /* @__PURE__ */ new Map(); root.querySelectorAll("img").forEach((img) => { if (!img.complete || !img.naturalWidth || img.closest(".wl-shot-stage")) return; const current = img.currentSrc || img.src; if (current.startsWith("https://shared.akamai.steamstatic.com/") && !capsules.has(current)) { capsules.set(current, img); } }); return capsules; }; var readCapsule = async (url, loadedImage) => { if (url.startsWith("data:image/")) return url; if (new URL(url).origin !== "https://shared.akamai.steamstatic.com") return EMPTY_IMAGE; const copied = loadedImage && copyDecodedImage(loadedImage); if (copied) return copied; if (activeImages >= IMAGE_CONCURRENCY) await new Promise((resolve) => imageQueue.push(resolve)); else activeImages++; try { let blob; try { const res = await fetch(url, { cache: "force-cache", credentials: "omit", signal: AbortSignal.timeout(5e3) }); if (!res.ok) throw new Error(); blob = await res.blob(); } catch { if (typeof GM_xmlhttpRequest !== "function") throw new Error(); blob = await new Promise((resolve, reject) => GM_xmlhttpRequest({ method: "GET", url, responseType: "blob", anonymous: true, timeout: 8e3, onload: (res) => res.status === 200 && res.response instanceof Blob ? resolve(res.response) : reject(new Error()), onerror: () => reject(new Error()), ontimeout: () => reject(new Error()), onabort: () => reject(new Error()) })); } return await blobDataUrl(blob); } catch { return EMPTY_IMAGE; } finally { const next = imageQueue.shift(); if (next) next(); else activeImages--; } }; var cachedCapsule = (url, loadedImage) => { const cached = capsuleCache.get(url); if (cached) return cached; if (capsuleCache.size >= 1e3) capsuleCache.delete(capsuleCache.keys().next().value); const pending = readCapsule(url, loadedImage).then((value) => { if (value === EMPTY_IMAGE) capsuleCache.delete(url); return value; }); capsuleCache.set(url, pending); return pending; }; var createDocument = (snapshot, options) => { const doc = document.createElement("div"); doc.className = `wl-shot-document${options.layout === "mobile" ? " is-mobile" : ""}`; doc.style.width = `${SCREENSHOT_WIDTHS[options.layout]}px`; doc.innerHTML = screenshotHtml(snapshot, options); doc.querySelectorAll(".wl-tag-edit, .wl-wishlist-remove").forEach((button) => button.remove()); doc.querySelectorAll("img").forEach((img) => { img.dataset.shotSrc = img.src; img.src = EMPTY_IMAGE; img.loading = "eager"; img.removeAttribute("srcset"); }); return doc; }; var downloadBlob = (blob, name) => { const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = name; document.body.appendChild(link); link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(url), 6e4); }; var canvasHeightLimit = 0; var maxJpegHeight = () => { if (canvasHeightLimit) return canvasHeightLimit; const canvas = document.createElement("canvas"); canvas.width = 1; try { for (const height of [JPEG_MAX_HEIGHT, 32760, 16380, 8190]) { try { canvas.height = height; const context2 = canvas.getContext("2d"); context2?.fillRect(0, height - 1, 1, 1); if (context2?.getImageData(0, height - 1, 1, 1).data[3] === 255) return canvasHeightLimit = height; } catch { } } throw new Error("浏览器不支持截图导出"); } finally { canvas.width = 0; canvas.height = 0; } }; var jpegBlob = (canvas) => new Promise((resolve, reject) => { canvas.toBlob((blob) => { if (blob?.type === "image/jpeg") resolve(blob); else reject(new Error("JPG 生成失败,请选择手机版或减少游戏数量")); }, "image/jpeg", JPEG_QUALITY); }); var exportScreenshot = async (root, snapshot, options, onProgress) => { const start = performance.now(); const timings = { coversMs: 0, renderMs: 0, encodeMs: 0, totalMs: 0, coverCount: 0, memoryCacheHits: 0, failedCovers: 0, renderPages: 0, files: [] }; const stage = document.createElement("div"); stage.className = "wl-shot-stage"; stage.inert = true; const doc = createDocument(snapshot, options); stage.appendChild(doc); root.appendChild(stage); try { await document.fonts.ready; const list = doc.querySelector(".wl-shot-list"); const cards = Array.from(list.children); const gameCount = cards.filter((card) => card.classList.contains("wl-row")).length; const heights = cards.map((card) => card.getBoundingClientRect().height); const overhead = Math.ceil(doc.getBoundingClientRect().height - list.getBoundingClientRect().height) + 2; const images = Array.from(doc.querySelectorAll("img[data-shot-src]")); const urls = [...new Set(images.map((img) => img.dataset.shotSrc))]; timings.coverCount = urls.length; timings.memoryCacheHits = urls.filter((url) => capsuleCache.has(url)).length; const coverStart = performance.now(); const loadedImages = loadedReportCapsules(root); const assets2 = /* @__PURE__ */ new Map(); let loaded = 0; onProgress?.({ phase: "covers", done: 0, total: urls.length }); await Promise.all(urls.map(async (url) => { const image = await cachedCapsule(url, loadedImages.get(url)); if (image === EMPTY_IMAGE) timings.failedCovers++; assets2.set(url, image); onProgress?.({ phase: "covers", done: ++loaded, total: urls.length }); })); for (const image of images) { const img = image; img.dataset.shotSrc = assets2.get(img.dataset.shotSrc); } timings.coversMs = performance.now() - coverStart; const originals = cards.map((card) => card.outerHTML); const pixelWidth = SCREENSHOT_WIDTHS[options.layout] * SCREENSHOT_SCALE; const heightLimit = maxJpegHeight(); const pages = splitScreenshotRows(heights, heightLimit / SCREENSHOT_SCALE - overhead - 64); const date = (/* @__PURE__ */ new Date()).toLocaleDateString("sv-SE", { timeZone: "Asia/Shanghai" }); const basename = `steam-wishlist-${options.layout}-${date}`; let renderedGames = 0; for (let page = 0; page < pages.length; page++) { const rows = pages[page]; list.innerHTML = rows.map((row) => originals[row]).join(""); const height = Math.ceil(doc.getBoundingClientRect().height); const pixelHeight = height * SCREENSHOT_SCALE; if (pixelHeight > heightLimit) throw new Error("图片过长,请减少游戏数量"); onProgress?.({ phase: "render", done: renderedGames, total: gameCount }); const renderStart = performance.now(); const output = await domToCanvas(doc, { width: SCREENSHOT_WIDTHS[options.layout], height, scale: SCREENSHOT_SCALE, backgroundColor: "#1b2838", font: false, maximumCanvasSize: heightLimit, features: { copyScrollbar: false }, includeStyleProperties: SCREENSHOT_STYLE_PROPERTIES, fetchFn: (url) => cachedCapsule(url), onCloneEachNode: (cloned) => { if (cloned instanceof HTMLElement && cloned.classList.contains("wl-cap")) { cloned.style.width = "184px"; cloned.style.height = "69px"; } if (cloned instanceof HTMLImageElement && cloned.dataset.shotSrc) { cloned.width = 184; cloned.height = 69; cloned.src = cloned.dataset.shotSrc; delete cloned.dataset.shotSrc; } } }); try { if (output.width !== pixelWidth || output.height !== pixelHeight) { throw new Error("截图尺寸不正确,请重试"); } timings.renderMs += performance.now() - renderStart; timings.renderPages++; renderedGames += rows.filter((row) => cards[row].classList.contains("wl-row")).length; onProgress?.({ phase: "render", done: renderedGames, total: gameCount }); onProgress?.({ phase: "encode", done: page + 1, total: pages.length }); const encodeStart = performance.now(); const blob = await jpegBlob(output); timings.encodeMs += performance.now() - encodeStart; timings.files.push({ width: pixelWidth, height: pixelHeight, bytes: blob.size }); const suffix = pages.length === 1 ? "" : `-${String(page + 1).padStart(3, "0")}`; downloadBlob(blob, `${basename}${suffix}.jpg`); } finally { output.width = 0; output.height = 0; } } timings.totalMs = performance.now() - start; return timings; } finally { stage.remove(); } }; var screenshotSwitch = (id, label, checked) => ` `; var openScreenshotExport = (root, snapshot, trigger) => { if (root.querySelector(".wl-shot-modal")) return; const saved = loadValue(OPTIONS_KEY, null); const options = { layout: saved?.layout === "mobile" || saved?.layout === "pc" ? saved.layout : window.innerWidth <= 640 ? "mobile" : "pc", includeWishlistQr: saved?.includeWishlistQr !== false, includeIntro: saved?.includeIntro !== false }; const modal = document.createElement("div"); const template = document.createElement("template"); template.innerHTML = snapshot.listHtml; const gameCount = template.content.querySelectorAll(".wl-row").length; modal.className = "wl-dialog-backdrop wl-shot-modal"; modal.innerHTML = ``; let busy = false; let awaitingConfirmation = false; const close = () => { if (!busy) { modal.remove(); trigger.focus(); } }; modal.querySelector("[data-dialog-close]").addEventListener("click", close); modal.addEventListener("click", (event) => { if (event.target === modal) close(); }); modal.addEventListener("keydown", (event) => { if (event.key === "Escape") { event.stopPropagation(); close(); } if (event.key !== "Tab") return; const controls = Array.from(modal.querySelectorAll('button:not(:disabled), input:not(:disabled):not([type="radio"]), input[type="radio"]:checked:not(:disabled)')); const scope = root.getRootNode(); const focused = scope instanceof ShadowRoot ? scope.activeElement : document.activeElement; if (!controls.length) event.preventDefault(); else if (event.shiftKey && focused === controls[0]) { event.preventDefault(); controls[controls.length - 1].focus(); } else if (!event.shiftKey && focused === controls[controls.length - 1]) { event.preventDefault(); controls[0].focus(); } }); const save = modal.querySelector("[data-shot-save]"); save.addEventListener("click", async () => { if (busy) return; const error = modal.querySelector(".wl-shot-error"); error.textContent = ""; if (gameCount > 99 && !awaitingConfirmation) { awaitingConfirmation = true; save.textContent = `确认导出 ${gameCount} 款游戏`; return; } awaitingConfirmation = false; const layout = modal.querySelector('input[name="wl-shot-layout"]:checked').value; options.layout = layout === "mobile" ? "mobile" : "pc"; options.includeWishlistQr = modal.querySelector("#wl-shot-wishlist-qr").checked; options.includeIntro = modal.querySelector("#wl-shot-intro").checked; busy = true; save.textContent = "导出中…"; modal.querySelectorAll("input, button").forEach((control) => { control.disabled = true; }); try { const timings = await exportScreenshot(root, snapshot, options, ({ phase, done, total }) => { save.textContent = phase === "covers" ? `读取封面 ${done}/${total}…` : phase === "encode" ? `压缩图片 ${done}/${total}…` : total ? `生成图片 ${done}/${total}…` : "生成图片…"; }); console.debug("[Steam 愿望单截图耗时]", timings); saveValue(OPTIONS_KEY, options); busy = false; close(); } catch (reason) { error.textContent = reason instanceof Error ? reason.message : "截图生成失败,请重试"; } finally { busy = false; save.textContent = "导出 JPG"; modal.querySelectorAll("input, button").forEach((control) => { control.disabled = false; }); } }); root.appendChild(modal); modal.querySelector("input:checked").focus(); }; // src/scripts/steam-wishlist-prices/ui/report-client.ts var mountReport = (root, payload, handlers) => { const codes2 = payload.countries.map((country) => country.code); const allCodes = COUNTRIES.map((country) => country.code); const el = (id) => root.querySelector(`#${id}`); let tagControls; const loadShown = () => { const setup = loadRegionSetup(); if (setup?.shown.length) { return new Set(setup.shown.filter((code) => allCodes.includes(code))); } return new Set(codes2); }; const state = { q: "", priceFilter: null, missing: false, gift: false, soon: false, cheapest: "", sort: "vsHome", dir: "asc", shown: loadShown(), giftLoose: localStorage.getItem("wishlist-gift-mode") === "loose", fxCheap: localStorage.getItem("wishlist-fx-cheap") !== "off", home: allCodes.includes(payload.home) ? payload.home : "CN" }; state.shown.add(state.home); const nearBand = () => state.giftLoose ? GIFT_BAND_LOOSE : GIFT_BAND_STRICT; const cheapBand = () => state.fxCheap ? FX_CHEAP_BAND : 1e-4; const fmt = (n) => n == null ? "—" : n.toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 }); const pct = (n) => n == null ? "—" : `${(n * 100).toFixed(1)}%`; const ymd = (ts) => { if (ts == null) return "—"; const date = new Date(ts * 1e3); return Number.isNaN(date.getTime()) ? "—" : date.toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" }); }; const visibleCountries = () => { const shown = payload.countries.filter((country) => state.shown.has(country.code)); return shown.filter((country) => country.code === state.home).concat(shown.filter((country) => country.code !== state.home)); }; const labelOf = (code) => COUNTRIES.find((country) => country.code === code)?.label || payload.countries.find((country) => country.code === code)?.label || code || "—"; const viewOf = (row) => { let cheapestCny = null; for (const country of visibleCountries()) { const cny = row.prices[country.code]?.cny; if (cny != null && (cheapestCny == null || cny < cheapestCny)) cheapestCny = cny; } const cheapestCodes = []; if (cheapestCny != null) { for (const country of visibleCountries()) { const cny = row.prices[country.code]?.cny; if (cny != null && cny <= cheapestCny * (1 + cheapBand())) cheapestCodes.push(country.code); } } const home = row.prices[state.home]?.cny ?? null; const vsHome = home != null && cheapestCny != null && home > 0 ? (home - cheapestCny) / home : null; return { cheapestCode: cheapestCodes[0] || null, cheapestCodes, cheapestCny, vsHome }; }; const band = (cny, min) => { if (cny == null || min == null) return ""; if (cny <= min * (1 + cheapBand())) return "cheap"; if (cny <= min * (1 + nearBand())) return "near"; return ""; }; const canGiftToHome = (cny, code, home) => { if (cny == null || home == null || home <= 0 || code === state.home) return false; if (cny > home * 1.0001) return false; return cny / home >= 1 - nearBand(); }; const noDeal = (row) => row.delisted || row.comingSoon || row.free; const statusText = (row) => row.delisted ? "已下架" : row.comingSoon ? "未发售" : row.free ? "免费" : ""; const homeOnSale = (row) => (row.prices[state.home]?.cut ?? 0) > 0; const isNewLow = (row) => !noDeal(row) && homeOnSale(row) && !!payload.itad?.enabled && payload.itad.home === state.home && row.itadNewLow === true; const isHistoryLow = (row) => !noDeal(row) && homeOnSale(row) && !!payload.itad?.enabled && (isNewLow(row) || row.historyLow?.country === state.home && row.historyLow.atLow === true); const filtered = (opts = {}) => payload.rows.filter((row) => { if (tagControls && !tagControls.matches(row.appid)) return false; const query = state.q.trim().toLowerCase(); if (query && !row.title.toLowerCase().includes(query) && !String(row.appid).includes(query)) { return false; } const view = viewOf(row); const shownPrices = visibleCountries().map((country) => row.prices[country.code]); if (state.priceFilter === "sale" && (noDeal(row) || !shownPrices.some((price) => price && price.cut > 0))) { return false; } if (state.priceFilter === "historyLow" && !isHistoryLow(row)) return false; if (state.priceFilter === "newLow" && !isNewLow(row)) return false; if (state.missing && (noDeal(row) || shownPrices.every((price) => price?.cny != null))) { return false; } if (state.gift) { if (noDeal(row)) return false; const home = row.prices[state.home]?.cny ?? null; const giftable = visibleCountries().some( (country) => canGiftToHome(row.prices[country.code]?.cny, country.code, home) ); if (!giftable) return false; } if (state.soon && row.comingSoon) return false; if (!opts.skipCheap && state.cheapest && !view.cheapestCodes.includes(state.cheapest)) { return false; } return true; }); const cheapShare = (count, total) => total ? `${Math.round(count / total * 100)}%` : "0%"; const cheapStats = () => { const rows = filtered({ skipCheap: true }).filter((row) => !noDeal(row)); const counts = {}; for (const row of rows) { for (const code of viewOf(row).cheapestCodes) { counts[code] = (counts[code] || 0) + 1; } } return { total: rows.length, counts }; }; const valueOf = (row, key) => { const view = viewOf(row); if (key === "title") return row.title; if (key === "releasedAt") return row.releasedAt; if (key === "discountEndsAt") return noDeal(row) ? null : gameDiscountEnd(row.prices, state.home); if (key === "discount") { const price = row.prices[state.home]; return noDeal(row) || price?.amount == null ? null : price.cut; } if (key === "appid") return row.appid; if (key === "cheapestCode") return view.cheapestCode || ""; if (key === "cheapest") return view.cheapestCny; if (key === "vsHome") return view.vsHome; return row.prices[key]?.cny; }; const cmp = (left, right, dir) => { if (left == null && right == null) return 0; if (left == null) return 1; if (right == null) return -1; const sign = dir === "asc" ? 1 : -1; if (typeof left === "string") return left.localeCompare(String(right), "zh") * sign; return (left - right) * sign; }; const isPriceSort = (key) => key !== "title" && key !== "releasedAt" && key !== "appid"; const sorted = (rows) => [...rows].sort((left, right) => { if (isPriceSort(state.sort)) { const aBottom = noDeal(left) ? 1 : 0; const bBottom = noDeal(right) ? 1 : 0; if (aBottom !== bBottom) return aBottom - bBottom; } return cmp(valueOf(left, state.sort), valueOf(right, state.sort), state.dir); }); const applySort = (key) => { if (state.sort === key) return; const wasPrice = isPriceSort(state.sort); state.sort = key; if (key === "title") state.dir = "asc"; else if (key === "releasedAt") state.dir = "desc"; else if (key === "discountEndsAt") state.dir = "asc"; else if (key === "discount") state.dir = "desc"; else if (!wasPrice) state.dir = "desc"; }; const dirLabel = () => { if (state.sort === "discountEndsAt") { return state.dir === "asc" ? discountTimeCopy.ascending : discountTimeCopy.descending; } if (state.sort === "title") return state.dir === "asc" ? "A→Z" : "Z→A"; if (state.sort === "releasedAt") return state.dir === "desc" ? "新→旧" : "旧→新"; return state.dir === "desc" ? "高→低" : "低→高"; }; const closeMenus = () => { el("region-menu-panel").classList.add("hidden"); el("cheap-menu-panel").classList.add("hidden"); el("home-menu-panel").classList.add("hidden"); el("sort-menu-panel").classList.add("hidden"); }; const sortOptions = () => { const fixed = [ { key: "vsHome", label: "相对账户区" }, { key: "cheapest", label: "最低价" }, { key: "discount", label: "折扣" }, { key: "title", label: "标题" }, { key: "releasedAt", label: "发售日" }, { key: "discountEndsAt", label: discountTimeCopy.label } ]; const regions = visibleCountries().map((country) => ({ key: country.code, label: country.label })); return fixed.concat(regions); }; const sortLabel = (key) => sortOptions().find((item) => item.key === key)?.label || "相对账户区"; const syncSortMenu = () => { const keys = new Set(sortOptions().map((item) => item.key)); if (!keys.has(state.sort)) { state.sort = "vsHome"; state.dir = "desc"; } el("sort-menu-label").textContent = sortLabel(state.sort); el("sort-dir-label").textContent = dirLabel(); el("sort-menu-list").innerHTML = sortOptions().map((item) => { const on = item.key === state.sort; return ``; }).join(""); }; const toggleMenu = (id) => { const panel = el(id); const willOpen = panel.classList.contains("hidden"); closeMenus(); if (willOpen) panel.classList.remove("hidden"); }; const syncCheapMenu = () => { if (state.cheapest && !state.shown.has(state.cheapest)) state.cheapest = ""; const stats = cheapStats(); const selectedCount = state.cheapest ? stats.counts[state.cheapest] || 0 : 0; el("cheap-menu-label").textContent = state.cheapest ? `最低价区:${labelOf(state.cheapest)}` : "最低价区:全部"; const stat = el("cheap-menu-stat"); if (state.cheapest) { stat.textContent = `${selectedCount} · ${cheapShare(selectedCount, stats.total)}`; stat.classList.remove("hidden"); } else { stat.textContent = ""; stat.classList.add("hidden"); } const items = [{ code: "", label: "全部", count: 0 }].concat( visibleCountries().map((country) => ({ code: country.code, label: country.label, count: stats.counts[country.code] || 0 })) ); el("cheap-menu-list").innerHTML = items.map((item) => { const on = item.code === state.cheapest; const meta = item.code ? `${item.count} · ${cheapShare(item.count, stats.total)}` : ""; return ``; }).join(""); }; const syncRegionMenu = () => { el("region-menu-count").textContent = `${state.shown.size}/${allCodes.length}`; for (const input of Array.from(el("region-menu-list").querySelectorAll("input[data-region]"))) { const box = input; const code = box.dataset.region || ""; box.checked = state.shown.has(code); box.disabled = code === state.home; } }; const persistRegions = () => { state.shown.add(state.home); saveRegionSetup({ home: state.home, shown: [...state.shown] }); const needsFetch = [...state.shown].some((code) => !codes2.includes(code)); if (needsFetch || state.shown.size > compareRegionLimit(payload.wishlistCount ?? payload.rows.length)) { handlers?.onRefetch?.(); return; } syncRegionMenu(); syncCheapMenu(); syncSortMenu(); render(); }; const syncHomeMenu = () => { if (!allCodes.includes(state.home)) state.home = "CN"; el("home-menu-label").textContent = labelOf(state.home); el("home-menu-list").innerHTML = COUNTRIES.map((country) => { const on = country.code === state.home; return ``; }).join(""); }; const persistHome = () => { state.shown.add(state.home); saveRegionSetup({ home: state.home, shown: [...state.shown] }); if (state.shown.size > compareRegionLimit(payload.wishlistCount ?? payload.rows.length) || !codes2.includes(state.home) || payload.itad?.enabled && state.home !== payload.itad.home) { handlers?.onRefetch?.(); return; } syncHomeMenu(); syncRegionMenu(); render(); }; const giftTip = () => state.giftLoose ? "宽松 15%:给公开汇率和 Steam 内部结算汇率留余量。相对当前账户区域,该区价 ÷ 账户区价 ≥ 85%。" : "严谨 10%:跟 SteamDB / 社区反推的旧送礼门槛。相对当前账户区域,该区价 ÷ 账户区价 ≥ 90%。"; const syncGiftMode = () => { const value = Math.round(nearBand() * 100); el("near-pct").textContent = String(value); el("gift-pct").textContent = String(value); el("gift-tip").textContent = giftTip(); const giftModeClass = (on, edge) => `h-5 px-1.5 text-[11px] leading-none ${edge ? "border-l border-line " : ""}${on ? "bg-cream text-ink" : "text-muted hover:bg-cream"}`; el("gift-strict").className = giftModeClass(!state.giftLoose, false); el("gift-loose").className = giftModeClass(state.giftLoose, true); }; const persistGiftMode = () => { localStorage.setItem("wishlist-gift-mode", state.giftLoose ? "loose" : "strict"); syncGiftMode(); render(); }; let screenshotSummary = ""; const render = () => { const countries = visibleCountries(); const rows = sorted(filtered()); const tagNames = new Map(payload.tags?.categories.map((tag) => [tag.id, tag])); const pricedRows = rows.filter((row) => !row.free); const homePrices = pricedRows.map((row) => row.prices[state.home]); const total = (values, missingLabel = reportSummaryCopy.missingPrice) => { const prices = values.filter((price) => price != null && Number.isFinite(price)); const missing = values.length - prices.length; return { value: missing > 0 && prices.length === 0 ? "—" : `¥${fmt(prices.reduce((sum, price) => sum + price, 0))}`, detail: missing > 0 ? missingLabel(missing) : void 0 }; }; const history = payload.itad?.enabled ? total( pricedRows.map((row) => !noDeal(row) && row.historyLow?.country === state.home ? row.historyLow.cny : null), reportSummaryCopy.missingHistory ) : { value: "—", detail: reportSummaryCopy.itadDisabled }; const metrics = renderReportMetrics([ { kind: "games", value: String(rows.length), suffix: `/ ${payload.rows.length}` }, { kind: "current", ...total(homePrices.map((price) => price?.cny)) }, { kind: "regular", ...total(homePrices.map((price) => price?.regularCny ?? (price?.cut === 0 ? price.cny : null))) }, { kind: "history", ...history } ]); el("report-metrics").innerHTML = metrics.html; screenshotSummary = metrics.text; syncSortMenu(); el("list").innerHTML = steamListHtml( rows.map((row) => { const view = viewOf(row); const status = noDeal(row) ? statusText(row) : ""; return { appid: row.appid, title: row.title, tags: payload.tags?.items[row.appid]?.map((id) => tagNames.get(id)).filter((tag) => !!tag), editTags: payload.tags?.editable && payload.tags.items[row.appid] !== void 0, removeGame: payload.canEditWishlist, capsule: row.capsule, released: row.releasedAt == null ? "" : ymd(row.releasedAt), status, discountEnd: status ? null : formatDiscountEnd(gameDiscountEnd(row.prices, state.home)), vsHome: status ? "" : `相对${labelOf(state.home)} ${pct(view.vsHome)}`, cheapestLabel: "最低", cheapest: status ? "" : `${view.cheapestCodes.map((code) => labelOf(code)).join(" / ")} ${fmt(view.cheapestCny)}`, chips: status ? [] : countries.map((country) => { const price = row.prices[country.code]; const cny = price?.cny ?? null; const home = row.prices[state.home]?.cny ?? null; return { label: country.label, cny: fmt(cny), local: price?.amount != null ? `${price.amount.toFixed(2)} ${price.currency}` : "", cut: price?.cut ?? 0, band: band(cny, view.cheapestCny), gift: canGiftToHome(cny, country.code, home), atLow: country.code === state.home && isHistoryLow(row), newLow: country.code === state.home && isNewLow(row), bundle: price?.bundle && price.bundle.cny !== null && price.bundle.cny < (price.cny ?? Infinity) ? { cny: `¥${fmt(price.bundle.cny)}`, local: `${price.bundle.amount.toFixed(2)} ${price.bundle.currency}`, name: price.bundle.name } : void 0 }; }), history: status || !payload.itad?.enabled ? void 0 : row.historyLow?.country === state.home ? { label: `${labelOf(state.home)}史低`, price: `${row.historyLow.amount.toFixed(2)} ${row.historyLow.currency}${row.historyLow.currency !== "CNY" && row.historyLow.cny != null ? ` ≈ ¥${fmt(row.historyLow.cny)}` : ""}`, date: row.historyLow.recordedAt ? new Date(row.historyLow.recordedAt).toLocaleDateString("en-CA", { timeZone: "Asia/Shanghai" }) : "" } : { label: payload.itad.warning ? "史低数据未获取" : "暂无史低数据", price: "—", date: "" } }; }) ); for (const img of Array.from(el("list").querySelectorAll("img"))) { img.addEventListener("error", () => { img.style.visibility = "hidden"; }); } syncCheapMenu(); }; if (payload.canEditWishlist) mountWishlistRemoval(root, payload, render); el("q").addEventListener("input", (event) => { state.q = event.target.value; render(); }); el("setup-open").addEventListener("click", () => handlers?.onSetup?.()); for (const mode of ["import", "export"]) { const trigger = root.querySelector(`#wishlist-${mode}-open`); trigger?.addEventListener("click", () => { closeMenus(); openWishlistTransfer(trigger, payload, mode, handlers?.onWishlistImported); }); } el("screenshot-open").addEventListener("click", () => { closeMenus(); openScreenshotExport(root, { steamName: payload.steamName || payload.steamId, wishlistUrl: el("wishlist-link").href, home: labelOf(state.home), countries: visibleCountries().map((country) => country.label), generatedAt: `生成于 ${new Date(payload.generatedAt).toLocaleString("zh-CN", { hour12: false, timeZone: "Asia/Shanghai" })}`, summary: screenshotSummary, listHtml: el("list").innerHTML }, el("screenshot-open")); }); const priceFilters = [["sale", "sale"], ["history-low", "historyLow"], ["new-low", "newLow"]].filter(([id]) => id === "sale" || payload.itad?.enabled); const syncPriceFilters = () => { for (const [id, value] of priceFilters) { el(id).checked = state.priceFilter === value; } }; syncPriceFilters(); for (const [id, value] of priceFilters) { el(id).addEventListener("change", (event) => { state.priceFilter = event.target.checked ? value : null; syncPriceFilters(); render(); }); } el("missing").addEventListener("change", (event) => { state.missing = event.target.checked; render(); }); el("gift").addEventListener("change", (event) => { state.gift = event.target.checked; render(); }); el("soon").addEventListener("change", (event) => { state.soon = event.target.checked; render(); }); el("fxCheap").checked = state.fxCheap; el("fxCheap").addEventListener("change", (event) => { state.fxCheap = event.target.checked; localStorage.setItem("wishlist-fx-cheap", state.fxCheap ? "on" : "off"); render(); }); el("gift-strict").addEventListener("click", () => { if (!state.giftLoose) return; state.giftLoose = false; persistGiftMode(); }); el("gift-loose").addEventListener("click", () => { if (state.giftLoose) return; state.giftLoose = true; persistGiftMode(); }); el("home-menu-btn").addEventListener("click", (event) => { event.stopPropagation(); toggleMenu("home-menu-panel"); }); el("home-menu-panel").addEventListener("click", (event) => { event.stopPropagation(); const btn = event.target.closest("[data-home]"); if (!btn) return; state.home = btn.dataset.home || state.home; closeMenus(); persistHome(); }); el("cheap-menu-btn").addEventListener("click", (event) => { event.stopPropagation(); toggleMenu("cheap-menu-panel"); }); el("cheap-menu-panel").addEventListener("click", (event) => { event.stopPropagation(); const btn = event.target.closest("[data-cheap]"); if (!btn) return; state.cheapest = btn.dataset.cheap || ""; closeMenus(); syncCheapMenu(); render(); }); el("region-menu-btn").addEventListener("click", (event) => { event.stopPropagation(); toggleMenu("region-menu-panel"); }); el("region-menu-panel").addEventListener("click", (event) => event.stopPropagation()); el("region-menu-list").addEventListener("change", (event) => { const input = event.target.closest("input[data-region]"); if (!input || input.disabled) return; const code = input.dataset.region || ""; if (input.checked) state.shown.add(code); else state.shown.delete(code); persistRegions(); }); el("regions-all").addEventListener("click", () => { state.shown = new Set(allCodes); persistRegions(); }); root.addEventListener("click", closeMenus); el("sort-menu-btn").addEventListener("click", (event) => { event.stopPropagation(); toggleMenu("sort-menu-panel"); }); el("sort-dir-btn").addEventListener("click", (event) => { event.stopPropagation(); state.dir = state.dir === "asc" ? "desc" : "asc"; closeMenus(); render(); }); el("sort-menu-panel").addEventListener("click", (event) => { event.stopPropagation(); const sortEl = event.target.closest("[data-sort]"); if (!sortEl) return; applySort(sortEl.dataset.sort || "vsHome"); closeMenus(); render(); }); if (payload.tags) tagControls = mountWishlistTagControls(root, payload, render); syncRegionMenu(); syncCheapMenu(); syncHomeMenu(); syncGiftMode(); render(); }; // src/scripts/steam-wishlist-prices/ui/overlay.ts var HOST_ID = "wl-prices-overlay"; var closeReportOverlay = () => { document.getElementById(HOST_ID)?.remove(); document.documentElement.style.removeProperty("overflow"); }; var attachOverlay = (mode) => { closeReportOverlay(); const host = document.createElement("div"); host.id = HOST_ID; const shadow = host.attachShadow({ mode: "open" }); const style = document.createElement("style"); style.textContent = report_generated_default; const overlay = document.createElement("div"); if (mode === "dialog") { overlay.className = "wl-overlay wl-dialog-backdrop z-[2147483646]"; overlay.innerHTML = ``; } else { overlay.className = "wl-overlay fixed inset-0 z-[2147483646] flex flex-col p-3"; overlay.innerHTML = `
`; } shadow.append(style, overlay); document.documentElement.style.overflow = "hidden"; document.body.appendChild(host); return { overlay, app: overlay.querySelector(".wl-app"), closeBtn: overlay.querySelector(".wl-close") }; }; var openReportOverlay = (payload, handlers) => { const { app: app2, closeBtn } = attachOverlay("page"); closeBtn?.addEventListener("click", closeReportOverlay); app2.innerHTML = renderReportShell(payload); mountReport(app2, payload, handlers); }; var openRegionSetup = (initial, wishlistCount) => new Promise((resolve) => { const { overlay, app: app2 } = attachOverlay("dialog"); let done = false; const finish = (value) => { if (done) return; done = true; closeReportOverlay(); resolve(value); }; overlay.addEventListener("click", (event) => { if (event.target === overlay) finish(null); }); app2.innerHTML = renderSetupShell(initial); app2.querySelector("[data-dialog-close]")?.addEventListener("click", () => finish(null)); mountSetup(app2, initial, (setup) => { saveItadApiKey(setup.itadKey); saveTagsEnabled(setup.tagsEnabled); saveRegionSetup(setup); finish(setup); }, wishlistCount); }); // src/scripts/steam-wishlist-prices/pricing/price-rows.ts var historyLowFor = (low, deal, rates) => low ? { ...low, cny: toCny(low.amount, low.currency, rates), // Historical currencies can differ after a regional currency change. Never use FX to judge a low. atLow: deal?.currency === low.currency ? deal.amount <= low.amount + 5e-3 : null } : null; var emptyPrice = () => ({ amount: null, currency: null, regular: null, cut: 0, discountEndsAt: null, cny: null, regularCny: null }); var fromDeal = (deal, rates) => { if (!deal) { return emptyPrice(); } const regular = deal.regular ?? (deal.cut === 0 ? deal.amount : null); return { amount: deal.amount, currency: deal.currency, regular: deal.regular, cut: deal.cut, discountEndsAt: deal.cut > 0 ? deal.discountEndsAt ?? null : null, cny: toCny(deal.amount, deal.currency, rates), regularCny: regular == null ? null : toCny(regular, deal.currency, rates), ...deal.bundle ? { bundle: { ...deal.bundle, cny: toCny(deal.bundle.amount, deal.bundle.currency, rates) } } : {} }; }; var blankPrices = (countries) => { const prices = {}; for (const country of countries) { prices[country.code] = emptyPrice(); } return prices; }; var buildGameRows = (games, steamDeals, countries, rates, historyLows = /* @__PURE__ */ new Map(), itadDeals = /* @__PURE__ */ new Map()) => { return games.map((game) => { if (game.delisted || game.comingSoon || game.free) { return { appid: game.appid, title: game.title, capsule: game.capsule, releasedAt: game.releasedAt, free: game.free, comingSoon: game.comingSoon, delisted: game.delisted, prices: blankPrices(countries), cheapestCode: null, cheapestCny: null, vsCn: null, historyLow: null }; } const prices = {}; let cheapestCode = null; let cheapestCny = null; for (const country of countries) { const price = fromDeal(steamDeals.get(country.code)?.get(game.appid), rates); prices[country.code] = price; if (price.cny !== null && (cheapestCny === null || price.cny < cheapestCny)) { cheapestCode = country.code; cheapestCny = price.cny; } } const cn = prices.CN?.cny ?? null; const vsCn = cn !== null && cheapestCny !== null && cn > 0 ? (cn - cheapestCny) / cn : null; const low = historyLows.get(game.appid); const referenceDeal = low ? steamDeals.get(low.country)?.get(game.appid) : void 0; const itadDeal = itadDeals.get(game.appid); const currentDeal = itadDeal ? steamDeals.get(itadDeal.country)?.get(game.appid) : void 0; const belowRecordedLow = !!low && referenceDeal?.currency === low.currency && referenceDeal.amount < low.amount; const matchingNewLowQuote = itadDeal?.flag === "N" && currentDeal?.currency === itadDeal.currency && Math.abs(currentDeal.amount - itadDeal.amount) < 5e-3; return { appid: game.appid, title: game.title, capsule: game.capsule, releasedAt: game.releasedAt, free: false, comingSoon: false, delisted: false, prices, cheapestCode, cheapestCny, vsCn, historyLow: historyLowFor(low, referenceDeal, rates), itadNewLow: belowRecordedLow || matchingNewLowQuote }; }); }; // src/scripts/steam-wishlist-prices/pricing/steam-prices.ts var loadBucket = (country) => loadValue(priceCacheKey(country), {}); var saveBucket = (country, bucket) => saveValue(priceCacheKey(country), bucket); var freshPrice = (hit, now) => !!hit && Number.isFinite(hit.savedAt) && now - hit.savedAt >= 0 && now - hit.savedAt < PRICE_TTL_MS; var usable = (hit, now) => { if (!freshPrice(hit, now)) return false; return !hit.deal || hit.deal.discountEndsAt === null || hit.deal.discountEndsAt !== void 0 && hit.deal.discountEndsAt > now; }; var COUNTRY_CURRENCY = { CN: "CNY", TW: "TWD", HK: "HKD", SG: "SGD", JP: "JPY", US: "USD", TR: "USD", UA: "UAH", IN: "INR", ID: "IDR", PH: "PHP", VN: "VND", KZ: "KZT", AZ: "USD", PK: "USD", RU: "RUB", AR: "USD" }; var currencyOf = (country, formatted) => { const text = formatted ?? ""; if (text.includes("NT$")) return "TWD"; if (text.includes("HK$")) return "HKD"; if (text.includes("S$")) return "SGD"; if (text.includes("Rp")) return "IDR"; if (text.includes("₱")) return "PHP"; if (text.includes("₽") || text.toLowerCase().includes("руб")) return "RUB"; if (text.includes("₴")) return "UAH"; if (text.includes("₸")) return "KZT"; if (text.includes("₫")) return "VND"; if (text.includes("$")) return "USD"; return COUNTRY_CURRENCY[country] ?? "USD"; }; var fromCents = (value) => { if (value == null || value === "") { return null; } const cents = Number(value); if (!Number.isFinite(cents) || cents < 0) { return null; } return cents / 100; }; var standaloneOption = (item) => { const options = [...item.purchase_options ?? [], item.best_purchase_option].filter( (option) => !!option && (option.bundleid == null || Number(option.bundleid) <= 0) && (option.packageid == null || Number(option.packageid) > 0) && fromCents(option.final_price_in_cents) !== null ); const best = item.best_purchase_option; if (best && (best.bundleid == null || Number(best.bundleid) <= 0) && (best.packageid == null || Number(best.packageid) > 0) && fromCents(best.final_price_in_cents) !== null && (best.included_game_count == null || best.included_game_count > 0)) { return best; } const gamePackages = options.filter((option) => option.included_game_count == null || option.included_game_count > 0); const candidates = gamePackages.length > 0 ? gamePackages : options; return candidates.reduce((selected, option) => { if (!selected) return option; return (fromCents(option.final_price_in_cents) ?? Infinity) < (fromCents(selected.final_price_in_cents) ?? Infinity) ? option : selected; }, void 0); }; var bundleOption = (item) => { let selected; let lowest = Infinity; for (const option of [...item.purchase_options ?? [], item.best_purchase_option]) { if (!option || option.bundleid == null || Number(option.bundleid) <= 0) continue; const amount = fromCents(option.final_price_in_cents); if (amount !== null && amount < lowest) { selected = option; lowest = amount; } } return selected; }; var toDeal = (item, country, appid) => { const id = item.appid && item.appid > 0 ? item.appid : appid; if (!id || item.unvailable_for_country_restriction) { return null; } const best = standaloneOption(item); const amount = fromCents(best?.final_price_in_cents); if (amount == null) { return null; } const regular = fromCents(best?.original_price_in_cents) ?? amount; const cut = typeof best?.discount_pct === "number" ? best.discount_pct : regular > 0 && amount < regular ? Math.round((1 - amount / regular) * 100) : 0; const endDates = (best?.active_discounts ?? []).map((discount2) => discount2.discount_end_date).filter((end) => Number.isInteger(end) && Number(end) > 0 && Number(end) <= 4294967295); const bundle = bundleOption(item); const bundleAmount = fromCents(bundle?.final_price_in_cents); return { amount, currency: currencyOf(country, best?.formatted_final_price), regular, cut, discountEndsAt: cut > 0 && endDates.length > 0 ? Math.min(...endDates) * 1e3 : null, ...bundle && bundleAmount !== null && bundleAmount < amount ? { bundle: { amount: bundleAmount, currency: currencyOf(country, bundle.formatted_final_price), name: bundle.purchase_option_name ?? "捆绑包" } } : {} }; }; var fetchAppIdPrices = async (country, appids) => { const deals = /* @__PURE__ */ new Map(); if (appids.length === 0) { return deals; } const context2 = { language: "schinese", country_code: country }; for (const group of chunkGetItems(appids, context2, PRICE_DATA_REQUEST)) { for (const item of await fetchStoreItems(group, context2, PRICE_DATA_REQUEST)) { const appid = item.appid && item.appid > 0 ? item.appid : item.id; const deal = toDeal(item, country, appid); if (appid && deal) { deals.set(appid, deal); } } } return deals; }; var fetchWishlistCountryPrices = async (steamId2, country, appids, listSize = 0, shareToken = "") => { const deals = /* @__PURE__ */ new Map(); if (appids.length === 0) { return deals; } const needed = new Set(appids); const { appids: sortedIds, storeItems } = await fillWishlistStoreItems( steamId2, country, PRICE_DATA_REQUEST, needed, Math.max(listSize, appids.length), shareToken ); for (const appid of appids) { const item = storeItems.get(appid); if (!item) { continue; } const deal = toDeal(item, country, appid); if (deal) { deals.set(appid, deal); } } const sortedSet = new Set(sortedIds); const leftover = appids.filter((appid) => !sortedSet.has(appid)); if (leftover.length > 0) { const extra = await fetchAppIdPrices(country, leftover); for (const [appid, deal] of extra) { deals.set(appid, deal); } } return deals; }; var loadedItems = (country, options) => { if (!options.refreshed) return null; return options.countryItems.get(country) ?? null; }; var pendingIds = (country, appids, options, now) => { if (loadedItems(country, options)) return []; const bucket = loadBucket(country); const added = new Set(options.addedAppids); return appids.filter((appid) => options.refreshed || !usable(bucket[appid], now) || added.has(appid) && !bucket[appid]?.deal); }; var estimateCountryFillRequests = (countries, appids, options, wishlistCount) => { if (appids.length === 0) return 0; const pages = Math.max(1, Math.ceil(Math.max(wishlistCount, appids.length) / WISHLIST_STORE_FILL_MAX)); return [...new Set(countries)].reduce((total, country) => { const items = loadedItems(country, options); if (items) { const missing = [...new Set(appids)].filter((appid) => !items.has(appid)); return total + chunkGetItems(missing, { language: "schinese", country_code: country }, PRICE_DATA_REQUEST).length; } return total + (pendingIds(country, appids, options, Date.now()).length > 0 ? pages : 0); }, 0); }; var rememberDeals = (country, appids, deals, now) => { const bucket = loadBucket(country); for (const appid of appids) { bucket[appid] = { savedAt: now, deal: deals.get(appid) ?? null }; } saveBucket(country, bucket); }; var loadSteamCountryPrices = async (steamId2, countries, appids, options, onCountry, wishlistCount = appids.length) => { const now = Date.now(); const selected = [...new Set(countries)]; const uniqueAppids = [...new Set(appids)]; const work = selected.map((country) => ({ country, appids: pendingIds(country, uniqueAppids, options, now) })); const total = work.filter((job) => job.appids.length > 0).length; let completed = 0; await Promise.all(work.map(async ({ country, appids: appids2 }) => { const items = loadedItems(country, options); if (items) { const deals = /* @__PURE__ */ new Map(); const missing = []; for (const appid of uniqueAppids) { const item = items.get(appid); if (!item) { missing.push(appid); continue; } const deal = toDeal(item, country, appid); if (deal) deals.set(appid, deal); } if (missing.length > 0) { for (const [appid, deal] of await fetchAppIdPrices(country, missing)) { deals.set(appid, deal); } } rememberDeals(country, uniqueAppids, deals, now); } else if (appids2.length > 0) { const deals = await fetchWishlistCountryPrices(steamId2, country, appids2, wishlistCount, options.shareToken); rememberDeals(country, appids2, deals, Date.now()); onCountry?.(country, ++completed, total); } })); const result = /* @__PURE__ */ new Map(); for (const country of selected) { const bucket = loadBucket(country); const deals = /* @__PURE__ */ new Map(); for (const appid of uniqueAppids) { const hit = bucket[appid]; if (freshPrice(hit, Date.now()) && hit.deal) deals.set(appid, hit.deal); } result.set(country, deals); } return result; }; // src/scripts/steam-wishlist-prices/steam/steam-profile.ts var TITLE_RE = /愿望单|願望單|Wishlist/i; var pageRoot = () => typeof unsafeWindow === "undefined" ? window : unsafeWindow; var fromProfileData = () => { const name = pageRoot().g_rgProfileData?.personaname; return typeof name === "string" && name.trim() ? name.trim() : null; }; var nameFromTitle = (text) => { const trimmed = text.replace(/\s+/g, " ").trim(); const cut = trimmed.replace(/\s*(的)?(愿望单|願望單|Wishlist).*$/i, "").trim(); if (!cut || TITLE_RE.test(cut) || cut.length > 64) { return null; } return cut; }; var fromDom = () => { const header = document.querySelector(".wishlist_header h2, .wishlist_header h1, .profile_small_header_name"); if (header?.textContent) { const name = nameFromTitle(header.textContent); if (name) { return name; } } const heading = Array.from(document.querySelectorAll("h1, h2")).find((el) => TITLE_RE.test(el.textContent || "")); if (heading?.textContent) { return nameFromTitle(heading.textContent); } return nameFromTitle(document.title); }; var loadSteamPersona = (steamId2) => fromProfileData() || fromDom() || steamId2; // src/scripts/steam-wishlist-prices/index.ts var BUTTON_ID = "wl-prices-launch"; var TITLE_RE2 = /愿望单|願望單|Wishlist/i; var BUTTON_STYLE = ` .wl-prices-header { display: flex; align-items: center; gap: 8px; } #${BUTTON_ID} { flex: none; height: 30px; padding: 0 12px; border: 0; border-radius: 2px; background: #1a2c3d; color: #67c1f5; font-size: 13px; cursor: pointer; font-family: "Motiva Sans", Arial, Helvetica, sans-serif; } #${BUTTON_ID}:hover { background: #67c1f5; color: #fff; } `; var findHeaderRow = () => { const legacy = document.querySelector(".wishlist_header"); if (legacy instanceof HTMLElement) { return legacy; } const title = Array.from(document.querySelectorAll("h1, h2, h3")).find((el) => { const text = (el.textContent || "").replace(/\s+/g, " ").trim(); return TITLE_RE2.test(text) && text.length < 80; }); if (!title) { return null; } let node = title.parentElement; for (let i = 0; i < 8 && node; i++) { const style = window.getComputedStyle(node); const flex = style.display.includes("flex"); const wide = node.getBoundingClientRect().width >= 640; if (flex && wide) { return node; } node = node.parentElement; } return title.parentElement; }; var placeButton = (host, button) => { const others = Array.from(host.querySelectorAll("button")).filter((el) => el.id !== BUTTON_ID); const last = others[others.length - 1]; if (last) { button.style.marginLeft = "8px"; last.insertAdjacentElement("afterend", button); return; } button.style.marginLeft = "auto"; host.appendChild(button); }; var ensureLaunchButton = () => { const host = findHeaderRow(); if (!host) { return; } host.classList.add("wl-prices-header"); let button = document.getElementById(BUTTON_ID); if (!button) { button = document.createElement("button"); button.id = BUTTON_ID; button.type = "button"; button.textContent = "区域比价"; button.addEventListener("click", () => { void runReport(); }); } if (host.contains(button)) { const others = Array.from(host.querySelectorAll("button")).filter((el) => el.id !== BUTTON_ID); const last = others[others.length - 1]; if (last && button.previousElementSibling !== last) { last.insertAdjacentElement("afterend", button); } return; } placeButton(host, button); }; var runReport = async (forceSetup = false, importedWishlistCount) => { let wishlistCount = importedWishlistCount ?? readWishlistPageCount(); const shareToken = new URL(location.href).searchParams.get("share_token") || ""; logWishlist("开始比价", { pageCount: wishlistCount, shared: Boolean(shareToken) }); closeReportOverlay(); const hud = new HudCard("愿望单比价", "检查愿望单数量…"); const meter = createRequestMeter((done, total) => hud.setRequestCount(done, total)); setRequestHook(() => meter.bump()); try { let steamId2; let knownAppids; if (wishlistCount === null) { steamId2 = resolveSteamId(); knownAppids = await fetchWishlistAppIds(steamId2, shareToken); wishlistCount = knownAppids.length; } const saved = loadRegionSetup(); const setup = needsRegionSetup(saved, wishlistCount, forceSetup || needsGuideSetup()) ? await openRegionSetup(saved ?? legacyRegionSetup(), wishlistCount) : saved; if (!setup) { hud.dismiss(0); return; } const countries = countriesForSetup(setup); hud.update("解析 Steam ID…"); steamId2 ?? (steamId2 = resolveSteamId()); meter.setTotal(meter.done + estimateOpeningRequests(steamId2, setup.home, wishlistCount, !!knownAppids, Boolean(shareToken))); hud.update("读取资料和愿望单…"); const steamName = loadSteamPersona(steamId2); const countryCodes = countries.map((country) => country.code); const wishlist = await loadSteamWishlist(steamId2, setup.home, wishlistCount, countryCodes, knownAppids, shareToken); const games = wishlist.games; const priceAppids = games.filter((game) => !game.delisted && !game.comingSoon && !game.free).map((game) => game.appid); const apiKey = loadItadApiKey(); const priceOptions = { refreshed: wishlist.refreshed, addedAppids: wishlist.addedAppids, countryItems: wishlist.countryItems, shareToken }; const fillRequests = estimateCountryFillRequests( countryCodes, priceAppids, priceOptions, games.length ); meter.setTotal(meter.done + fillRequests + (fxRequestPending() ? 1 : 0)); hud.update( wishlist.refreshed ? `更新 ${countries.length} 区价格…` : fillRequests > 0 ? "补齐新区域价格…" : "读取缓存价格…" ); const deals = await loadSteamCountryPrices( steamId2, countryCodes, priceAppids, priceOptions, (country, index, total) => { hud.update(`价格 ${country}(${index}/${total})`); hud.setProgress(index / total * 100); }, games.length ); if (apiKey) hud.update("读取 ITAD 本区史低…"); const itad = await loadItadSteamLows(priceAppids, setup.home, apiKey, (count) => { meter.setTotal(meter.total + count); }, deals.get(setup.home)); hud.update("换算人民币…"); const rates = await loadUsdRates(); const rows = buildGameRows(games, deals, countries, rates, itad.lows, itad.deals); const tagsEnabled = loadTagsEnabled(); const tagShareToken = tagsEnabled ? shareToken : ""; if (tagsEnabled) hud.update("读取愿望单标签…"); const tags = tagsEnabled ? await loadWishlistTags(steamId2, setup.home, tagShareToken, wishlist.tagIds) : void 0; const payload = { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), fxAt: rates.fetchedAt, steamId: steamId2, steamName, wishlistCount, home: setup.home, countries, rows, tags, tagShareToken, canEditWishlist: !shareToken && loggedInSteamId() === steamId2, itad: { enabled: itad.enabled, home: itad.home, warning: itad.warning } }; const showReport = () => openReportOverlay(payload, { onRefetch: () => void runReport(false), onSetup: () => void configureSetup(payload.wishlistCount ?? rows.length, showReport), onWishlistImported: (count) => void runReport(false, count) }); showReport(); logWishlist("比价数据", { games: rows.length, regions: countryCodes, wishlistCache: !wishlist.refreshed, prices: Object.fromEntries([...deals].map(([country, offers]) => [country, offers.size])), tagsEnabled, tagCount: tags?.categories.length, requests: meter.done }); hud.update(`${steamName} · ${rows.length} 款`, "完成", "success"); hud.dismiss(1600); } catch (error) { const message = error instanceof Error ? error.message : String(error); logWishlist("比价失败", { reason: message }); hud.update(message, "失败", "error"); hud.dismiss(5e3); } finally { setRequestHook(null); } }; var configureSetup = async (wishlistCount, onCancel) => { if (await openRegionSetup(loadRegionSetup() ?? legacyRegionSetup(), wishlistCount)) void runReport(); else onCancel?.(); }; whenDocumentReady(() => { logWishlist("脚本已加载"); injectStyle("wl-prices-launch-style", BUTTON_STYLE); startPolling(ensureLaunchButton, 800); GM_registerMenuCommand("打开区域比价", () => { void runReport(); }); GM_registerMenuCommand("设置比价区域", () => { void runReport(true); }); }); })();