// ==UserScript== // @name Steam 免费入库助手 // @namespace steam-free-library.local // @version 1.0.1 // @description 读取 Steam +1 候选指南,快捷入库免费可加一的游戏。 // @match https://store.steampowered.com/* // @match https://steamcommunity.com/* // @grant GM.getValue // @grant GM.setValue // @grant GM.registerMenuCommand // @grant GM.addValueChangeListener // @grant GM.xmlHttpRequest // @grant GM.listValues // @grant GM.deleteValue // @connect steamcommunity.com // @icon data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3Cdefs%3E%3ClinearGradient%20id='a'%20x2='128'%20y2='128'%20gradientUnits='userSpaceOnUse'%3E%3Cstop%20stop-color='%232b4255'/%3E%3Cstop%20offset='1'%20stop-color='%23111d29'/%3E%3C/linearGradient%3E%3ClinearGradient%20id='b'%20x1='24'%20y1='34'%20x2='96'%20y2='100'%20gradientUnits='userSpaceOnUse'%3E%3Cstop%20stop-color='%23315873'/%3E%3Cstop%20offset='1'%20stop-color='%231b2c3d'/%3E%3C/linearGradient%3E%3C/defs%3E%3Cg%20stroke-width='2'%3E%3Crect%20x='1'%20y='1'%20width='126'%20height='126'%20rx='27'%20fill='url(%23a)'%20stroke='%23526779'/%3E%3Crect%20x='31'%20y='21'%20width='68'%20height='69'%20rx='10'%20fill='%232b4255'%20stroke='%23698398'/%3E%3C/g%3E%3Crect%20x='23'%20y='32'%20width='75'%20height='68'%20rx='11'%20fill='url(%23b)'%20stroke='%2366c0f4'%20stroke-width='2.5'/%3E%3Cpath%20d='M45%2053h29c6%200%2010%206%2011%2013l2%2010c1%206-5%2010-9%206l-8-7H49l-8%207c-5%204-11%200-9-6l2-10c1-7%205-13%2011-13Z'%20fill='%23e4edf4'/%3E%3Cpath%20d='M45%2061v12m-6-6h12'%20fill='none'%20stroke='%231b2838'%20stroke-width='3.5'%20stroke-linecap='round'/%3E%3Cg%20fill='%231b2838'%3E%3Ccircle%20cx='72'%20cy='63'%20r='2.7'/%3E%3Ccircle%20cx='79'%20cy='70'%20r='2.7'/%3E%3Ccircle%20cx='96'%20cy='96'%20r='23'/%3E%3C/g%3E%3Ccircle%20cx='96'%20cy='96'%20r='20'%20fill='%238bc53f'/%3E%3Cpath%20d='M96%2086v20m-10-10h20'%20fill='none'%20stroke='%2314202d'%20stroke-width='5'%20stroke-linecap='round'/%3E%3C/svg%3E // @run-at document-idle // @sandbox DOM // @noframes // ==/UserScript== 'use strict'; "use strict"; (() => { // src/core/model.ts var LABELS = { review: "待核对", ready: "待领取", claiming: "请求中", pending: "待核验", verified: "已验证入库", owned: "已拥有", expired: "已过期", future: "尚未开始", blocked: "已排除", "base-required": "缺少本体", invalid: "无效包", retry: "待重试", unknown: "结果未知" }; function candidate(subId, sourceUrl = "manual") { return { subId, appIds: [], name: `Sub ${subId}`, sourceUrl, discoveredAt: Date.now(), offer: "unknown", content: "unknown", countHint: "unknown" }; } function eligibility(c, now = Date.now()) { if (c.licenseExpiresAt !== void 0 || ["demo", "playtest", "other"].includes(c.content)) { return { status: "blocked", message: "临时许可、试玩或非游戏内容不参与领取" }; } if (c.claimEndsAt !== void 0 && c.claimEndsAt <= now) return { status: "expired", message: "领取活动已结束" }; if (c.startsAt !== void 0 && c.startsAt > now) return { status: "future", message: "活动尚未开始" }; return { status: "review", message: c.offer === "unknown" ? "请先查看包信息;勾选表示尝试领取此免费包" : "请核对包信息后勾选领取" }; } function toItem(c) { return { ...c, ...eligibility(c), selected: false, attempts: 0, updatedAt: Date.now() }; } function freshState(accountId) { return { schemaVersion: 1, accountId, items: [], cooldownUntil: 0, run: "idle", scanOffset: 0, message: "首次打开将自动缓存指南清单;完成后点击“一键入库”。" }; } // src/core/import.ts function validSubId(value) { const text = String(value); if (!/^[1-9]\d{0,9}$/.test(text)) return; const id = Number(text); return id <= 4294967295 ? id : void 0; } // src/core/storage.ts var stateKey = (id) => `sfl:account:v1:${id}`; function validateCandidates(data) { if (!Array.isArray(data)) return []; return data.slice(0, 500).flatMap((raw) => { if (!raw || typeof raw !== "object" || !validSubId(raw.subId)) return []; const item = toItem({ subId: raw.subId, appIds: Array.isArray(raw.appIds) ? raw.appIds.filter((id) => validSubId(id)).slice(0, 100) : [], name: typeof raw.name === "string" ? raw.name.slice(0, 200) : `Sub ${raw.subId}`, sourceUrl: typeof raw.sourceUrl === "string" ? raw.sourceUrl.slice(0, 1e3) : "manual", discoveredAt: Number.isFinite(raw.discoveredAt) ? raw.discoveredAt : Date.now(), offer: ["free-to-keep", "evergreen", "free-to-play"].includes(raw.offer) ? raw.offer : "unknown", content: ["game", "dlc", "demo", "playtest", "other"].includes(raw.content) ? raw.content : "unknown", countHint: ["possible", "no"].includes(raw.countHint) ? raw.countHint : "unknown", automatic: raw.automatic === true, coverUrl: typeof raw.coverUrl === "string" ? raw.coverUrl.slice(0, 1e3) : void 0, releaseDate: typeof raw.releaseDate === "string" ? raw.releaseDate.slice(0, 100) : void 0, isNew: raw.isNew === true, infoStatus: ["ready", "missing", "error"].includes(raw.infoStatus) ? raw.infoStatus : void 0, infoError: typeof raw.infoError === "string" ? raw.infoError.slice(0, 300) : void 0, ...Object.fromEntries(["startsAt", "claimEndsAt", "licenseExpiresAt"].flatMap((k) => Number.isFinite(raw[k]) ? [[k, raw[k]]] : [])) }); return [item]; }); } async function loadState(store, accountId, recover = true) { const raw = await store.getValue(stateKey(accountId), null); if (!raw || raw.schemaVersion !== 1 || raw.accountId !== accountId || !Array.isArray(raw.items)) return freshState(accountId); const state = freshState(accountId); const accepted = /* @__PURE__ */ new Set(["review", "ready", "claiming", "pending", "verified", "owned", "expired", "future", "blocked", "base-required", "invalid", "retry", "unknown"]); state.items = validateCandidates(raw.items).map((c) => { const old = raw.items.find((i) => i.subId === c.subId); return { ...toItem(c), status: accepted.has(old.status) ? old.status : "review", selected: old.selected === true, attempts: Number.isInteger(old.attempts) ? Math.max(0, old.attempts) : 0, message: typeof old.message === "string" ? old.message.slice(0, 300) : "", updatedAt: old.updatedAt || Date.now() }; }); state.cooldownUntil = Number.isFinite(raw.cooldownUntil) ? raw.cooldownUntil : 0; state.scanOffset = Number.isInteger(raw.scanOffset) && raw.scanOffset >= 0 && raw.scanOffset <= 1e7 ? raw.scanOffset : 0; state.run = raw.run === "running" ? recover ? "paused" : "running" : raw.run === "paused" ? "paused" : "idle"; state.message = raw.run === "running" && recover ? "检测到上次任务中断,请先点击“核验已拥有”;不会自动恢复领取。" : String(raw.message || state.message).slice(0, 300); for (const item of state.items) if (recover && item.status === "claiming") { item.status = "pending"; item.selected = false; item.message = "上次请求中断,请先核验许可证"; } return state; } // src/steam/guide.ts var GUIDE_URL = "https://steamcommunity.com/sharedfiles/filedetails/?id=2827818083"; function parseGuide(doc) { const sections = [...doc.querySelectorAll(".subSection")]; const section = sections.find((el) => /^ii\)\s*Add licenses with ASF$/i.test(el.querySelector(".subSectionTitle")?.textContent?.trim() ?? "")) ?? doc.getElementById("5484125"); if (!section || !/ii\)\s*Add licenses with ASF/i.test(section.textContent ?? "")) throw new Error("指南集中清单章节不可读,已保留原缓存。"); const body = section.querySelector(".subSectionDesc") ?? section; const code = [...body.querySelectorAll(".bb_code, pre, code")].find((el) => /^\s*!addlicense\s+ASF\b/i.test(el.textContent ?? "")); const text = code?.textContent?.trim() ?? (body.textContent ?? "").split(/\r?\n/).find((line) => /^\s*!addlicense\s+ASF\b/i.test(line))?.trim() ?? ""; const command = text.match(/^!addlicense\s+ASF\s+(s\/\d+(?:\s*,\s*s\/\d+)*)\s*$/i)?.[1]; if (!command) throw new Error("指南未返回完整有效的 SubID 清单,已保留原缓存。"); const ids = [...new Set([...command.matchAll(/s\/(\d+)/g)].map((m) => validSubId(m[1])))]; if (ids.some((id) => id === void 0) || !ids.length || ids.length > 500) throw new Error("指南清单数量或 ID 异常,已保留原缓存。"); const stats = [...doc.querySelectorAll(".detailsStatRight")].map((el) => el.textContent?.trim() ?? ""); return { ids, updatedLabel: stats.at(-1) ?? "" }; } async function fetchGuide(signal) { signal.throwIfAborted(); const task = GM.xmlHttpRequest({ method: "GET", url: GUIDE_URL, anonymous: true, timeout: 2e4, headers: { Accept: "text/html" } }); const abort = () => { if (typeof task.abort === "function") task.abort(); }; signal.addEventListener("abort", abort, { once: true }); try { const response = await task; signal.throwIfAborted(); if (response.status === 429) throw new Error("Steam 指南请求受限(HTTP 429),请稍后手动同步;原缓存已保留。"); const finalUrl = new URL(response.finalUrl || GUIDE_URL); if (response.status !== 200 || finalUrl.origin !== "https://steamcommunity.com" || finalUrl.pathname !== "/sharedfiles/filedetails/" || finalUrl.searchParams.get("id") !== "2827818083") { throw new Error("指南请求失败或跳转登录页,已保留原缓存。"); } return parseGuide(new DOMParser().parseFromString(response.responseText, "text/html")); } catch (error) { if (signal.aborted) throw new DOMException("同步已取消", "AbortError"); if (error instanceof Error) throw error; throw new Error("无法读取 Steam 指南,请检查脚本管理器的网络权限后手动同步。"); } finally { signal.removeEventListener("abort", abort); } } // src/steam/packages.ts var MetadataRateLimit = class extends Error { }; function safeCover(value) { if (typeof value !== "string") return; try { const u = new URL(value); if (u.protocol === "https:" && (/^(?:[a-z0-9-]+\.)*steamstatic\.com$/i.test(u.hostname) || u.hostname === "steamcdn-a.akamaihd.net")) return u.href; } catch { } } function coverFallback(appId) { return `https://shared.fastly.steamstatic.com/store_item_assets/steam/apps/${appId}/header.jpg`; } function missingEntry(subId, message, kind = "missing") { return { ...candidate(subId, GUIDE_URL), countHint: "possible", infoStatus: kind, infoError: message, fetchedAt: Date.now(), isNew: false }; } var PackageReader = class { request; apps = /* @__PURE__ */ new Map(); country; signal; constructor(country, signal, request = fetch) { this.country = country; this.signal = signal; this.request = (url, options) => request(url, options); } async json(url) { this.signal.throwIfAborted(); const controller = new AbortController(); const abort = () => controller.abort(); this.signal.addEventListener("abort", abort, { once: true }); const timer = setTimeout(abort, 2e4); try { const response = await this.request(url.href, { credentials: "same-origin", cache: "no-store", signal: controller.signal }); this.signal.throwIfAborted(); if (response.status === 429) throw new MetadataRateLimit("Steam 详情读取限流,请稍后手动同步;原缓存已保留。"); if (!response.ok) throw new Error(`Steam 详情读取失败(HTTP ${response.status})`); return await response.json(); } finally { clearTimeout(timer); this.signal.removeEventListener("abort", abort); } } app(appId) { let task = this.apps.get(appId); if (!task) { const url = new URL("https://store.steampowered.com/api/appdetails"); url.search = new URLSearchParams({ appids: String(appId), cc: this.country, l: "schinese" }).toString(); task = this.json(url).then((data) => data?.[appId]?.success === true ? data[appId].data : void 0); this.apps.set(appId, task); } return task; } async read(subId) { const url = new URL("https://store.steampowered.com/api/packagedetails"); url.search = new URLSearchParams({ packageids: String(subId), cc: this.country, l: "schinese" }).toString(); const payload = await this.json(url); const entry = payload?.[subId]; if (entry?.success !== true || !entry.data || typeof entry.data.name !== "string") { return missingEntry(subId, "当前地区的包详情不可用,可能受地区或上架状态限制;可手动同步重试。"); } const data = entry.data; const appIds = [...new Set((Array.isArray(data.apps) ? data.apps : []).map((app) => validSubId(app.id)).filter((id) => id !== void 0))].slice(0, 100); const c = { ...candidate(subId, GUIDE_URL), appIds, name: data.name.slice(0, 200), infoStatus: "ready", fetchedAt: Date.now(), isNew: false, countHint: "possible", offer: "evergreen" }; c.releaseDate = typeof data.release_date?.date === "string" ? data.release_date.date : void 0; let first; for (const appId of appIds.slice(0, 4)) { try { const info = await this.app(appId); if (info && (!first || info.type === "game")) first = info; if (info?.type === "game") break; } catch (error) { if (this.signal.aborted || error instanceof MetadataRateLimit) throw error; c.infoError = "包信息已缓存,部分应用详情读取失败;可手动同步重试。"; } } if (first) { c.content = first.type === "game" ? "game" : first.type === "dlc" ? "dlc" : first.type === "demo" ? "demo" : first.type === "playtest" ? "playtest" : "other"; c.coverUrl = safeCover(first.header_image) ?? safeCover(first.capsule_image); } c.coverUrl ??= safeCover(data.page_image) ?? safeCover(data.small_logo) ?? (appIds[0] ? coverFallback(appIds[0]) : void 0); if (typeof data.price?.final === "number" && data.price.final > 0) { c.infoStatus = "missing"; c.infoError = "商店当前显示此包有价格,暂停自动领取;请核对包信息。"; } return c; } }; // src/core/catalog.ts var DATABASE_KEY = "sfl:library:v2"; var DATABASE_LOCK = "sfl:library-database:v2"; async function loadDatabase(store) { const raw = await store.getValue(DATABASE_KEY, null); if (!raw || raw.schemaVersion !== 2 || !raw.accounts || typeof raw.accounts !== "object") return { schemaVersion: 2, catalog: null, accounts: {} }; const catalog = raw.catalog; if (catalog && (catalog.schemaVersion !== 1 || !Array.isArray(catalog.entries) || !Number.isFinite(catalog.syncedAt) || catalog.entries.length > 500 || !catalog.entries.every((c) => c && validSubId(c.subId) && typeof c.name === "string" && Array.isArray(c.appIds)))) { throw new Error("本地清单缓存格式异常,请导出记录后检查脚本存储。"); } return structuredClone(raw); } async function readAccount(db, id, recover = true) { const account = db.accounts[id]; const store = { getValue: async (_k, fallback) => account ?? fallback, setValue: async () => { } }; const state = account ? await loadState(store, id, recover) : freshState(id); reconcileAccount(state, db.catalog); db.accounts[id] = state; return state; } function reconcileAccount(state, catalog) { if (!catalog) { state.items = []; return; } const old = new Map(state.items.map((i) => [i.subId, i])); state.items = catalog.entries.map((c) => { const existing = old.get(c.subId); const item = existing ? { ...existing, ...c } : toItem(c); item.coverUrl = safeCover(c.coverUrl); if (["review", "ready", "future", "expired", "blocked"].includes(item.status)) Object.assign(item, eligibility(item)); if (c.infoStatus !== "ready") { item.selected = false; if (!["verified", "owned", "pending", "unknown"].includes(item.status)) item.message = c.infoError || "游戏信息尚未加载完成"; } else if (item.status === "review") item.message = c.infoError || "指南候选;游戏数 +1 尚未实测"; return item; }); } async function synchronizeCatalog(previous, country, services) { const source = await services.guide(); services.signal.throwIfAborted(); if (!source.ids.length || source.ids.length > 500 || source.ids.some((id) => !validSubId(id))) throw new Error("指南清单无效,已保留原缓存。"); const ids = [...new Set(source.ids)]; const old = new Map(previous?.entries.map((i) => [i.subId, i]) ?? []); const entries = []; let errors = 0; for (const id of ids) { services.signal.throwIfAborted(); let entry; try { entry = await services.details(id); } catch (error) { if (services.signal.aborted || error instanceof MetadataRateLimit) throw error; entry = missingEntry(id, "包信息读取失败,可稍后手动同步重试。", "error"); } services.signal.throwIfAborted(); const existing = old.get(id); if (entry.infoStatus !== "ready") { errors++; if (existing) entry = { ...existing, infoStatus: entry.infoStatus, infoError: entry.infoError, fetchedAt: entry.fetchedAt }; } entries.push({ ...entry, subId: id, sourceUrl: GUIDE_URL, isNew: existing ? existing.isNew : previous !== null }); services.progress(entries.length, ids.length); if (entries.length < ids.length) await services.wait(); } services.signal.throwIfAborted(); return { catalog: { schemaVersion: 1, syncedAt: Date.now(), country, updatedLabel: source.updatedLabel, entries }, added: ids.filter((id) => !old.has(id)).length, removed: [...old.keys()].filter((id) => !ids.includes(id)).length, errors, first: previous === null }; } async function commitCatalog(db, catalog, store, signal) { const next = structuredClone(db); const legacy = (await store.listValues()).filter((k) => /^sfl:account:v1:\d+$/.test(k) || /^sfl:inbox:v1(?::(?:steamdb|keylol))?$/.test(k)); for (const key of legacy.filter((k) => k.startsWith("sfl:account:v1:"))) { const id = key.slice("sfl:account:v1:".length); if (!db.catalog || !next.accounts[id]) { const old = await loadState(store, id), current = next.accounts[id]; next.accounts[id] = current ? { ...old, run: current.run, message: current.message, cooldownUntil: Math.max(old.cooldownUntil, current.cooldownUntil) } : old; } } next.catalog = catalog; for (const account of Object.values(next.accounts)) reconcileAccount(account, catalog); signal?.throwIfAborted(); await store.setValue(DATABASE_KEY, next); Object.assign(db, next); for (const key of legacy) await store.deleteValue(key); } function markCatalogRead(db) { if (!db.catalog) return; for (const item of db.catalog.entries) item.isNew = false; for (const account of Object.values(db.accounts)) reconcileAccount(account, db.catalog); } // src/steam/verify.ts function applyVerification(state, snapshot) { if (snapshot.accountId !== state.accountId) throw new Error("核验账号与队列账号不一致"); if (!snapshot.readable) throw new Error("许可证表格不可读,无法核验;请刷新后重试"); let count = 0; for (const item of state.items) { if (!snapshot.owned.has(item.subId)) { if (["pending", "unknown"].includes(item.status)) item.message = `本次已拥有包列表未找到 Sub ${item.subId};仍待确认,可稍后点击“核验已拥有”。${snapshot.warning ?? ""}`; continue; } if (["verified", "owned"].includes(item.status)) continue; const submitted = ["claiming", "pending", "unknown", "retry"].includes(item.status); item.status = submitted ? "verified" : "owned"; item.message = submitted ? "已在当前账号的已拥有包列表中核验到此 SubID" : "当前账号已拥有此 SubID"; item.selected = false; item.updatedAt = Date.now(); count++; } return count; } // src/core/queue.ts var QueueRunner = class { state; services; control = "run"; constructor(state, services) { this.state = state; this.services = services; } pause() { this.control = "pause"; } stop() { this.control = "stop"; } getControl() { return this.control; } async commit() { await this.services.save(this.state); } async verify() { this.services.assertAccount(); applyVerification(this.state, await this.services.verify()); await this.commit(); } async run() { const s = this.state; if (s.cooldownUntil > this.services.now()) throw new Error("冷却尚未结束,请稍后恢复"); this.control = "run"; s.run = "running"; s.message = "正在检查当前账号的许可证…"; try { await this.commit(); await this.verify(); const tasks = s.items.filter((i) => i.selected && ["review", "ready", "retry", "unknown"].includes(i.status)); for (const item of tasks) { if (this.control !== "run") break; if (!item.selected) continue; const gate = eligibility(item, this.services.now()); if (gate.status !== "review") { Object.assign(item, gate, { selected: false }); await this.commit(); continue; } if (item.attempts >= 3) { item.selected = false; item.status = "unknown"; item.message = "此包已尝试 3 次,请人工检查后再处理"; await this.commit(); continue; } this.services.assertAccount(); item.status = "claiming"; item.attempts++; item.updatedAt = this.services.now(); item.message = "正在请求免费许可证…"; s.message = `正在领取 Sub ${item.subId};暂停或停止会在当前请求结束后生效。`; await this.commit(); const result = await this.services.claim(item.subId); this.services.assertAccount(); this.applyResult(item, result); await this.commit(); if (result.kind === "accepted") { try { await this.verify(); } catch { item.message = "领取请求已返回,但许可证读取失败;请点击“核验已拥有”。"; await this.commit(); } } if (["rate-limit", "auth", "unknown"].includes(result.kind)) { if (this.getControl() === "run") this.control = "pause"; s.message = result.message; break; } if (this.control === "run" && tasks.some((t) => t.selected && ["review", "ready", "retry", "unknown"].includes(t.status))) { let remaining = this.services.interval(); while (remaining > 0 && this.control === "run") { const chunk = Math.min(250, remaining); await this.services.sleep(chunk); remaining -= chunk; } } } if (s.items.some((i) => ["pending", "unknown"].includes(i.status))) { try { await this.verify(); } catch { s.message = "本批请求已结束,但许可证核验未完成;请登录商店后点击“核验已拥有”。"; } } const endControl = this.getControl(); s.run = endControl === "pause" ? "paused" : endControl === "stop" ? "stopped" : "idle"; if (endControl === "run") s.message = "本批处理结束。待核验项目可稍后点击“核验已拥有”。"; if (endControl === "pause" && s.message.startsWith("正在")) s.message = "已暂停,点击继续可处理剩余选中项目。"; if (endControl === "stop") s.message = "已停止,未发送的项目保留在列表中。"; } catch (error) { s.run = "paused"; s.message = error instanceof Error ? error.message : "任务已暂停,请刷新后检查"; for (const item of s.items) if (item.status === "claiming") { item.status = "pending"; item.selected = false; item.message = "请求结果未确认,请先核验许可证"; } } finally { await this.commit(); } } applyResult(item, result) { item.message = result.message; item.updatedAt = this.services.now(); if (result.kind === "rate-limit") { this.state.cooldownUntil = this.services.now() + (result.retryAfterMs ?? 60 * 6e4); item.status = "retry"; } else if (result.kind === "auth") { item.status = "retry"; } else { item.selected = false; item.status = result.kind === "accepted" ? "pending" : result.kind === "unknown" ? "unknown" : result.kind; } } }; // src/steam/session.ts var STEAM_ID_BASE = 76561197960265728n; function accountIdentity(doc) { const account = doc.querySelector('#account_pulldown, [data-miniprofile][id="account_pulldown"]'); if (!account) return; const scripts = [...doc.querySelectorAll("script:not([src])")].map((s) => s.textContent ?? "").join("\n"); let accountId = scripts.match(/\bg_steamID\s*=\s*["'](7656\d{13})["']/)?.[1]; const accountNumber = scripts.match(/\bg_AccountID\s*=\s*(\d+)/)?.[1]; if (!accountId && accountNumber && Number(accountNumber) > 0 && Number(accountNumber) <= 4294967295) { accountId = String(STEAM_ID_BASE + BigInt(accountNumber)); } for (const el of doc.querySelectorAll("[data-userinfo], #application_config[data-config]")) { try { const data = JSON.parse(el.getAttribute("data-userinfo") ?? el.getAttribute("data-config") ?? "{}"); const id = data.steamid ?? data.STEAMID ?? data.userinfo?.steamid; if (/^7656\d{13}$/.test(String(id))) accountId ??= String(id); } catch { } } if (!accountId) { const profile = doc.querySelector('#global_actions a.user_avatar, #global_actions a[href*="/profiles/"]'); accountId = profile?.getAttribute("href")?.match(/\/profiles\/(7656\d{13})(?:\/|$)/)?.[1]; } if (!accountId) return; return { accountId, name: account.textContent?.trim() || "Steam 账号" }; } function readSession(doc, cookie) { const identity = accountIdentity(doc); if (!identity) throw new Error("无法确认当前 Steam 账号。请登录商店并刷新许可证页。"); const scripts = [...doc.querySelectorAll("script:not([src])")].map((s) => s.textContent ?? "").join("\n"); const cookieValue = cookie.split(";").map((p) => p.trim()).find((p) => p.startsWith("sessionid="))?.slice(10); const sessionId = cookieValue ?? scripts.match(/\bg_sessionID\s*=\s*["']([a-zA-Z0-9]+)["']/)?.[1]; if (!sessionId || !/^[a-zA-Z0-9]{12,128}$/.test(sessionId)) throw new Error("Steam 会话不可用,请刷新许可证页后重试。"); return { ...identity, sessionId }; } // src/steam/licenses.ts function parseLicenses(doc, expectedAccountId) { const identity = accountIdentity(doc); if (identity?.accountId !== expectedAccountId) throw new Error("登录账号已变化或失效,请刷新页面。"); const tables = [...doc.querySelectorAll(".account_table, #licenses_table, [data-license-table]")]; const owned = /* @__PURE__ */ new Set(); for (const table of tables) { for (const el of table.querySelectorAll("[data-packageid], [data-subid], a[href], [onclick]")) { for (const attr of ["data-packageid", "data-subid"]) { const id = validSubId(el.getAttribute(attr)); if (id) owned.add(id); } for (const attr of ["href", "onclick"]) { const source = el.getAttribute(attr) ?? ""; for (const match of source.matchAll(/\bRemoveFreeLicense\s*\(\s*['"]?(\d+)['"]?\s*[,)]/g)) { const id = validSubId(match[1]); if (id) owned.add(id); } } } } return { accountId: expectedAccountId, owned, readable: tables.length > 0 }; } async function fetchLicenses(accountId, request = fetch, currentDocument = document) { const assertCurrentAccount = () => { if (accountIdentity(currentDocument)?.accountId !== accountId) throw new Error("当前页面账号已变化或未登录,请刷新后核验。"); }; assertCurrentAccount(); const url = new URL("https://store.steampowered.com/dynamicstore/userdata/"); url.searchParams.set("_", String(Date.now())); let packageError = ""; try { const packagesResponse = await request(url.href, { credentials: "same-origin", cache: "no-store", signal: AbortSignal.timeout(2e4) }); if (!packagesResponse.ok) throw new Error(`已拥有包接口 HTTP ${packagesResponse.status}`); if (packagesResponse.url && new URL(packagesResponse.url).pathname.includes("/login")) throw new Error("已拥有包接口跳转登录页"); const payload = await packagesResponse.json(); if (!Array.isArray(payload?.rgOwnedPackages) || !payload.rgOwnedPackages.every((id) => typeof id === "number" && (id === 0 || validSubId(id)))) throw new Error("已拥有包列表格式异常"); assertCurrentAccount(); return { accountId, owned: new Set(payload.rgOwnedPackages.filter((id) => id !== 0)), readable: true }; } catch (error) { assertCurrentAccount(); packageError = error instanceof Error ? error.message : "已拥有包接口读取失败"; } try { const response = await request("https://store.steampowered.com/account/licenses/", { credentials: "same-origin", cache: "no-store", signal: AbortSignal.timeout(2e4) }); if (!response.ok) throw new Error(`许可证页 HTTP ${response.status}`); if (response.url && new URL(response.url).pathname.includes("/login")) throw new Error("许可证页跳转登录页"); const doc = new DOMParser().parseFromString(await response.text(), "text/html"); const snapshot = parseLicenses(doc, accountId); assertCurrentAccount(); if (!snapshot.readable || !snapshot.owned.size) throw new Error("许可证页未提供可核验的 SubID"); snapshot.warning = `${packageError};当前仅核验页面中带明确 SubID 的条目。`; return snapshot; } catch (error) { assertCurrentAccount(); throw new Error(`核验失败:${packageError};${error instanceof Error ? error.message : "许可证页读取失败"}。未重新提交领取。`); } } // src/steam/claim.ts function retryAfterMs(value, now = Date.now()) { if (!value) return; const ms = /^\d+$/.test(value.trim()) ? Number(value) * 1e3 : Date.parse(value) - now; return Number.isFinite(ms) && ms > 0 ? Math.min(ms, 7 * 24 * 60 * 6e4) : void 0; } function classifyResponse(status, body, retryAfter) { if (status === 429) return { kind: "rate-limit", message: "Steam 请求限流,队列已暂停", retryAfterMs: retryAfterMs(retryAfter ?? null) }; if ([401, 403].includes(status)) return { kind: "auth", message: "登录已失效或受到家庭限制,请在 Steam 页面处理后刷新" }; let data; try { data = JSON.parse(body); } catch { return { kind: /login|parentalunlock|parentalfeaturerequest|captcha/i.test(body) ? "auth" : "unknown", message: "收到非预期页面,请检查登录或验证提示;领取结果待核验" }; } if (status >= 200 && status < 300 && Array.isArray(data) && data.length === 0) { return { kind: "accepted", message: "Steam 已接受请求,等待许可证核验" }; } const code = data && typeof data === "object" ? data.purchaseresultdetail : void 0; switch (code) { case 5: return { kind: "invalid", message: "Steam 返回无效包(5)" }; case 9: return { kind: "owned", message: "Steam 返回已拥有(9)" }; case 24: return { kind: "base-required", message: "缺少所需游戏本体(24)" }; case 53: return { kind: "rate-limit", message: "Steam 激活限流(53),队列已暂停", retryAfterMs: retryAfterMs(retryAfter ?? null) }; default: return { kind: "unknown", message: `未识别的 Steam 响应(HTTP ${status}${typeof code === "number" ? `,代码 ${code}` : ""}),请核验许可证` }; } } async function claimFreeLicense(subId, session, request = fetch) { if (!validSubId(subId)) throw new Error("SubID 无效"); if (typeof location !== "undefined" && location.origin !== "https://store.steampowered.com") { throw new Error("请从 Steam 商店许可证页领取"); } try { const response = await request(`https://store.steampowered.com/freelicense/addfreelicense/${subId}`, { method: "POST", credentials: "same-origin", signal: AbortSignal.timeout(2e4), headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", "X-Requested-With": "XMLHttpRequest" }, body: new URLSearchParams({ ajax: "true", sessionid: session.sessionId }) }); return classifyResponse(response.status, await response.text(), response.headers.get("Retry-After")); } catch { return { kind: "unknown", message: "网络中断或请求超时,可能已经提交;先核验许可证再决定是否重试" }; } } // src/steam/discovery.ts function readStoreCountry(doc, cookie = "") { const valid = (value) => typeof value === "string" && /^[a-z]{2}$/i.test(value) ? value.toLowerCase() : void 0; for (const el of doc.querySelectorAll("[data-config]")) { try { const data = JSON.parse(el.getAttribute("data-config") ?? "{}"); const cc2 = valid(data.COUNTRY ?? data.country); if (cc2) return cc2; } catch { } } const script = [...doc.querySelectorAll("script:not([src])")].map((s) => s.textContent ?? "").join("\n"); const cc = valid(script.match(/\bg_strCountryCode\s*=\s*["']([a-z]{2})["']/i)?.[1]); if (cc) return cc; try { return valid(decodeURIComponent(cookie.split(";").map((s) => s.trim()).find((s) => s.startsWith("steamCountry="))?.slice(13) ?? "").split("|")[0]); } catch { return; } } // src/ui/styles.ts var panelStyles = ` :host{color-scheme:dark;color:#dcdedf;font:14px/1.5 Arial,"Microsoft YaHei",sans-serif}*{box-sizing:border-box}[hidden]{display:none!important} dialog{display:flex;flex-direction:column;width:min(940px,calc(100vw - 40px));max-width:none;max-height:calc(100dvh - 40px);margin:auto;padding:18px;background:#1b2838;border:1px solid #526779;border-radius:0;box-shadow:0 12px 48px #0009;color:inherit;font:inherit;overflow:hidden}dialog:not([open]){display:none}dialog::backdrop{background:#000b} header{padding:0;background:transparent;font:inherit;display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:10px;flex-shrink:0}h2{color:#fff;font-size:20px;font-weight:500;margin:0}p{margin:0}button{color:#dcdedf;background:linear-gradient(90deg,#354b60,#2b4255);border:1px solid #526779;border-radius:2px;padding:7px 11px;min-height:36px;font:inherit;cursor:pointer}button:hover{background:#466781;color:#fff}button:disabled{opacity:.45;cursor:default}button.primary{background:#2b5877;border-color:#5585a5}:focus-visible{outline:2px solid #66c0f4;outline-offset:3px} .filter-form{display:flex;align-items:flex-end;gap:10px;flex-shrink:0;margin:0;padding:8px 0 12px;border-block:1px solid #3d5060}.fields{display:grid;flex:1;grid-template-columns:minmax(0,1.4fr) minmax(130px,1fr);gap:10px 12px;min-width:0}.fields label{display:flex;flex-direction:column;gap:4px;min-width:0;color:#c6d4df;font-size:13px}input:not([type=checkbox]),select{width:100%;min-width:0;max-width:100%;min-height:36px;padding:6px 8px;background:#111d29;border:1px solid #526779;border-radius:2px;color:#fff;font:inherit}.form-actions{display:flex;align-items:center;flex-wrap:nowrap;gap:8px;white-space:nowrap} .feedback{display:flex;align-items:center;flex-wrap:wrap;gap:8px;padding:10px 0 4px;flex-shrink:0;font-size:13px;color:#c6d4df}.feedback p{overflow-wrap:anywhere}.sync-info{width:100%;font-size:12px;color:#a8b7c5}.sync-info a{color:#66c0f4}progress{width:100px;height:5px;accent-color:#66c0f4}.selection{display:flex;align-items:center;flex-wrap:wrap;gap:8px;padding:10px 0;flex-shrink:0;border-top:1px solid #3d5060;margin-top:6px}.selection>label{display:flex;align-items:center;gap:6px;min-height:36px;cursor:pointer}.selection-count{margin-right:auto;color:#b8d8ed;font-size:13px} .results-scroll{flex:1 1 auto;min-height:120px;max-height:55dvh;overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable}.card{position:relative;display:grid;grid-template-columns:28px 160px minmax(0,1fr) max-content;align-items:center;gap:12px;margin:6px 0;padding:10px;background:linear-gradient(105deg,#213b51,#1b2c3d);border:1px solid transparent}.card.selected{border-color:#66c0f4;background:#25445c}.check{display:flex;align-items:center;justify-content:center;min-height:44px;align-self:stretch;cursor:pointer}input[type=checkbox]{width:18px;height:18px;accent-color:#66c0f4;vertical-align:middle;cursor:pointer}.cover{position:relative;width:160px;height:75px;background:#14202d;overflow:hidden}.cover img{display:block;width:100%;height:100%;object-fit:cover}.cover span{position:absolute;inset:0;display:grid;place-items:center;color:#8f9dab;font-size:12px}.info{min-width:0}.title-line{display:flex;align-items:center;flex-wrap:wrap;gap:8px}.title-line a{color:#fff;text-decoration:none;font-size:16px;overflow-wrap:anywhere}.title-line a:hover{color:#66c0f4}.info p{display:block;margin-top:5px;font-size:12px;color:#a8b7c5;overflow-wrap:anywhere}.new{display:inline-block;flex-shrink:0;white-space:nowrap;border:1px solid #66c0f4;padding:0 5px;color:#b8e3ff;background:#25445c;font-size:11px;font-weight:700;line-height:18px}.item-actions{display:flex;align-items:flex-end;flex-direction:column;gap:6px}.status{font-size:12px;color:#c6d4df}.status.good{color:#a4d8b7}.empty{color:#a8b7c5;text-align:center;padding:25px 10px}.empty strong{display:block;color:#dcdedf;font-size:15px;font-weight:500;margin-bottom:6px}.more{width:100%;margin-top:8px}footer{flex-shrink:0;border-top:1px solid #3d5060;margin-top:10px;padding-top:10px;color:#a8b7c5;font-size:12px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px}.account{color:#a8b7c5;font-size:12px;margin-top:3px} @media(max-width:640px){dialog{width:calc(100vw - 20px);padding:12px;max-height:calc(100dvh - 20px)}.filter-form{flex-direction:column;align-items:stretch}.fields{grid-template-columns:minmax(0,1fr) minmax(110px,.7fr)}.form-actions{flex-wrap:wrap}button{min-height:44px}.card{grid-template-columns:minmax(0,1fr);gap:8px;padding:8px}.cover{width:100%;height:auto;aspect-ratio:460/215;grid-column:1}.cover img{position:absolute;inset:0}.check{position:absolute;left:14px;top:14px;z-index:2;width:44px;background:#111d29df;border-radius:2px}.info{grid-column:1}.item-actions{flex-direction:row;justify-content:space-between;align-items:center}.selection{gap:6px}.selection>label{flex:1 1 100%}.selection-count{flex:1}.selection button{flex:1}header{align-items:flex-start}.account{overflow-wrap:anywhere}} @media(max-width:640px){.selection-count{flex:1 1 100%}.selection button{flex:1 1 auto}} `; // src/ui/panel.ts function eligibleItem(item) { return item.infoStatus === "ready" && item.attempts < 3 && eligibility(item).status === "review" && ["review", "ready", "retry"].includes(item.status); } var Panel = class { host; root; dialog; actions; view = { catalog: null, busy: false, remote: false }; previousFocus = null; cooldownTimer; limit = 50; observer; constructor(doc, actions) { this.actions = actions; this.host = doc.createElement("div"); this.host.id = "steam-free-library"; this.root = this.host.attachShadow({ mode: "open" }); this.root.innerHTML = `

