`;
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("[免费入库] 初始化失败,请检查脚本管理器的站点权限后刷新。"));
})();