免费入库

正在读取本地清单…

Steam +1 候选指南

`; doc.body.append(this.host); this.dialog = this.root.querySelector("dialog"); const bind = (id, fn) => { this.el(id).onclick = () => { void this.perform(fn); }; }; bind("close", () => this.close()); bind("sync", () => actions.sync()); bind("read", () => actions.markRead()); bind("check", () => actions.check()); bind("start", () => actions.claimSelected()); bind("automatic-start", () => actions.claimAll()); bind("stop", () => actions.stop()); bind("export", () => actions.exportResults()); this.root.querySelector("form").onsubmit = (event) => event.preventDefault(); this.el("query").oninput = () => { this.limit = 50; this.render(this.view); }; this.el("filter").onchange = () => { this.limit = 50; this.render(this.view); }; this.el("all").onchange = () => { const checked = this.el("all").checked; void this.perform(() => actions.select(this.filtered().filter(eligibleItem).map((i) => i.subId), checked)); }; this.dialog.addEventListener("cancel", (event) => { event.preventDefault(); this.close(); }); this.dialog.addEventListener("click", (event) => { if (event.target !== this.dialog) return; const r = this.dialog.getBoundingClientRect(); if (event.clientX < r.left || event.clientX > r.right || event.clientY < r.top || event.clientY > r.bottom) this.close(); }); } el(id) { return this.root.getElementById(id); } async perform(fn) { try { await fn(); } catch (error) { this.el("notice").textContent = error instanceof Error ? error.message : "操作失败,请稍后重试"; } } open() { if (this.dialog.open) return; this.previousFocus = this.host.ownerDocument.activeElement; this.dialog.showModal(); this.el("close").focus(); } close() { this.actions.close(); this.dialog.close(); this.observer?.disconnect(); if (this.previousFocus instanceof HTMLElement) this.previousFocus.focus(); } filtered() { const words = this.el("query").value.toLowerCase().trim().split(/\s+/).filter(Boolean); const filter = this.el("filter").value; return (this.view.state?.items ?? []).filter((i) => { const text = `${i.name} ${i.subId} ${i.appIds.join(" ")}`.toLowerCase(); return words.every((w) => text.includes(w)) && (filter === "all" || filter === "ready" && eligibleItem(i) || filter === "new" && i.isNew || filter === "owned" && ["verified", "owned"].includes(i.status) || filter === "missing" && i.infoStatus !== "ready"); }); } render(view) { this.view = view; const s = view.state, catalog = view.catalog, blocked = view.busy || view.remote || !s; this.dialog.setAttribute("aria-busy", String(view.busy)); this.el("account").textContent = s ? `${view.accountName || "Steam 账号"} · ${s.accountId}` : "请先登录 Steam 商店"; const cooling = Boolean(s && s.cooldownUntil > Date.now()); clearTimeout(this.cooldownTimer); if (cooling && s) this.cooldownTimer = setTimeout(() => this.render(this.view), Math.min(s.cooldownUntil - Date.now() + 25, 2147483647)); this.el("notice").textContent = `${view.notice || (view.remote ? "另一标签正在同步或领取,请在该标签完成操作。" : s?.message || "请登录 Steam 商店后重新打开。")}${cooling && s ? ` 冷却至 ${new Date(s.cooldownUntil).toLocaleTimeString()},届时请手动继续。` : ""}`; this.el("sync-info").textContent = catalog ? ` · 上次同步 ${new Date(catalog.syncedAt).toLocaleString()} · ${catalog.entries.length} 个包${catalog.updatedLabel ? ` · 指南更新 ${catalog.updatedLabel}` : ""}` : " · 首次打开将自动拉取并缓存"; const progress = this.el("progress"); progress.hidden = !view.progress; if (view.progress) { progress.max = Math.max(1, view.progress.total); progress.value = view.progress.done; } for (const id of ["sync", "read", "check"]) this.el(id).disabled = blocked; this.el("read").disabled ||= !catalog?.entries.some((i) => i.isNew); this.el("sync").textContent = view.activity === "sync" && view.busy ? "正在同步…" : "手动同步"; this.el("check").textContent = view.activity === "check" && view.busy ? "正在核验…" : "核验已拥有"; this.el("automatic-start").disabled = blocked || cooling || !s?.items.some(eligibleItem); this.el("automatic-start").textContent = s?.run === "paused" && s.items.some(eligibleItem) ? "继续一键入库" : "一键入库"; this.el("start").disabled = blocked || cooling || !s?.items.some((i) => i.selected && eligibleItem(i)); this.el("stop").hidden = !view.busy; this.el("stop").textContent = view.activity === "sync" ? "取消同步" : "停止"; this.el("export").disabled = !catalog; const items = this.filtered(), eligible = items.filter(eligibleItem), selected = s?.items.filter((i) => i.selected).length ?? 0; this.el("selection").textContent = `显示 ${items.length} / ${s?.items.length ?? 0} · 已选 ${selected} · NEW ${catalog?.entries.filter((i) => i.isNew).length ?? 0}`; const all = this.el("all"); all.disabled = blocked || !eligible.length; all.checked = Boolean(eligible.length && eligible.every((i) => i.selected)); all.indeterminate = eligible.some((i) => i.selected) && !all.checked; const list = this.el("list"), scrollTop = list.scrollTop, focused = this.root.activeElement?.getAttribute("data-sub"); this.observer?.disconnect(); list.replaceChildren(); if (!items.length) { const empty = this.host.ownerDocument.createElement("p"); empty.className = "empty"; const strong = this.host.ownerDocument.createElement("strong"); strong.textContent = catalog ? "没有符合条件的条目" : "正在准备指南清单"; empty.append(strong, catalog ? "可调整筛选条件,或点击“手动同步”。" : "首次加载完成后将自动保存,后续直接读取缓存。"); list.append(empty); } for (const item of items.slice(0, this.limit)) list.append(this.row(item, blocked, cooling)); if (items.length > this.limit) { const more = this.host.ownerDocument.createElement("button"); more.className = "more"; more.textContent = "继续显示 50 项"; const append = () => { this.limit += 50; this.render(this.view); }; more.onclick = append; list.append(more); if (typeof IntersectionObserver === "function") { this.observer = new IntersectionObserver((entries) => { if (entries.some((e) => e.isIntersecting)) append(); }, { root: list }); this.observer.observe(more); } } list.scrollTop = scrollTop; if (focused) this.root.querySelector(`input[data-sub="${focused}"]`)?.focus({ preventScroll: true }); } row(item, blocked, cooling) { const doc = this.host.ownerDocument, card = doc.createElement("article"); card.className = `card${item.selected ? " selected" : ""}`; card.dataset.subid = String(item.subId); const label = doc.createElement("label"); label.className = "check"; const input = doc.createElement("input"); input.type = "checkbox"; input.dataset.sub = String(item.subId); input.checked = item.selected; input.setAttribute("aria-label", `选择 ${item.name}`); input.disabled = blocked || !eligibleItem(item); input.onchange = () => { void this.perform(() => this.actions.select([item.subId], input.checked)); }; label.append(input); const cover = doc.createElement("div"); cover.className = "cover"; const placeholder = doc.createElement("span"); placeholder.textContent = "封面暂不可用"; const url = safeCover(item.coverUrl); if (url) { const img = doc.createElement("img"); img.src = url; img.alt = ""; img.width = 160; img.height = 75; img.loading = "lazy"; img.referrerPolicy = "no-referrer"; placeholder.hidden = true; img.onerror = () => { const fallback = item.appIds[0] ? coverFallback(item.appIds[0]) : ""; if (fallback && !img.dataset.fallback && img.src !== fallback) { img.dataset.fallback = "1"; img.src = fallback; } else { img.hidden = true; placeholder.hidden = false; } }; cover.append(img); } cover.append(placeholder); const info = doc.createElement("div"); info.className = "info"; const title = doc.createElement("div"); title.className = "title-line"; const a = doc.createElement("a"); a.href = item.appIds[0] ? `https://store.steampowered.com/app/${item.appIds[0]}/` : `https://store.steampowered.com/sub/${item.subId}/`; a.target = "_blank"; a.rel = "noopener noreferrer"; a.textContent = item.name; title.append(a); if (item.isNew) { const badge = doc.createElement("span"); badge.className = "new"; badge.textContent = "NEW"; badge.setAttribute("aria-label", "同步新增条目"); title.append(badge); } const meta = doc.createElement("p"); meta.textContent = `Sub ${item.subId}${item.appIds.length ? ` · App ${item.appIds.join(", ")}` : ""} · 指南 +1 候选`; const message = doc.createElement("p"); message.textContent = item.infoStatus !== "ready" ? item.infoError || "游戏信息未完整" : item.message; info.append(title, meta, message); if (item.releaseDate) { const time = doc.createElement("p"); time.textContent = `发行日期:${item.releaseDate}`; info.append(time); } const actions = doc.createElement("div"); actions.className = "item-actions"; const status = doc.createElement("span"); status.className = `status${["verified", "owned"].includes(item.status) ? " good" : ""}`; status.textContent = item.infoStatus !== "ready" && !["verified", "owned", "pending", "unknown"].includes(item.status) ? "信息未完整" : LABELS[item.status]; const claim = doc.createElement("button"); claim.type = "button"; claim.textContent = "领取"; claim.disabled = blocked || cooling || !eligibleItem(item); claim.setAttribute("aria-label", `领取 ${item.name}`); claim.onclick = () => { void this.perform(() => this.actions.claimOne(item.subId)); }; actions.append(status, claim); card.append(label, cover, info, actions); return card; } }; // src/ui/menu.ts var PANEL_URL = "https://store.steampowered.com/account/licenses/#steam-free-library"; var isLicensePage = (url) => url.hostname === "store.steampowered.com" && /^\/account\/licenses\/?$/.test(url.pathname); var handlers = /* @__PURE__ */ new WeakMap(); function delegateClicks(doc, openPanel) { if (!handlers.has(doc)) { doc.addEventListener("click", (event) => { const entry = event.target?.closest?.("a[data-sfl-menu]"); if (entry && isLicensePage(new URL(doc.URL)) && event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey) { event.preventDefault(); handlers.get(doc)?.(); } }); } handlers.set(doc, openPanel); } function insertMenuEntries(doc, openPanel) { delegateClicks(doc, openPanel); let count = 0; for (const anchor of doc.querySelectorAll( "#global_header a[href], .responsive_header a[href], .responsive_menu a[href], #responsive_page_menu a[href], .supernav_container a[href]" )) { let url; try { url = new URL(anchor.getAttribute("href") ?? "", doc.URL); } catch { continue; } if (url.hostname !== "store.steampowered.com" || !/^\/explore\/?$/.test(url.pathname)) continue; const parent = anchor.parentElement; if (!parent || parent.querySelector("[data-sfl-menu]")) continue; const entry = doc.createElement("a"); entry.className = anchor.className; entry.setAttribute("data-sfl-menu", "true"); entry.href = PANEL_URL; entry.textContent = "免费入库"; anchor.after(entry); count++; } return count; } function watchMenus(doc, openPanel) { insertMenuEntries(doc, openPanel); let scheduled = false; const observer = new MutationObserver(() => { if (scheduled) return; scheduled = true; queueMicrotask(() => { scheduled = false; insertMenuEntries(doc, openPanel); }); }); observer.observe(doc.body, { childList: true, subtree: true }); return () => observer.disconnect(); } // src/main.ts async function boot() { if (!["store.steampowered.com", "steamcommunity.com"].includes(location.hostname)) return; const store = { getValue: (key, fallback) => GM.getValue(key, fallback), setValue: (key, value) => GM.setValue(key, value), listValues: () => GM.listValues(), deleteValue: (key) => GM.deleteValue(key) }; let panel, db = { schemaVersion: 2, catalog: null, accounts: {} }; let state, accountName = "", busy = false, remote = false, notice = ""; let activity; let progress; let controller, runner, listening = false; const render = () => panel?.render({ state, catalog: db.catalog, accountName, busy, remote, notice, progress, activity }); const persist = async () => { if (state) db.accounts[state.accountId] = state; await store.setValue(DATABASE_KEY, structuredClone(db)); render(); }; const assertAccount = (id) => { if (readSession(document, document.cookie).accountId !== id) throw new Error("当前账号已变化,请刷新后再操作。"); }; async function listen() { if (listening) return; listening = true; await GM.addValueChangeListener(DATABASE_KEY, (_key, _old, _new, otherTab) => { if (!otherTab || busy) return; void (async () => { const identity = accountIdentity(document); if (!identity) return; const next = await loadDatabase(store); if (busy) return; db = next; state = await readAccount(db, identity.accountId, false); remote = Object.values(db.accounts).some((a) => a.run === "running"); notice = ""; render(); })().catch(() => { notice = "本地清单同步失败,请重新打开弹框。"; render(); }); }); } const operate = async (kind, action) => { if (busy) throw new Error("当前操作尚未结束,请先停止或等待。"); if (!navigator.locks) throw new Error("当前浏览器不支持任务互斥,请更新浏览器后重试。"); const session = readSession(document, document.cookie); accountName = session.name; busy = true; activity = kind; notice = ""; render(); try { await navigator.locks.request(DATABASE_LOCK, { mode: "exclusive", ifAvailable: true }, async (lock) => { db = await loadDatabase(store); state = await readAccount(db, session.accountId, Boolean(lock)); if (!lock) { remote = true; throw new Error("另一标签正在同步或领取,当前页面只显示缓存。"); } remote = false; for (const a of Object.values(db.accounts)) if (a.run === "running") a.run = "paused"; assertAccount(session.accountId); try { await action(); } catch (error) { state = db.accounts[session.accountId] ?? state; state.run = "paused"; state.message = controller?.signal.aborted ? "同步已取消,原清单缓存已保留。" : error instanceof Error ? error.message : "操作失败,请稍后重试。"; if (error instanceof MetadataRateLimit) state.cooldownUntil = Date.now() + 5 * 6e4; await persist(); throw error; } await persist(); }); } finally { busy = false; activity = void 0; progress = void 0; controller = void 0; runner = void 0; notice = ""; render(); } }; async function countryForSync(signal) { let country = readStoreCountry(document, document.cookie); if (!country) { const response = await fetch("https://store.steampowered.com/?l=english", { credentials: "same-origin", signal }); if (!response.ok) throw new Error("无法读取商店地区,请刷新 Steam 商店后重试。"); const doc = new DOMParser().parseFromString(await response.text(), "text/html"); if (accountIdentity(doc)?.accountId !== state?.accountId) throw new Error("Steam 登录已变化,请刷新后同步。"); country = readStoreCountry(doc, document.cookie); } if (!country) throw new Error("无法确认商店地区,请打开 Steam 商店首页后重试。"); return country; } async function syncWork() { if (!state) return; const id = state.accountId; controller = new AbortController(); const signal = controller.signal; state.run = "running"; state.message = db.catalog ? "正在读取指南并同步游戏信息…" : "首次初始化:正在读取 Steam 指南清单…"; progress = { done: 0, total: 1 }; await persist(); const country = await countryForSync(signal), reader = new PackageReader(country, signal); const result = await synchronizeCatalog(db.catalog, country, { guide: () => fetchGuide(signal), details: (id2) => reader.read(id2), signal, progress: (done, total) => { progress = { done, total }; state.message = `正在缓存游戏信息 ${done}/${total}…`; render(); }, wait: async () => { signal.throwIfAborted(); await new Promise((resolve) => setTimeout(resolve, 150)); } }); signal.throwIfAborted(); assertAccount(id); await commitCatalog(db, result.catalog, store, signal); state = db.accounts[id]; state.run = "idle"; const snapshot = parseLicenses(document, id); if (snapshot.readable) applyVerification(state, snapshot); state.message = result.first ? `首次缓存完成:${result.catalog.entries.length} 个包。` : `同步完成:新增 ${result.added} 项,删除 ${result.removed} 项。`; if (result.errors) state.message += ` ${result.errors} 项信息未完整,已保留并标记,可稍后手动同步重试。`; else state.message += " 后续打开直接读缓存;领取请点击“一键入库”。"; progress = void 0; } const sync = () => operate("sync", syncWork); const claim = (mode) => operate("claim", async () => { if (!state || !db.catalog) throw new Error("请先完成指南同步。"); if (state.cooldownUntil > Date.now()) throw new Error("冷却尚未结束,请稍后继续。"); reconcileAccount(state, db.catalog); for (const item of state.items) item.selected = eligibleItem(item) && (mode === "all" || mode === "selected" && item.selected || mode === item.subId); if (!state.items.some((i) => i.selected)) { state.message = "没有可以领取的项目;信息缺失项可手动同步重试。"; return; } const s = state; runner = new QueueRunner(s, { assertAccount: () => assertAccount(s.accountId), verify: () => fetchLicenses(s.accountId), claim: async (subId) => { const owned = await fetchLicenses(s.accountId); if (!owned.readable) throw new Error("许可证页不可读,已暂停领取。"); if (owned.owned.has(subId)) return { kind: "owned", message: "提交前检查确认已拥有此包" }; if (!db.catalog?.entries.some((i) => i.subId === subId && i.infoStatus === "ready")) throw new Error("此包已不在当前可领取清单中。"); if (runner?.getControl() !== "run") return { kind: "unknown", message: "已取消,此包尚未提交领取。" }; const session = readSession(document, document.cookie); assertAccount(s.accountId); return claimFreeLicense(subId, session); }, save: async () => persist(), sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now: Date.now, interval: () => 3e3 + Math.floor(Math.random() * 2001) }); await runner.run(); }); function stop() { controller?.abort(); runner?.stop(); if (busy) { notice = activity === "sync" ? "正在取消同步,原缓存将保留…" : "已请求停止;当前请求结束后完成核验。"; render(); } } function createPanel() { panel = new Panel(document, { sync, check: () => operate("check", async () => { if (!state) return; let snapshot; try { snapshot = await fetchLicenses(state.accountId); } catch (error) { const message = error instanceof Error ? error.message : "核验请求失败,请稍后重试。"; for (const item of state.items) if (["pending", "unknown"].includes(item.status)) item.message = message; throw error; } const confirmed = applyVerification(state, snapshot); const pending = state.items.filter((i) => ["pending", "unknown"].includes(i.status)).length; state.message = `许可证核验完成:识别 ${snapshot.owned.size} 个包,本次确认 ${confirmed} 项,仍待确认 ${pending} 项。${snapshot.warning ?? ""}`; }), claimAll: () => claim("all"), claimSelected: () => claim("selected"), claimOne: (id) => claim(id), select: (ids, value) => operate("check", async () => { for (const item of state?.items ?? []) if (ids.includes(item.subId) && eligibleItem(item)) item.selected = value; }), markRead: () => operate("check", async () => { markCatalogRead(db); if (state) { state = db.accounts[state.accountId]; state.message = "已清除 NEW 标识。"; } }), stop, close: stop, exportResults: () => { const result = { exportedAt: (/* @__PURE__ */ new Date()).toISOString(), catalog: db.catalog, account: state }; const url = URL.createObjectURL(new Blob([JSON.stringify(result, null, 2)], { type: "application/json" })); const a = document.createElement("a"); a.href = url; a.download = `steam-guide-library-${Date.now()}.json`; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1e3); } }); } async function openPanel() { if (!isLicensePage(new URL(location.href))) { location.assign(PANEL_URL); return; } if (!panel) createPanel(); panel.open(); if (busy) { render(); return; } try { await listen(); await operate("check", async () => { if (!state) return; if (!db.catalog) { activity = "sync"; await syncWork(); } else { const needsVerification = state.items.some((i) => ["pending", "unknown"].includes(i.status)); const snapshot = needsVerification ? await fetchLicenses(state.accountId) : parseLicenses(document, state.accountId); if (snapshot.readable) applyVerification(state, snapshot); if (state.run !== "paused") state.message = `已加载 ${db.catalog.entries.length} 个缓存包;仅“手动同步”会更新指南和游戏信息。`; } }); } catch (error) { notice = controller?.signal.aborted ? "同步已取消,原清单缓存已保留。" : error instanceof Error ? error.message : "无法打开免费入库,请检查脚本权限后刷新。"; } render(); } watchMenus(document, () => { void openPanel(); }); window.addEventListener("hashchange", () => { if (location.hash === "#steam-free-library") void openPanel(); }); void Promise.resolve().then(() => GM.registerMenuCommand("打开免费入库", () => { void openPanel(); })).catch(() => { console.warn("[免费入库] 扩展菜单注册失败,仍可使用商店导航入口。"); }); if (isLicensePage(new URL(location.href)) && location.hash === "#steam-free-library") await openPanel(); } void boot().catch(() => console.error("[免费入库] 初始化失败,请检查脚本管理器的站点权限后刷新。")); })();