// ==UserScript==
// @name BetterSearch
// @namespace bettersearch
// @version 0.1.0
// @description Cleaner, safer search results for Google, Bing and Baidu: no ads, site blocking, lookalike warnings, auto-paging and a card layout.
// @description:zh-CN 让 Google、Bing、百度的搜索结果更干净、更安全:去广告、屏蔽网站、提示仿冒官网、自动翻页、多列卡片布局。
// @homepageURL https://github.com/ONTHEREIN/BetterSearch
// @supportURL https://github.com/ONTHEREIN/BetterSearch/issues
// @match https://www.google.com/search*
// @match https://www.google.com.hk/search*
// @match https://www.google.co.jp/search*
// @match https://www.bing.com/search*
// @match https://cn.bing.com/search*
// @match https://www.bing.com/news/search*
// @match https://www.baidu.com/
// @match https://www.baidu.com/s*
// @match https://m.baidu.com/s*
// @match https://m.baidu.com/*/s*
// @connect *
// @grant GM_addValueChangeListener
// @grant GM_getValue
// @grant GM_registerMenuCommand
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @run-at document-start
// @license GPL-3.0
// ==/UserScript==
(function() {
"use strict";
var HOSTNAME = /(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}/i;
function hostFromDisplayUrl(text) {
if (!text) return null;
const match = text.replace(/^\s*https?:\/\//i, "").match(HOSTNAME);
return match ? match[0].toLowerCase() : null;
}
function stripWww(host) {
return host.startsWith("www.") ? host.slice(4) : host;
}
var SUFFIXES = new Set([
"com.cn",
"net.cn",
"org.cn",
"gov.cn",
"edu.cn",
"ac.cn",
"com.hk",
"org.hk",
"com.tw",
"org.tw",
"com.sg",
"com.my",
"co.jp",
"ne.jp",
"or.jp",
"ac.jp",
"co.kr",
"or.kr",
"co.uk",
"org.uk",
"ac.uk",
"com.au",
"net.au",
"org.au",
"co.nz",
"co.in",
"com.br",
"com.mx",
"co.za",
"github.io",
"gitee.io",
"gitlab.io",
"blogspot.com",
"wordpress.com",
"vercel.app",
"netlify.app",
"pages.dev",
"workers.dev",
"web.app",
"firebaseapp.com",
"herokuapp.com",
"notion.site"
]);
var PORTALS = new Set([
"baidu.com",
"qq.com",
"tencent.com",
"google.com",
"google.cn",
"microsoft.com",
"apple.com",
"sina.com.cn",
"sina.cn",
"sohu.com",
"163.com",
"aliyun.com",
"alibaba.com"
]);
function registrableDomain(host) {
const labels = host.toLowerCase().split(".");
if (labels.length <= 2) return labels.join(".");
const lastTwo = labels.slice(-2).join(".");
return SUFFIXES.has(lastTwo) ? labels.slice(-3).join(".") : lastTwo;
}
function siteOf(host) {
const domain = registrableDomain(host);
return PORTALS.has(domain) ? stripWww(host.toLowerCase()) : domain;
}
var HOST$2 = /^(www|m)\.baidu\.com$/;
var TEMPLATES = {
www_index: "organic",
www_struct: "organic",
wenda_generate: "ai-answer",
ai_agent_distribute: "ai-answer",
new_baikan_index: "ai-answer",
recommend_list: "related",
recommend_list_san: "related",
rel_base_realtime: "news",
"news-normal": "organic",
sg_kg_entity_san: "knowledge",
bk_polysemy: "knowledge",
short_video: "video",
yl_vd_main_san: "video",
yl_vd_series_san: "video",
yl_vd_plot_intro_san: "video",
weather_forecast_new_san: "widget",
jr_exrate_san: "widget",
jr_quote: "widget",
jr_stock_comment_san: "widget",
sp_purc_pc: "widget",
"pc-soft-accurate": "widget",
image_grid_san: "widget",
sp_purc_atom: "ad",
guanfanghao_san: "unknown"
};
var AD_LINK = "a[href*=\"baidu.php?\"]";
var MOBILE_AD = ".ec_wise_ad";
var BRAND_AD = ".ecom_pingzhuan";
var NEWS_PAGE = "#page a[href*=\"tn=news&\"], #content_left > [tpl=\"news-normal\"]";
function classify(el) {
const tpl = el.getAttribute("tpl");
if (!tpl) {
if (el.matches(BRAND_AD) || el.querySelector(`${AD_LINK}, ${MOBILE_AD}`)) return "ad";
return el.matches(".result") && el.querySelector("h3 a") ? "organic" : "unknown";
}
if (tpl.startsWith("ads_")) return "ad";
return TEMPLATES[tpl] ?? "unknown";
}
function loggedMu(el) {
try {
const mu = JSON.parse(el.dataset.log ?? "").mu;
return typeof mu === "string" ? mu : null;
} catch {
return null;
}
}
function realUrl(el) {
const mu = el.getAttribute("mu") ?? loggedMu(el);
if (!mu || !/^https?:\/\//.test(mu)) return null;
try {
const url = new URL(mu);
return url.hostname === "nourl.ubs.baidu.com" ? null : url;
} catch {
return null;
}
}
function directUrl(href) {
if (!href || !/^https?:\/\//.test(href)) return null;
try {
const url = new URL(href);
return HOST$2.test(url.hostname) ? null : url;
} catch {
return null;
}
}
function badgedOfficial(el) {
return [...el.querySelectorAll("span, a, div")].some((e) => e.children.length === 0 && e.textContent?.trim() === "官方");
}
function mobileResult(el) {
const card = el.querySelector("[rl-link-href]");
const heading = el.querySelector("h3");
if (!card || !heading) return null;
const title = heading.cloneNode(true);
for (const tag of title.querySelectorAll(".cos-tag")) tag.remove();
const url = realUrl(el);
return {
title: title.textContent?.trim() ?? "",
href: card.getAttribute("rl-link-href") ?? "",
url: url?.href ?? null,
host: url?.hostname ?? null,
prominent: badgedOfficial(el)
};
}
var baiduAdapter = {
id: "baidu",
adSelectors: [
"#top-ad",
`#content_left > ${BRAND_AD}`,
`#content_left > div:not([tpl]):has(${AD_LINK})`,
`#results > div:not([tpl]):has(${MOBILE_AD})`,
"#results > [tpl^=\"ads_\"]",
"#results > [tpl=\"sp_purc_atom\"]"
],
ownsHost(hostname) {
return HOST$2.test(hostname);
},
resultsContainer(root) {
return root.querySelector("#content_left, #results");
},
sideColumn(root) {
return root.querySelector("#content_right");
},
leftColumn(root) {
return null;
},
injectedModules: "",
paginationSelector: "#page:not(.search-page), #page-controller",
nextPageUrl(root, base) {
const href = ([...root.querySelectorAll("#page a.n")].at(-1) ?? root.querySelector("#page-controller a[class*=\"nextpage\"]"))?.getAttribute("href");
return href ? new URL(href, base).href : null;
},
searchBar(root) {
return root.querySelector(".chat-input-wrapper") ?? root.querySelector("#kw")?.closest("form") ?? null;
},
query(url) {
return url.searchParams.get("wd") ?? url.searchParams.get("word") ?? "";
},
tab(url, root) {
if (!HOST$2.test(url.hostname) || !/(^|\/)s$/.test(url.pathname) || url.searchParams.has("pd")) return null;
return url.searchParams.get("tn") === "news" || root.querySelector(NEWS_PAGE) ? "news" : "web";
},
collectBlocks(root) {
const blocks = [];
const brand = root.querySelector("#top-ad");
if (brand?.textContent?.trim()) blocks.push({
el: brand,
type: "ad"
});
for (const el of root.querySelectorAll("#content_left > *, #content_right [tpl], #results > *")) if (el.textContent?.trim()) blocks.push({
el,
type: classify(el)
});
return blocks;
},
extractResult(block) {
if (block.type !== "organic") return null;
const link = block.el.querySelector("h3 a");
if (!link) return mobileResult(block.el);
const url = realUrl(block.el) ?? directUrl(link.getAttribute("href"));
const host = url?.hostname ?? hostFromDisplayUrl(block.el.querySelector("[class*=\"showurl\"]")?.textContent);
const prominent = badgedOfficial(block.el);
return {
title: link.textContent?.trim() ?? "",
href: link.getAttribute("href") ?? "",
url: url?.href ?? null,
host,
prominent
};
}
};
var HOST$1 = /^(www|cn)\.bing\.com$/;
var ANSWERS = [
["ai-answer", ".cht_ans_root"],
["news", ".ans_nws"],
["paa", ".b_paa_item, #df_listaa"],
["related", "#inline_rs, .b_rs, .rslist, .richrswrapper"],
["video", "#serpvidans, .b_vidAns"]
];
function classifyAnswer(el) {
if (el.matches(".b_vidAns")) return "video";
for (const [type, selector] of ANSWERS) if (el.querySelector(selector)) return type;
return "unknown";
}
var NEWS_CARD = "#algocore > .news-card";
function hasText(el) {
return !!el?.textContent?.trim();
}
function byDocumentOrder$1(a, b) {
return a.el.compareDocumentPosition(b.el) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
}
var bingAdapter = {
id: "bing",
adSelectors: [
".b_bza_pole_wrapper",
"#b_results > li.b_ad",
".b_adTop",
".b_adBottom",
"#b_pole:has(.eu_promotedlabel)"
],
ownsHost(hostname) {
return HOST$1.test(hostname);
},
resultsContainer(root) {
return root.querySelector("#b_results, #algocore");
},
sideColumn(root) {
return root.querySelector("#b_context");
},
leftColumn(root) {
return root.querySelector(".news-side-nav");
},
injectedModules: "#b_results > li.b_algo > .b_inline_ajax_rs",
paginationSelector: "#b_results > li.b_pag",
nextPageUrl(root, base) {
const href = root.querySelector("a.sb_pagN")?.getAttribute("href");
return href ? new URL(href, base).href : null;
},
searchBar(root) {
return root.querySelector("#sb_form_q")?.closest("form") ?? null;
},
query(url) {
return url.searchParams.get("q") ?? "";
},
tab(url) {
if (!HOST$1.test(url.hostname)) return null;
return url.pathname === "/search" ? "web" : url.pathname === "/news/search" ? "news" : null;
},
collectBlocks(root) {
const blocks = [];
const brand = root.querySelector(".b_bza_pole_wrapper");
if (hasText(brand)) blocks.push({
el: brand,
type: "ad"
});
const pole = root.querySelector("#b_pole");
if (hasText(pole)) blocks.push({
el: pole,
type: pole.querySelector(".eu_promotedlabel") ? "ad" : "knowledge"
});
const top = root.querySelector("#b_topw");
if (hasText(top)) blocks.push({
el: top,
type: "knowledge"
});
for (const el of root.querySelectorAll("#b_results > li")) {
if (!hasText(el)) continue;
if (el.matches(".b_ad, .b_adTop, .b_adBottom")) blocks.push({
el,
type: "ad"
});
else if (el.matches(".b_algo")) blocks.push({
el,
type: "organic"
});
else if (el.matches(".b_ans")) blocks.push({
el,
type: classifyAnswer(el)
});
}
for (const el of root.querySelectorAll(NEWS_CARD)) if (hasText(el)) blocks.push({
el,
type: "organic"
});
for (const el of root.querySelectorAll("#b_context > *")) if (hasText(el)) blocks.push({
el,
type: el.matches(".b_ans") ? classifyAnswer(el) : "unknown"
});
return blocks.sort(byDocumentOrder$1);
},
extractResult(block) {
if (block.type !== "organic") return null;
if (block.el.matches(NEWS_CARD)) {
const link = block.el.querySelector("a.title");
const url = block.el.dataset.url ?? "";
if (!link || !/^https?:\/\//.test(url)) return null;
return {
title: link.textContent?.trim() ?? "",
href: link.getAttribute("href") ?? "",
url,
host: new URL(url).hostname,
prominent: false
};
}
const link = block.el.querySelector("h2 a") ?? block.el.querySelector("a h2")?.closest("a");
if (!link) return null;
const href = link.getAttribute("href") ?? "";
const url = /^https?:\/\//.test(href) && !/^https?:\/\/[^/]*bing\.com\//.test(href) ? href : null;
const host = hostFromDisplayUrl(block.el.querySelector("cite")?.textContent) ?? (url ? new URL(url).hostname : null);
const prominent = block.el.matches(".b_vtl_deeplinks") || !!block.el.querySelector(".b_deep, .b_vlist2col");
return {
title: link.textContent?.trim() ?? "",
href,
url,
host,
prominent
};
}
};
var HOST = /(^|\.)google\.(com|co\.[a-z]{2}|com\.[a-z]{2}|[a-z]{2})$/;
var UNIT = ".ULSxyf, .MjjYud";
var RESULT = [
"[data-rpos]",
".MjjYud",
"[data-hveid]"
];
var AI_ANSWER = "#m-x-content, [data-subtree=\"aimc\"]";
var MODULES = [
["ad", "#tads, #tadsb, #bottomads, #tvcap, [data-text-ad]"],
["ai-answer", AI_ANSWER],
["paa", ".related-question-pair, [data-initq]"],
["knowledge", "[data-attrid^=\"kc:\"]"],
["widget", "[data-attrid=\"Converter\"], #wob_wc"]
];
var TITLE = "a h3, a [role=\"heading\"][aria-level=\"3\"]";
var NEWS_ITEM = "[data-news-doc-id]";
var VIDEO_CAROUSEL_MIN = 2;
function outermostUnit(el, scope) {
let unit = null;
for (let e = el.parentElement; e && e !== scope; e = e.parentElement) if (e.matches(UNIT)) unit = e;
return el.matches(UNIT) && !unit ? el : unit;
}
function resultContainer(title, scope) {
for (const selector of RESULT) {
const el = title.closest(selector);
if (el && el !== scope && scope.contains(el)) return el;
}
return null;
}
function collectMain(scope) {
const modules = new Map();
for (const [type, selector] of MODULES) for (const marker of scope.querySelectorAll(selector)) {
if (!marker.textContent?.trim()) continue;
const unit = outermostUnit(marker, scope) ?? marker;
if (!modules.has(unit)) modules.set(unit, type);
}
const videoCounts = new Map();
for (const marker of scope.querySelectorAll("[data-vid]")) {
const unit = outermostUnit(marker, scope);
if (unit && !modules.has(unit)) videoCounts.set(unit, (videoCounts.get(unit) ?? 0) + 1);
}
for (const [unit, count] of videoCounts) if (count >= VIDEO_CAROUSEL_MIN) modules.set(unit, "video");
const inModule = (el) => [...modules.keys()].some((m) => m.contains(el));
const blocks = [...modules].map(([el, type]) => ({
el,
type
}));
const organic = new Set();
for (const title of scope.querySelectorAll(TITLE)) {
if (inModule(title) || title.closest(NEWS_ITEM)) continue;
const el = resultContainer(title, scope);
if (el && !organic.has(el)) {
organic.add(el);
blocks.push({
el,
type: "organic"
});
}
}
for (const el of scope.querySelectorAll(NEWS_ITEM)) if (!inModule(el) && !organic.has(el)) {
organic.add(el);
blocks.push({
el,
type: "organic"
});
}
for (const unit of scope.querySelectorAll(UNIT)) {
if (outermostUnit(unit, scope) !== unit || modules.has(unit)) continue;
if (!unit.textContent?.trim()) continue;
if ([...organic].some((o) => unit.contains(o) || o.contains(unit))) continue;
blocks.push({
el: unit,
type: "unknown"
});
}
return blocks;
}
function byDocumentOrder(a, b) {
return a.el.compareDocumentPosition(b.el) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
}
var googleAdapter = {
id: "google",
adSelectors: [
"#tads",
"#tadsb",
"#tvcap",
"#bottomads"
],
ownsHost(hostname) {
return HOST.test(hostname);
},
resultsContainer(root) {
return root.querySelector("#rso");
},
sideColumn(root) {
return root.querySelector("#rhs");
},
leftColumn(root) {
return null;
},
injectedModules: "",
paginationSelector: "#botstuff [role=\"navigation\"], #foot",
nextPageUrl(root, base) {
const href = root.querySelector("#pnnext")?.getAttribute("href");
return href ? new URL(href, base).href : null;
},
searchBar(root) {
return root.querySelector("textarea[name=\"q\"], input[name=\"q\"]")?.closest("form") ?? null;
},
query(url) {
return url.searchParams.get("q") ?? "";
},
tab(url) {
if (!HOST.test(url.hostname) || url.pathname !== "/search") return null;
const tbm = url.searchParams.get("tbm");
if (tbm !== null) return tbm === "nws" ? "news" : null;
const udm = url.searchParams.get("udm");
return udm === null || udm === "14" ? "web" : null;
},
collectBlocks(root) {
const blocks = [];
const top = root.querySelector("#Odp5De");
if (top?.querySelector(AI_ANSWER)) blocks.push({
el: top,
type: "ai-answer"
});
const scope = root.querySelector("#rso");
if (scope) blocks.push(...collectMain(scope));
const side = root.querySelector("#rhs");
if (side?.textContent?.trim()) blocks.push({
el: side,
type: "knowledge"
});
const related = root.querySelector("#bres");
if (related?.textContent?.trim()) blocks.push({
el: related,
type: "related"
});
return blocks.sort(byDocumentOrder);
},
extractResult(block) {
if (block.type !== "organic") return null;
if (block.el.matches(NEWS_ITEM)) {
const link = block.el.querySelector("a[href]");
const title = block.el.querySelector("[role=\"heading\"]");
if (!link || !title) return null;
return {
title: title.textContent?.trim() ?? "",
href: link.getAttribute("href") ?? "",
url: null,
host: null,
prominent: false
};
}
const title = block.el.querySelector(TITLE);
const link = title?.closest("a");
if (!title || !link) return null;
const href = link.getAttribute("href") ?? "";
const url = /^https?:\/\//.test(href) ? href : null;
return {
title: title.textContent?.trim() ?? "",
href,
url,
host: hostFromDisplayUrl(block.el.querySelector("cite")?.textContent) ?? (url ? new URL(url).hostname : null),
prominent: block.el.querySelectorAll("table a, [role=\"list\"] a").length >= 3
};
}
};
var AI_PROVIDERS = [
{
id: "deepseek",
name: "DeepSeek",
baseUrl: "https://api.deepseek.com/v1",
model: "deepseek-chat",
keyUrl: "https://platform.deepseek.com/api_keys"
},
{
id: "qwen",
name: "通义千问",
baseUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1",
model: "qwen-plus",
keyUrl: "https://bailian.console.aliyun.com/?apiKey=1"
},
{
id: "kimi",
name: "Kimi",
baseUrl: "https://api.moonshot.cn/v1",
model: "moonshot-v1-8k",
keyUrl: "https://platform.moonshot.cn/console/api-keys"
},
{
id: "zhipu",
name: "智谱",
baseUrl: "https://open.bigmodel.cn/api/paas/v4",
model: "glm-4-flash",
keyUrl: "https://open.bigmodel.cn/usercenter/apikeys"
},
{
id: "openai",
name: "OpenAI",
baseUrl: "https://api.openai.com/v1",
model: "gpt-4o-mini",
keyUrl: "https://platform.openai.com/api-keys"
},
{
id: "claude",
name: "Claude",
baseUrl: "https://api.anthropic.com/v1",
model: "claude-sonnet-5-5",
keyUrl: "https://console.anthropic.com/settings/keys"
},
{
id: "gemini",
name: "Gemini",
baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",
model: "gemini-2.5-flash",
keyUrl: "https://aistudio.google.com/apikey"
},
{
id: "custom",
name: "",
baseUrl: "",
model: "",
keyUrl: ""
}
];
function aiReady(config) {
return !!config.baseUrl.trim() && !!config.model.trim() && (!!config.apiKey.trim() || config.provider === "custom");
}
function endpoint(baseUrl, path) {
return `${baseUrl.trim().replace(/\/+$/, "")}/${path}`;
}
function authHeaders(config) {
const key = config.apiKey.trim();
return key ? { Authorization: `Bearer ${key}` } : {};
}
function chatRequest(config, messages) {
return {
method: "POST",
url: endpoint(config.baseUrl, "chat/completions"),
headers: {
"Content-Type": "application/json",
Accept: "text/event-stream",
...authHeaders(config)
},
body: JSON.stringify({
model: config.model.trim(),
messages,
stream: true
})
};
}
function modelsRequest(config) {
return {
method: "GET",
url: endpoint(config.baseUrl, "models"),
headers: authHeaders(config)
};
}
function parseModels(body) {
try {
return (JSON.parse(body).data ?? []).map((m) => m.id).filter((id) => typeof id === "string").sort();
} catch {
return [];
}
}
function errorMessage(body) {
try {
const data = JSON.parse(body);
const message = typeof data.error === "string" ? data.error : data.error?.message ?? data.message;
return typeof message === "string" && message ? message : null;
} catch {
return null;
}
}
var ChatStream = class {
read = 0;
partial = "";
streamed = false;
push(received) {
const chunk = received.slice(this.read);
this.read = received.length;
const lines = (this.partial + chunk).split("\n");
this.partial = lines.pop();
return lines.map((line) => this.line(line)).join("");
}
finish(received) {
let text = this.push(received) + this.line(this.partial);
this.partial = "";
if (!this.streamed) try {
const content = JSON.parse(received).choices?.[0]?.message?.content;
if (typeof content === "string") text += content;
} catch {}
return text;
}
line(line) {
const match = /^data:\s?(.*)$/.exec(line.trim());
if (!match || match[1] === "[DONE]") return "";
this.streamed = true;
try {
const content = JSON.parse(match[1]).choices?.[0]?.delta?.content;
return typeof content === "string" ? content : "";
} catch {
return "";
}
}
};
var SNIPPET_CHARS = 300;
var PAGE_CHARS = 12e3;
var ANSWER_STYLE = "Answer in the language of the question. Be concise: a short paragraph, then a few bullet points if they help. Use plain Markdown (paragraphs, \"- \" bullets, **bold**); no headings, tables or code unless asked.";
function clip(text, max) {
return text.length > max ? `${text.slice(0, max)}…` : text;
}
function searchPrompt(query, sources) {
const list = sources.map((s, i) => `[${i + 1}] ${s.title}\n${s.url}\n${clip(s.snippet, SNIPPET_CHARS)}`).join("\n\n");
return [{
role: "system",
content: "You summarise web search results for the user. Use only the numbered results below; when they do not answer the question, say so. Cite results as [n] after the sentence that uses them. " + ANSWER_STYLE
}, {
role: "user",
content: `Search: ${query}\n\nResults:\n\n${list}`
}];
}
function pagePrompt(query, page) {
return [{
role: "system",
content: "You summarise a web page for someone who found it by searching. Say what the page offers, what it says about the search, and anything that makes it less trustworthy. " + ANSWER_STYLE
}, {
role: "user",
content: `Search: ${query}\n\nPage: ${page.title}\n${page.url}\n\n${clip(page.text, PAGE_CHARS)}`
}];
}
function htmlCharset(bytes, contentType) {
const fromHeader = /charset=["']?([\w-]+)/i.exec(contentType ?? "")?.[1];
if (fromHeader) return fromHeader.toLowerCase();
const head = String.fromCharCode(...bytes.subarray(0, 2048));
return /]+charset=["']?([\w-]+)/i.exec(head)?.[1]?.toLowerCase() ?? "utf-8";
}
function decodeHtml(bytes, contentType) {
try {
return new TextDecoder(htmlCharset(bytes, contentType)).decode(bytes);
} catch {
return new TextDecoder().decode(bytes);
}
}
var NOT_CONTENT = "script, style, noscript, template, svg, iframe, form, nav, header, footer, aside, [hidden], [aria-hidden=\"true\"]";
var BLOCKS = "p, div, li, h1, h2, h3, h4, h5, h6, br, tr, section, article, pre, blockquote, dd, dt";
function extractPageText(doc, max = PAGE_CHARS) {
const title = (doc.querySelector("meta[property=\"og:title\"]")?.getAttribute("content") ?? doc.title ?? "").trim();
for (const el of doc.querySelectorAll(NOT_CONTENT)) el.remove();
const root = [...doc.querySelectorAll("article")].sort((a, b) => (b.textContent?.length ?? 0) - (a.textContent?.length ?? 0))[0] ?? doc.querySelector("main, [role=\"main\"]") ?? doc.body;
if (!root) return {
title,
text: ""
};
for (const el of root.querySelectorAll(BLOCKS)) el.after(doc.createTextNode("\n"));
return {
title,
text: (root.textContent ?? "").split("\n").map((line) => line.replace(/\s+/g, " ").trim()).filter(Boolean).join("\n").slice(0, max)
};
}
function inlines(text) {
const out = [];
const pattern = /\*\*(.+?)\*\*|\[(\d+(?:\s*[,,]\s*\d+)*)\]/g;
let last = 0;
for (const match of text.matchAll(pattern)) {
if (match.index > last) out.push({ text: text.slice(last, match.index) });
if (match[1] !== void 0) out.push({
text: match[1],
bold: true
});
else for (const n of match[2].split(/[,,]/)) out.push({ cite: Number(n.trim()) });
last = match.index + match[0].length;
}
if (last < text.length) out.push({ text: text.slice(last) });
return out;
}
function parseAnswer(text) {
const blocks = [];
let paragraph = [];
const flush = () => {
if (paragraph.length) blocks.push({
type: "p",
content: inlines(paragraph.join(" "))
});
paragraph = [];
};
for (const raw of text.split("\n")) {
const line = raw.trim();
const item = /^(?:[-*•]|\d+[.)])\s+(.*)$/.exec(line);
if (!line) flush();
else if (item) {
flush();
blocks.push({
type: "li",
content: inlines(item[1])
});
} else {
const heading = /^#{1,6}\s+(.*)$/.exec(line);
if (heading) {
flush();
blocks.push({
type: "p",
content: [{
text: heading[1],
bold: true
}]
});
} else paragraph.push(line);
}
}
flush();
return blocks;
}
function planGrid(container, blocks) {
const inside = blocks.filter((b) => b.el !== container && container.contains(b.el));
const cells = new Map();
const wrappers = new Set();
const holdsOther = (el, self) => inside.some((b) => b !== self && el.contains(b.el));
for (const block of inside) {
let cell = block.el;
let parent = cell.parentElement;
while (parent && parent !== container && !holdsOther(parent, block)) {
cell = parent;
parent = cell.parentElement;
}
cells.set(block.el, cell);
for (let w = cell.parentElement; w && w !== container; w = w.parentElement) wrappers.add(w);
}
return {
cells,
wrappers
};
}
function autoColumns(width) {
if (width >= 1320) return 3;
if (width >= 880) return 2;
return 1;
}
var MAX_WIDTH_FOR_COLUMNS = [
0,
760,
1200,
1400
];
function gridSize(setting, room, original) {
const max = setting === "auto" ? 3 : Number(setting);
const columns = Math.max(1, Math.min(max, autoColumns(room)));
return {
columns,
width: Math.round(Math.max(original, Math.min(room, MAX_WIDTH_FOR_COLUMNS[columns])))
};
}
var TRACKING = [
/^utm_/,
/^spm(_id_from)?$/,
/^(gclid|fbclid|msclkid|yclid|dclid)$/,
/^mc_(cid|eid)$/
];
function stripTracking(url) {
let parsed;
try {
parsed = new URL(url);
} catch {
return url;
}
const drop = [...parsed.searchParams.keys()].filter((key) => TRACKING.some((re) => re.test(key)));
if (!drop.length) return url;
for (const key of drop) parsed.searchParams.delete(key);
return parsed.href;
}
var MESSAGES = {
zh: {
"block.button": "屏蔽 {site}",
"block.toast": "已屏蔽 {site}",
"block.undo": "撤销",
"report.button": "举报 {site} 是仿冒网站",
"report.link": "举报仿冒",
"blocked.notice": "隐藏了 {count} 条来自 {sites} 的结果,这些是你屏蔽的网站。",
"blocked.show": "显示",
"blocked.separator": "、",
"ai.collapsed": "已折叠搜索引擎生成的 AI 回答。",
"ai.expand": "展开",
"assistant.label": "AI 总结",
"assistant.summarize": "总结搜索结果",
"assistant.again": "重新总结",
"assistant.clear": "清除",
"assistant.stop": "停止",
"assistant.settings": "设置",
"assistant.privacy": "点按钮时,搜索词和结果摘要会从你的浏览器直接发给这个模型的服务商",
"assistant.searchTitle": "总结这一页搜索结果(已排除屏蔽的网站)",
"assistant.pageTitle": "总结 {site} 的这个网页",
"assistant.readingPage": "正在读取 {site} 的网页…",
"assistant.pageFallback": "没能读到 {site} 的正文({error}),下面只根据搜索结果里的摘要总结。",
"assistant.noText": "网页上几乎没有文字,可能需要登录",
"assistant.noSources": "这一页没有可以总结的结果。",
"assistant.thinking": "正在生成…",
"assistant.stopped": "已停止。",
"assistant.error": "请求失败:{error}",
"assistant.ask": "继续提问",
"assistant.askPlaceholder": "继续提问…",
"assistant.send": "发送",
"assistant.summaryButton": "用 AI 总结这个网页",
"sync.title": "同步(WebDAV)",
"sync.enable": "用 WebDAV 在多台设备间同步",
"sync.hint": "同步设置、屏蔽规则和订阅地址;AI 的 API Key 和这里的密码不同步。数据存在你的 WebDAV 里的 BetterSearch 文件夹,保留最近 10 个旧版本。打开搜索页时同步(至少隔 10 分钟),改设置后几秒内上传。第一次在一台设备上同步时,云端已有的设置优先。",
"sync.url": "WebDAV 地址",
"sync.username": "用户名",
"sync.password": "密码",
"sync.passwordHint": "请用应用专用密码,不要用登录密码。坚果云:账户信息 → 安全选项 → 第三方应用管理 → 添加应用。",
"sync.now": "立即同步",
"sync.running": "正在同步…",
"sync.last": "上次同步:{when}",
"sync.never": "还没同步过。",
"sync.failed": "同步失败:{error}。",
"sync.auth": "用户名或密码不对",
"assistant.engineShow": "看搜索引擎的 AI 回答",
"assistant.engineHide": "收起搜索引擎的 AI 回答",
"pager.divider": "第 {page} 页",
"pager.loading": "正在加载第 {page} 页…",
"pager.loadNext": "加载下一页",
"pager.end": "没有更多结果了。",
"pager.failed": "下一页没能自动加载,可能需要完成验证。",
"pager.openNext": "打开下一页",
"lookalike.prominent": "{site} 的域名像是在 {official} 后面加了后缀,可能是仿冒的。搜索引擎把 {official} 列为这个网站本身,下载前请核对。",
"lookalike.claimsWithOfficial": "这个网站自称官网,但 {brand} 的官网可能是 {official}。{site} 的域名像是仿冒的,下载前请核对。",
"lookalike.claims": "这个网站自称官网,但 {site} 的域名像是在 {brand} 后面加了后缀,可能是仿冒的。下载前请核对。",
"lookalike.unknown": "标题说是 {brand} 官方,但 {site} 不在 Wikidata 登记的官网里,也不是常见网站。下载前请核对。",
"official.badge": "官方网站",
"official.source": "{brand} 的官网,来自 Wikidata 登记",
"menu.settings": "BetterSearch 设置",
"gear.title": "BetterSearch 设置(Alt+,)",
"settings.title": "BetterSearch 设置",
"settings.close": "关闭设置",
"appearance.title": "外观",
"appearance.layout": "使用多列卡片布局",
"appearance.columns": "列数",
"appearance.columns1": "1 列",
"appearance.columns2": "最多 2 列",
"appearance.columns3": "最多 3 列",
"appearance.theme": "主题",
"appearance.card": "描边卡片",
"appearance.raised": "浮起卡片",
"appearance.line": "细线分隔",
"appearance.density": "密度",
"appearance.compact": "紧凑",
"appearance.comfortable": "宽松",
"appearance.collapseAi": "折叠搜索引擎自带的 AI 回答(配好 AI 后从 AI 栏展开)",
"theme.css": "自定义 CSS",
"theme.cssHint": "在所有引擎上生效。只改一个引擎时,选择器前加 html[data-bs-engine='bing'](google、bing、baidu)。",
"theme.export": "复制主题",
"theme.copied": "已复制到剪贴板",
"theme.import": "导入主题",
"theme.importPlaceholder": "粘贴别人分享的主题 JSON",
"theme.apply": "应用",
"theme.cancel": "取消",
"theme.imported": "已导入主题",
"theme.shareHint": "主题包括卡片样式、密度和自定义 CSS。",
"theme.invalid": "这不是 BetterSearch 主题。",
"theme.remote": "这个主题会从别的网站加载内容(@import 或外部 url()),可能借此把你的搜索词发出去,所以没有导入。图片请用 data: 地址内嵌。",
"theme.escape": "这个主题的 CSS 里有反斜杠转义,可能用来绕过检查,所以没有导入。",
"aiset.title": "AI",
"aiset.hint": "用你自己的 API Key,在结果上方显示 AI 总结栏。只有点按钮时才会请求:搜索词、结果摘要和要总结的网页正文从你的浏览器直接发给所选服务,不经过 BetterSearch。API Key 只保存在脚本管理器里。",
"aiset.provider": "服务",
"aiset.custom": "自定义(OpenAI 兼容接口)",
"aiset.key": "API Key",
"aiset.getKey": "去获取 API Key",
"aiset.baseUrl": "接口地址",
"aiset.model": "模型",
"aiset.listModels": "获取模型列表",
"aiset.models": "找到 {count} 个模型,可以在模型框里选。",
"aiset.modelsFailed": "没能获取模型列表:{error}",
"aiset.firstRequest": "第一次请求时,脚本管理器会请你允许访问这个服务的域名。",
"official.title": "官网核对",
"official.mark": "核对网站是否为 Wikidata 登记的官网",
"official.pin": "把官方网站排到最前面(多列布局时)",
"official.hint": "标题自称官方、却不在 Wikidata 登记的官网和常见网站里的结果会显示提示;搜索词里的品牌对上时标出官网。数据来自 Wikidata 和 Majestic Million,每周更新,按域名分片下载,只会请求所查域名所在的那一片。",
"official.proxy": "GitHub 加速前缀",
"official.proxyHint": "国内下载不了时可以填一个你信任的 GitHub 加速地址,例如 https://ghfast.top/,会最先尝试。",
"paging.title": "翻页",
"paging.auto": "滚动到底部时自动加载下一页",
"paging.limitBefore": "自动加载",
"paging.limitAfter": "页后,改为点击按钮加载",
"ads.title": "广告",
"ads.remove": "去除搜索结果中的广告",
"links.title": "链接",
"links.clean": "点击结果时直接打开目标网站,并去掉链接里的跟踪参数",
"links.googleHint": "Google 的结果链接是加密跳转,暂时只能去掉点击上报。",
"links.open": "打开方式",
"links.openEngine": "跟随搜索引擎",
"links.openNew": "总是在新标签页打开",
"links.openSame": "总是在当前页打开",
"blocking.title": "屏蔽",
"blocking.action": "被屏蔽的结果",
"blocking.collapse": "折叠成一行,可以点击显示",
"blocking.hide": "完全隐藏",
"blocking.sites": "已屏蔽的网站",
"blocking.unblock": "取消屏蔽",
"blocking.none": "还没有屏蔽任何网站。把鼠标移到搜索结果上,点右上角的图标就能屏蔽它所在的网站。",
"subs.title": "订阅列表",
"subs.failed": "更新失败:{error}",
"subs.notFetched": "尚未下载",
"subs.status": "{count} 条规则,更新于 {when}",
"subs.lastFailed": "(最近一次更新失败)",
"subs.mirrors": ",另有 {count} 个镜像",
"subs.remove": "删除",
"subs.address": "订阅地址",
"subs.placeholder": "订阅地址,多个镜像用空格分隔",
"subs.add": "添加",
"subs.refreshing": "正在更新…",
"subs.refresh": "立即更新全部订阅",
"subs.hint": "支持 uBlacklist 格式的列表,每 24 小时自动更新。第一次访问新的地址时,脚本管理器会请你确认。",
"rules.title": "屏蔽规则",
"rules.hint": "每行一条,兼容 uBlacklist 语法,例如 *://*.example.com/*、example.com 或正则 /keyword/。以 @ 开头的规则表示不屏蔽。"
},
en: {
"block.button": "Block {site}",
"block.toast": "Blocked {site}",
"block.undo": "Undo",
"report.button": "Report {site} as a lookalike",
"report.link": "Report",
"blocked.notice": "Hid {count} results from {sites}, which you blocked.",
"blocked.show": "Show",
"blocked.separator": ", ",
"ai.collapsed": "Collapsed the AI answer generated by the search engine.",
"ai.expand": "Expand",
"assistant.label": "AI summary",
"assistant.summarize": "Summarise results",
"assistant.again": "Summarise again",
"assistant.clear": "Clear",
"assistant.stop": "Stop",
"assistant.settings": "Settings",
"assistant.privacy": "When you click, your search and the result snippets go straight from your browser to this model’s provider",
"assistant.searchTitle": "Summary of these results (blocked sites left out)",
"assistant.pageTitle": "Summary of this page on {site}",
"assistant.readingPage": "Reading the page on {site}…",
"assistant.pageFallback": "Could not read the page on {site} ({error}), so this uses only the search snippet.",
"assistant.noText": "the page has almost no text; it may need a login",
"assistant.noSources": "There are no results on this page to summarise.",
"assistant.thinking": "Writing…",
"assistant.stopped": "Stopped.",
"assistant.error": "Request failed: {error}",
"assistant.ask": "Ask a follow-up",
"assistant.askPlaceholder": "Ask a follow-up…",
"assistant.send": "Send",
"assistant.summaryButton": "Summarise this page with AI",
"sync.title": "Sync (WebDAV)",
"sync.enable": "Sync between devices through WebDAV",
"sync.hint": "Syncs settings, block rules and subscription addresses; not the AI API key or the password here. The data lives in a BetterSearch folder on your WebDAV, with the last 10 versions kept. Syncs when you open a search page (at most every 10 minutes) and a few seconds after you change a setting. The first time a device syncs, the settings already synced win.",
"sync.url": "WebDAV address",
"sync.username": "Username",
"sync.password": "Password",
"sync.passwordHint": "Use an app password, not your login password.",
"sync.now": "Sync now",
"sync.running": "Syncing…",
"sync.last": "Last synced {when}",
"sync.never": "Not synced yet.",
"sync.failed": "Sync failed: {error}.",
"sync.auth": "wrong username or password",
"assistant.engineShow": "Show the search engine's AI answer",
"assistant.engineHide": "Hide the search engine's AI answer",
"pager.divider": "Page {page}",
"pager.loading": "Loading page {page}…",
"pager.loadNext": "Load next page",
"pager.end": "No more results.",
"pager.failed": "The next page did not load automatically. It may ask you to complete a check.",
"pager.openNext": "Open next page",
"lookalike.prominent": "{site} looks like {official} with a suffix added and may be an imitation. The search engine lists {official} as the site itself. Check before downloading anything.",
"lookalike.claimsWithOfficial": "This site calls itself official, but the official {brand} site is probably {official}. {site} looks like an imitation. Check before downloading anything.",
"lookalike.claims": "This site calls itself official, but {site} looks like {brand} with a suffix added and may be an imitation. Check before downloading anything.",
"lookalike.unknown": "The title says official {brand}, but {site} is neither an official website on Wikidata nor a well-known site. Check before downloading anything.",
"official.badge": "Official site",
"official.source": "Official {brand} site, as registered on Wikidata",
"menu.settings": "BetterSearch settings",
"gear.title": "BetterSearch settings (Alt+,)",
"settings.title": "BetterSearch settings",
"settings.close": "Close settings",
"appearance.title": "Appearance",
"appearance.layout": "Arrange results in cards and columns",
"appearance.columns": "Columns",
"appearance.columns1": "1 column",
"appearance.columns2": "Up to 2 columns",
"appearance.columns3": "Up to 3 columns",
"appearance.theme": "Theme",
"appearance.card": "Outlined cards",
"appearance.raised": "Raised cards",
"appearance.line": "Divider lines",
"appearance.density": "Density",
"appearance.compact": "Compact",
"appearance.comfortable": "Comfortable",
"appearance.collapseAi": "Collapse the search engine's own AI answer (opened from the AI bar once AI is set up)",
"theme.css": "Custom CSS",
"theme.cssHint": "Applies on every engine. To change one engine only, start the selector with html[data-bs-engine='bing'] (google, bing, baidu).",
"theme.export": "Copy theme",
"theme.copied": "Copied to the clipboard",
"theme.import": "Import theme",
"theme.importPlaceholder": "Paste theme JSON someone shared",
"theme.apply": "Apply",
"theme.cancel": "Cancel",
"theme.imported": "Theme imported",
"theme.shareHint": "A theme holds the card style, density and custom CSS.",
"theme.invalid": "This is not a BetterSearch theme.",
"theme.remote": "This theme loads content from other sites (@import or a remote url()), which could send your searches out, so it was not imported. Embed images as data: URLs.",
"theme.escape": "The CSS in this theme uses backslash escapes, which can hide what it loads, so it was not imported.",
"aiset.title": "AI",
"aiset.hint": "Shows an AI summary bar above the results, using your own API key. Nothing is sent until you click: your search, the result snippets and the text of a page you summarise go straight from your browser to the chosen service, never through BetterSearch. The key stays in your userscript manager.",
"aiset.provider": "Service",
"aiset.custom": "Custom (OpenAI-compatible API)",
"aiset.key": "API key",
"aiset.getKey": "Get an API key",
"aiset.baseUrl": "API base URL",
"aiset.model": "Model",
"aiset.listModels": "List models",
"aiset.models": "Found {count} models; pick one in the model field.",
"aiset.modelsFailed": "Could not list models: {error}",
"aiset.firstRequest": "On the first request, your userscript manager asks you to allow this service’s domain.",
"official.title": "Official-site check",
"official.mark": "Check sites against Wikidata's official websites",
"official.pin": "Move official sites to the top (in the card layout)",
"official.hint": "A result whose title claims to be official while its site is neither an official website on Wikidata nor well known gets a warning; when the query names a brand, its official site is marked. Data from Wikidata and the Majestic Million, updated weekly and downloaded in shards: only the shard holding a looked-up domain is requested.",
"official.proxy": "GitHub proxy prefix",
"official.proxyHint": "If downloads fail, enter a GitHub proxy you trust, e.g. https://ghfast.top/; it is tried first.",
"paging.title": "Paging",
"paging.auto": "Load the next page when scrolling to the bottom",
"paging.limitBefore": "After",
"paging.limitAfter": "pages, load more with a button",
"ads.title": "Ads",
"ads.remove": "Remove ads from search results",
"links.title": "Links",
"links.clean": "Open the destination directly and remove tracking parameters from links",
"links.googleHint": "Google result links are encrypted redirects; for now only click tracking is removed.",
"links.open": "Open links",
"links.openEngine": "As the search engine does",
"links.openNew": "Always in a new tab",
"links.openSame": "Always in the current tab",
"blocking.title": "Blocking",
"blocking.action": "Blocked results",
"blocking.collapse": "Collapse into one line that can be shown",
"blocking.hide": "Hide completely",
"blocking.sites": "Blocked sites",
"blocking.unblock": "Unblock",
"blocking.none": "No sites blocked yet. Hover over a search result and click the icon in its top-right corner to block its site.",
"subs.title": "Subscriptions",
"subs.failed": "Update failed: {error}",
"subs.notFetched": "Not downloaded yet",
"subs.status": "{count} rules, updated {when}",
"subs.lastFailed": " (last update failed)",
"subs.mirrors": ", plus {count} mirrors",
"subs.remove": "Remove",
"subs.address": "Subscription URL",
"subs.placeholder": "Subscription URL; separate mirrors with spaces",
"subs.add": "Add",
"subs.refreshing": "Updating…",
"subs.refresh": "Update all subscriptions now",
"subs.hint": "Lists in uBlacklist format, updated every 24 hours. The script manager asks you to confirm the first visit to a new address.",
"rules.title": "Block rules",
"rules.hint": "One per line, in uBlacklist syntax, e.g. *://*.example.com/*, example.com or a regular expression /keyword/. Rules starting with @ unblock."
}
};
var current$1 = "zh";
function detectLocale(languages) {
return languages[0]?.toLowerCase().startsWith("zh") ? "zh" : "en";
}
function setLocale(locale) {
current$1 = locale;
}
function t(key, vars = {}) {
return MESSAGES[current$1][key].replace(/\{(\w+)\}/g, (match, name) => name in vars ? String(vars[name]) : match);
}
var RULES_REPO = "ONTHEREIN/bettersearch-rules";
var ENGINE_OPTION = {
google: "Google",
bing: "Bing",
baidu: "百度 Baidu"
};
function reportUrl(host, query, engine) {
const site = siteOf(host);
const url = new URL(`https://github.com/${RULES_REPO}/issues/new`);
url.searchParams.set("template", "report.yml");
url.searchParams.set("title", `[举报] ${site}`);
url.searchParams.set("domain", site);
url.searchParams.set("query", query);
url.searchParams.set("engine", ENGINE_OPTION[engine]);
return url.href;
}
var RAW = "https://raw.githubusercontent.com/ONTHEREIN/bettersearch-rules/main";
var GITEE = "https://gitee.com/R3less/bettersearch-rules/raw/main";
var JSDELIVR = "https://cdn.jsdelivr.net/gh/ONTHEREIN/bettersearch-rules@main";
var RETRY_AFTER_MS = 6e5;
function shardUrls(shard, githubProxy = "") {
const path = `sites/${shard}.txt`;
const urls = [
`${GITEE}/${path}`,
`${JSDELIVR}/${path}`,
`${RAW}/${path}`
];
const proxy = githubProxy.trim();
if (/^https?:\/\//.test(proxy)) urls.unshift(`${proxy.replace(/\/*$/, "/")}${RAW}/${path}`);
return urls;
}
function shardOf(domain) {
let h = 2166136261;
for (let i = 0; i < domain.length; i++) {
h ^= domain.charCodeAt(i);
h = Math.imul(h, 16777619) >>> 0;
}
return h.toString(16).padStart(8, "0").slice(0, 3);
}
var SortedList = class {
text;
start;
constructor(text) {
this.text = text;
let start = 0;
while (text.startsWith("#", start)) {
const end = text.indexOf("\n", start);
start = end === -1 ? text.length : end + 1;
}
this.start = start;
}
get(key) {
const { text } = this;
let lo = this.start;
let hi = text.length;
while (lo < hi) {
const mid = lo + hi >>> 1;
const start = text.lastIndexOf("\n", mid - 1) + 1;
let end = text.indexOf("\n", start);
if (end === -1) end = text.length;
const sep = text.indexOf(" = ", start);
const lineKey = text.slice(start, sep !== -1 && sep < end ? sep : end);
if (lineKey === key) return sep !== -1 && sep < end ? text.slice(sep + 3, end) : "";
if (lineKey < key) lo = end + 1;
else hi = start;
}
return null;
}
};
var SiteDirectory = class {
store;
fetcher;
urls;
onLoad;
now;
lists = new Map();
pending = new Set();
failedAt = new Map();
constructor(store, fetcher, urls, onLoad, now = Date.now) {
this.store = store;
this.fetcher = fetcher;
this.urls = urls;
this.onLoad = onLoad;
this.now = now;
}
peek(host) {
const domain = registrableDomain(host.toLowerCase());
const shard = shardOf(domain);
const loaded = this.load(shard);
if (!loaded) return this.failedAt.has(shard) ? null : void 0;
const value = loaded.get(domain);
return value === null ? null : { names: value ? value.split("|") : [] };
}
load(shard) {
let entry = this.lists.get(shard);
if (!entry) {
const cached = this.store.get(`sites:${shard}`, null);
if (cached) {
entry = {
fetchedAt: cached.fetchedAt,
list: new SortedList(cached.text)
};
this.lists.set(shard, entry);
}
}
if (!entry || this.now() - entry.fetchedAt >= 6048e5) this.download(shard);
return entry?.list ?? null;
}
async download(shard) {
const failed = this.failedAt.get(shard);
if (this.pending.has(shard) || failed !== void 0 && this.now() - failed < RETRY_AFTER_MS) return;
this.pending.add(shard);
try {
for (const url of this.urls(shard)) try {
const text = await this.fetcher(url);
const entry = {
fetchedAt: this.now(),
text
};
this.store.set(`sites:${shard}`, entry);
this.lists.set(shard, {
fetchedAt: entry.fetchedAt,
list: new SortedList(text)
});
this.failedAt.delete(shard);
return;
} catch {}
this.failedAt.set(shard, this.now());
} finally {
this.pending.delete(shard);
this.onLoad();
}
}
};
function normalizeText(text) {
return text.toLowerCase().replace(/["“”「」『』]/g, "").replace(/\s+/g, " ").trim();
}
var isWordChar = (c) => !!c && /[a-z0-9]/.test(c);
function mentions(text, name) {
const s = normalizeText(text);
const n = normalizeText(name);
if (!n) return false;
for (let i = s.indexOf(n); i !== -1; i = s.indexOf(n, i + 1)) {
const before = isWordChar(s[i - 1]) && isWordChar(n[0]);
const after = isWordChar(s[i + n.length]) && isWordChar(n[n.length - 1]);
if (!before && !after) return true;
}
return false;
}
function officialFor(site, query) {
let best = null;
for (const name of site.names) if ((!best || name.length > best.length) && mentions(query, name)) best = name;
return best;
}
var CLAIMS_OFFICIAL = /官网|官方|official/i;
var LOOKALIKE_TAIL = /^[-_]?[a-z0-9]{1,10}$/;
var COPYCAT_TAIL = /^[-_]?([a-z]{1,3}|\d+|pro|app|pc|soft|down|download|xiazai|guanwang|official|online|client)$/;
var MIN_BRAND_LENGTH = 4;
var NOT_BRANDS = new Set([
"download",
"free",
"official",
"app",
"apk",
"pc",
"windows",
"win",
"mac",
"macos",
"android",
"ios",
"linux",
"version",
"latest",
"setup",
"install",
"installer",
"online",
"login",
"web",
"site",
"the",
"and",
"for",
"pro",
"crack",
"portable",
"client",
"chinese",
"english"
]);
var CJK_FILLER = [
"官方网站",
"下载安装",
"最新版本",
"官方版",
"最新版",
"中文版",
"电脑版",
"手机版",
"安卓版",
"苹果版",
"绿色版",
"破解版",
"免费版",
"正式版",
"安装包",
"客户端",
"官网",
"官方",
"网站",
"下载",
"最新",
"免费",
"安装",
"入口",
"登录",
"注册",
"首页",
"软件",
"正版",
"地址",
"链接",
"版本",
"在线",
"网页版"
].sort((a, b) => b.length - a.length);
function domainLabel(host) {
return registrableDomain(host).split(".")[0] ?? "";
}
function brandTokens(query) {
return [...new Set(query.toLowerCase().match(/[a-z0-9]{3,}/g) ?? [])];
}
function brandTerms(query) {
const latin = brandTokens(query).filter((w) => !NOT_BRANDS.has(w));
let rest = query.toLowerCase().replace(/[a-z0-9]+/g, " ");
for (const word of CJK_FILLER) rest = rest.split(word).join(" ");
const cjk = rest.match(/[\u3400-\u9fff\uf900-\ufaff]{2,}/g) ?? [];
return [...new Set([...latin, ...cjk])];
}
function siteName(host) {
return siteOf(host).split(".")[0] ?? "";
}
function checkLookalike(result, query, page, { known = null } = {}) {
if (!result.host || result.prominent || known === true || known === void 0) return null;
return claimsOfficialOnBrandDomain(result, query, page) ?? imitatesProminent(result, page) ?? (known === false ? claimsOfficialUnknownSite(result, query) : null);
}
function claimsOfficialUnknownSite(result, query) {
if (!CLAIMS_OFFICIAL.test(result.title)) return null;
const label = domainLabel(result.host);
for (const brand of brandTerms(query)) {
if (label.includes(brand) || !mentions(result.title, brand)) continue;
return {
message: t("lookalike.unknown", {
site: registrableDomain(result.host),
brand
}),
likelyOfficial: null
};
}
return null;
}
function imitatesProminent(result, page) {
const site = registrableDomain(result.host);
const label = site.split(".")[0] ?? "";
for (const official of page) {
if (!official.prominent || !official.host || official === result) continue;
if (registrableDomain(official.host) === site) continue;
const name = siteName(official.host);
if (name.length < MIN_BRAND_LENGTH || label === name || !label.startsWith(name)) continue;
if (!COPYCAT_TAIL.test(label.slice(name.length))) continue;
return {
message: t("lookalike.prominent", {
site,
official: siteOf(official.host)
}),
likelyOfficial: official.host
};
}
return null;
}
function claimsOfficialOnBrandDomain(result, query, page) {
if (!CLAIMS_OFFICIAL.test(result.title)) return null;
const label = domainLabel(result.host);
for (const brand of brandTokens(query)) {
if (label === brand || !label.startsWith(brand)) continue;
if (!LOOKALIKE_TAIL.test(label.slice(brand.length))) continue;
const official = page.find((r) => r.host && domainLabel(r.host) === brand)?.host ?? null;
const site = registrableDomain(result.host);
return {
message: official ? t("lookalike.claimsWithOfficial", {
brand,
official: registrableDomain(official),
site
}) : t("lookalike.claims", {
site,
brand
}),
likelyOfficial: official
};
}
return null;
}
function globToRegExp(glob) {
const escaped = glob.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
return new RegExp(`^${escaped}$`);
}
function compileMatchPattern(pattern) {
const m = pattern.match(/^(\*|https?):\/\/(\*|(?:\*\.)?[^/*]+)(\/.*)$/);
if (!m) return null;
const [, scheme, host, path] = m;
const pathRe = globToRegExp(path);
return (url) => {
if (scheme !== "*" && url.protocol !== `${scheme}:`) return false;
if (host !== "*") {
if (host.startsWith("*.")) {
const base = host.slice(2);
if (url.hostname !== base && !url.hostname.endsWith(`.${base}`)) return false;
} else if (url.hostname !== host) return false;
}
return pathRe.test(url.pathname + url.search);
};
}
function compileLine(line) {
if (line.length > 2 && line.startsWith("/") && line.endsWith("/")) try {
const re = new RegExp(line.slice(1, -1));
return (url) => re.test(url.href);
} catch {
return null;
}
if (line.includes("://")) return compileMatchPattern(line);
if (/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(line)) return compileMatchPattern(`*://*.${line.toLowerCase()}/*`);
return null;
}
function compileRules(text) {
const block = [];
const allow = [];
for (const raw of text.split("\n")) {
const line = raw.trim();
if (!line || line.startsWith("#")) continue;
const isAllow = line.startsWith("@");
const matcher = compileLine(isAllow ? line.slice(1) : line);
if (matcher) (isAllow ? allow : block).push(matcher);
}
return { blocks(href) {
let url;
try {
url = new URL(href);
} catch {
return false;
}
return block.some((m) => m(url)) && !allow.some((m) => m(url));
} };
}
function siteRule(host) {
return `*://*.${siteOf(host)}/*`;
}
var cacheKey = (sub) => `subscription:${sub.urls[0] ?? ""}`;
var failureKey = (sub) => `subscription-error:${sub.urls[0] ?? ""}`;
function cachedList(store, sub) {
return store.get(cacheKey(sub), null);
}
function lastFailure(store, sub) {
return store.get(failureKey(sub), null);
}
function isStale(list, now) {
return !list || now - list.fetchedAt >= 864e5;
}
async function refreshSubscription(store, sub, fetcher, now = Date.now()) {
const errors = [];
for (const url of sub.urls) try {
const list = {
fetchedAt: now,
source: url,
rules: await fetcher(url)
};
store.set(cacheKey(sub), list);
store.set(failureKey(sub), null);
return list;
} catch (error) {
errors.push(`${url}: ${error instanceof Error ? error.message : String(error)}`);
}
store.set(failureKey(sub), {
failedAt: now,
message: errors.join("; ")
});
return cachedList(store, sub);
}
function combinedRules(store, userRules, subs) {
return [userRules, ...subs.filter((s) => s.enabled).map((s) => cachedList(store, s)?.rules ?? "")].join("\n");
}
var DEFAULT_SETTINGS = {
version: 2,
removeAds: true,
cleanLinks: true,
openLinks: "engine",
blockAction: "collapse",
layout: true,
columns: "2",
cardStyle: "card",
density: "compact",
customCss: "",
collapseAiAnswers: true,
markOfficial: true,
pinOfficial: false,
githubProxy: "",
autoPage: true,
autoPageLimit: 5,
rules: "",
subscriptions: [],
aiProvider: "deepseek",
aiBaseUrl: "https://api.deepseek.com/v1",
aiModel: "deepseek-chat",
aiApiKey: ""
};
var KEY = "settings";
function migrateSettings(stored) {
const next = { ...stored };
if ((next.version ?? 1) < 2 && next.columns === "auto") next.columns = "2";
next.version = 2;
return next;
}
function loadSettings(store) {
const stored = store.get(KEY, null);
return {
...DEFAULT_SETTINGS,
...stored ? migrateSettings(stored) : {}
};
}
function saveSettings(store, settings) {
store.set(KEY, settings);
}
function addRule(rules, rule) {
if (rules.split("\n").map((l) => l.trim()).includes(rule)) return rules;
return rules.trim() ? `${rules.trimEnd()}\n${rule}` : rule;
}
function removeRule(rules, rule) {
return rules.split("\n").filter((l) => l.trim() !== rule).join("\n");
}
var NOT_SYNCED = new Set([
"version",
"aiApiKey",
"rules",
"subscriptions"
]);
var TOMBSTONE_MS = 15552e6;
function emptyDoc() {
return {
format: 1,
settingsVersion: 2,
fields: {},
rules: {},
subscriptions: {}
};
}
var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
function ruleLines(rules) {
return [...new Set(rules.split("\n").map((l) => l.trim()).filter(Boolean))];
}
function stampLocal(previous, settings, now) {
const at = previous ? now : 0;
const base = previous ?? emptyDoc();
const doc = {
...emptyDoc(),
fields: { ...base.fields },
rules: { ...base.rules },
subscriptions: { ...base.subscriptions }
};
for (const [key, value] of Object.entries(settings)) {
if (NOT_SYNCED.has(key)) continue;
const old = base.fields[key];
if (!old || !same(old.value, value)) doc.fields[key] = {
value,
at
};
}
const lines = new Set(ruleLines(settings.rules));
for (const line of lines) if (!base.rules[line] || base.rules[line].deleted) doc.rules[line] = { at };
for (const [line, stamp] of Object.entries(base.rules)) if (!stamp.deleted && !lines.has(line)) doc.rules[line] = {
at,
deleted: true
};
const subs = new Map(settings.subscriptions.filter((s) => s.urls[0]).map((s) => [s.urls[0], s]));
for (const [key, sub] of subs) {
const old = base.subscriptions[key];
if (!old || old.deleted || !same(old.value, sub)) doc.subscriptions[key] = {
value: sub,
at
};
}
for (const [key, stamp] of Object.entries(base.subscriptions)) if (!stamp.deleted && !subs.has(key)) doc.subscriptions[key] = {
at,
deleted: true
};
return doc;
}
function mergeMap(local, remote, pruneBefore) {
const out = {};
for (const key of new Set([...Object.keys(remote), ...Object.keys(local)])) {
const a = local[key];
const b = remote[key];
const winner = !a ? b : !b ? a : a.at > b.at ? a : b;
if (winner.deleted && winner.at < pruneBefore) continue;
out[key] = winner;
}
return out;
}
function mergeDocs(local, remote, now) {
return {
format: Math.max(local.format, remote.format),
settingsVersion: Math.max(local.settingsVersion, remote.settingsVersion),
fields: mergeMap(local.fields, remote.fields, 0),
rules: mergeMap(local.rules, remote.rules, now - TOMBSTONE_MS),
subscriptions: mergeMap(local.subscriptions, remote.subscriptions, now - TOMBSTONE_MS),
history: remote.history
};
}
function sameContent(a, b) {
return same([
a.fields,
a.rules,
a.subscriptions
], [
b.fields,
b.rules,
b.subscriptions
]);
}
function applyDoc(settings, doc) {
const next = { ...settings };
for (const [key, { value }] of Object.entries(doc.fields)) {
const known = DEFAULT_SETTINGS[key];
if (known === void 0 || NOT_SYNCED.has(key)) continue;
if (typeof value !== typeof known || Array.isArray(value) !== Array.isArray(known)) continue;
next[key] = value;
}
const live = new Set(Object.keys(doc.rules).filter((line) => !doc.rules[line].deleted));
const kept = new Set();
const lines = settings.rules.split("\n").filter((raw) => {
const line = raw.trim();
if (!line) return true;
if (!live.has(line) || kept.has(line)) return false;
kept.add(line);
return true;
});
for (const line of live) if (!kept.has(line)) lines.push(line);
next.rules = lines.join("\n").replace(/^\n+|\n+$/g, "");
const subs = settings.subscriptions.filter((s) => {
const stamp = doc.subscriptions[s.urls[0] ?? ""];
return stamp && !stamp.deleted;
});
const present = new Set(subs.map((s) => s.urls[0]));
for (const [key, stamp] of Object.entries(doc.subscriptions)) if (!stamp.deleted && stamp.value && !present.has(key)) subs.push(stamp.value);
next.subscriptions = subs.map((s) => {
return doc.subscriptions[s.urls[0]]?.value ?? s;
});
if (next.aiBaseUrl !== settings.aiBaseUrl) next.aiApiKey = "";
return next;
}
var FOLDER = "BetterSearch/";
var MAIN = "sync.json";
function basicAuth(username, password) {
const bytes = new TextEncoder().encode(`${username}:${password}`);
return `Basic ${btoa(String.fromCharCode(...bytes))}`;
}
function davRequest(config, method, path, body) {
const base = config.url.trim().replace(/\/*$/, "/");
const headers = { Authorization: basicAuth(config.username, config.password) };
if (body !== void 0) headers["Content-Type"] = "application/json; charset=utf-8";
return {
method,
url: base + FOLDER + path,
headers,
body
};
}
var SyncError = class extends Error {
status;
constructor(message, status = 0) {
super(message);
this.status = status;
}
};
function parseDoc(body) {
try {
const doc = JSON.parse(body);
if (typeof doc.format === "number" && doc.fields && doc.rules && doc.subscriptions) return doc;
} catch {}
throw new SyncError("sync.json is not a BetterSearch sync file");
}
var ok = (status) => status >= 200 && status < 300;
function failure(status) {
return new SyncError(status === 401 || status === 403 ? "auth" : `HTTP ${status}`, status);
}
function backupName(now) {
return `history/${new Date(now).toISOString().replace(/[:.]/g, "-")}.json`;
}
async function runSync(send, config, local, now) {
const got = await send(davRequest(config, "GET", MAIN));
if (!ok(got.status) && got.status !== 404) throw failure(got.status);
const remote = got.status === 404 ? null : parseDoc(got.body);
const merged = remote ? mergeDocs(local, remote, now) : {
...local,
history: []
};
if (remote && sameContent(merged, remote)) return {
doc: merged,
uploaded: false
};
const put = async (path, body) => {
let r = await send(davRequest(config, "PUT", path, body));
if (r.status === 404 || r.status === 409) {
await send(davRequest(config, "MKCOL", ""));
await send(davRequest(config, "MKCOL", "history/"));
r = await send(davRequest(config, "PUT", path, body));
}
if (!ok(r.status)) throw failure(r.status);
};
let history = merged.history ?? [];
let dropped = [];
if (remote) {
const name = backupName(now);
await put(name, got.body);
history = [...history.filter((h) => h !== name), name];
dropped = history.slice(0, -10);
history = history.slice(-10);
}
const doc = {
...merged,
history
};
await put(MAIN, JSON.stringify(doc));
await Promise.allSettled(dropped.map((name) => send(davRequest(config, "DELETE", name))));
return {
doc,
uploaded: true
};
}
var FORMAT = "bettersearch-theme";
var CARD_STYLES = [
"card",
"raised",
"line"
];
var DENSITIES = ["compact", "comfortable"];
function exportTheme(settings) {
const { cardStyle, density, customCss } = settings;
return JSON.stringify({
format: FORMAT,
version: 1,
cardStyle,
density,
css: customCss
}, null, 2);
}
function themeCssProblem(css) {
const code = css.replace(/\/\*[\s\S]*?(\*\/|$)/g, " ").toLowerCase();
if (code.includes("\\")) return "theme.escape";
if (/@import|image-set\(|(^|[^\w-])src\(/.test(code)) return "theme.remote";
for (const match of code.matchAll(/url\(\s*(['"]?)\s*([^'")\s]*)/g)) if (!match[2].startsWith("data:")) return "theme.remote";
return null;
}
function parseTheme(text) {
let data;
try {
data = JSON.parse(text);
} catch {
return { problem: "theme.invalid" };
}
if (!data || typeof data !== "object") return { problem: "theme.invalid" };
const { format, cardStyle, density, css } = data;
if (format !== FORMAT || !CARD_STYLES.includes(cardStyle) || !DENSITIES.includes(density) || typeof css !== "string") return { problem: "theme.invalid" };
const problem = themeCssProblem(css);
if (problem) return { problem };
return { theme: {
cardStyle,
density,
customCss: css
} };
}
var adapters = [
googleAdapter,
bingAdapter,
baiduAdapter
];
function adapterForHost(hostname) {
return adapters.find((a) => a.ownsHost(hostname));
}
var is_array = Array.isArray;
var index_of = Array.prototype.indexOf;
var includes = Array.prototype.includes;
var array_from = Array.from;
var define_property = Object.defineProperty;
var get_descriptor = Object.getOwnPropertyDescriptor;
var get_descriptors = Object.getOwnPropertyDescriptors;
var object_prototype = Object.prototype;
var array_prototype = Array.prototype;
var get_prototype_of = Object.getPrototypeOf;
var is_extensible = Object.isExtensible;
var noop = () => {};
function run_all(arr) {
for (var i = 0; i < arr.length; i++) arr[i]();
}
function deferred() {
var resolve;
var reject;
return {
promise: new Promise((res, rej) => {
resolve = res;
reject = rej;
}),
resolve,
reject
};
}
var CLEAN = 1024;
var DIRTY = 2048;
var MAYBE_DIRTY = 4096;
var INERT = 8192;
var DESTROYED = 16384;
var REACTION_RAN = 32768;
var DESTROYING = 1 << 25;
var EFFECT_TRANSPARENT = 65536;
var EFFECT_PRESERVED = 1 << 19;
var USER_EFFECT = 1 << 20;
var EFFECT_OFFSCREEN = 1 << 25;
var REACTION_IS_UPDATING = 1 << 21;
var ASYNC = 1 << 22;
var ERROR_VALUE = 1 << 23;
var STATE_SYMBOL = Symbol("$state");
var COMPONENT_SYMBOL = Symbol("component");
var LOADING_ATTR_SYMBOL = Symbol("");
var ATTRIBUTES_CACHE = Symbol("attributes");
var CLASS_CACHE = Symbol("class");
var STYLE_CACHE = Symbol("style");
var TEXT_CACHE = Symbol("text");
var FORM_RESET_HANDLER = Symbol("form reset");
var STALE_REACTION = new class StaleReactionError extends Error {
name = "StaleReactionError";
message = "The reaction that called `getAbortSignal()` was re-run or destroyed";
}();
var IS_XHTML = !!globalThis.document?.contentType && globalThis.document.contentType.includes("xml");
var HYDRATION_ERROR = {};
var UNINITIALIZED = Symbol("uninitialized");
var NAMESPACE_HTML = "http://www.w3.org/1999/xhtml";
var NAMESPACE_SVG = "http://www.w3.org/2000/svg";
var NAMESPACE_MATHML = "http://www.w3.org/1998/Math/MathML";
function derived_inert() {
console.warn(`https://svelte.dev/e/derived_inert`);
}
function hydration_mismatch(location) {
console.warn(`https://svelte.dev/e/hydration_mismatch`);
}
function select_multiple_invalid_value() {
console.warn(`https://svelte.dev/e/select_multiple_invalid_value`);
}
function svelte_boundary_reset_noop() {
console.warn(`https://svelte.dev/e/svelte_boundary_reset_noop`);
}
var hydrating = false;
function set_hydrating(value) {
hydrating = value;
}
var hydrate_node;
function set_hydrate_node(node) {
if (node === null) {
hydration_mismatch();
throw HYDRATION_ERROR;
}
return hydrate_node = node;
}
function hydrate_next() {
return set_hydrate_node(get_next_sibling(hydrate_node));
}
function reset(node) {
if (!hydrating) return;
if (get_next_sibling(hydrate_node) !== null) {
hydration_mismatch();
throw HYDRATION_ERROR;
}
hydrate_node = node;
}
function next(count = 1) {
if (hydrating) {
var i = count;
var node = hydrate_node;
while (i--) node = get_next_sibling(node);
hydrate_node = node;
}
}
function skip_nodes(remove = true) {
var depth = 0;
var node = hydrate_node;
while (true) {
if (node.nodeType === 8) {
var data = node.data;
if (data === "]") {
if (depth === 0) return node;
depth -= 1;
} else if (data === "[" || data === "[!" || data[0] === "[" && !isNaN(Number(data.slice(1)))) depth += 1;
}
var next = get_next_sibling(node);
if (remove) node.remove();
node = next;
}
}
function read_hydration_instruction(node) {
if (!node || node.nodeType !== 8) {
hydration_mismatch();
throw HYDRATION_ERROR;
}
return node.data;
}
function equals(value) {
return value === this.v;
}
function safe_not_equal(a, b) {
return a != a ? b == b : a !== b || a !== null && typeof a === "object" || typeof a === "function";
}
function safe_equals(value) {
return !safe_not_equal(value, this.v);
}
function async_derived_orphan() {
throw new Error(`https://svelte.dev/e/async_derived_orphan`);
}
function each_key_duplicate(a, b, value) {
throw new Error(`https://svelte.dev/e/each_key_duplicate`);
}
function effect_update_depth_exceeded() {
throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`);
}
function state_descriptors_fixed() {
throw new Error(`https://svelte.dev/e/state_descriptors_fixed`);
}
function state_prototype_fixed() {
throw new Error(`https://svelte.dev/e/state_prototype_fixed`);
}
function state_unsafe_mutation() {
throw new Error(`https://svelte.dev/e/state_unsafe_mutation`);
}
function svelte_boundary_reset_onerror() {
throw new Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`);
}
var async_mode_flag = false;
var legacy_mode_flag = false;
var component_context = null;
function set_component_context(context) {
component_context = context;
}
function push(props, runes = false, fn) {
component_context = {
p: component_context,
i: false,
c: null,
e: null,
s: props,
x: null,
r: active_effect,
l: legacy_mode_flag && !runes ? {
s: null,
u: null,
$: []
} : null
};
}
function pop(component) {
var context = component_context;
var effects = context.e;
if (effects !== null) {
context.e = null;
for (var fn of effects) create_user_effect(fn);
}
if (component !== void 0) context.x = component;
context.i = true;
component_context = context.p;
return mark_as_component(component);
}
function mark_as_component(component = {}) {
define_property(component, COMPONENT_SYMBOL, { value: true });
return component;
}
function is_runes() {
return !legacy_mode_flag || component_context !== null && component_context.l === null;
}
var micro_tasks = [];
function run_micro_tasks() {
var tasks = micro_tasks;
micro_tasks = [];
run_all(tasks);
}
function queue_micro_task(fn) {
if (micro_tasks.length === 0 && !is_flushing_sync) {
var tasks = micro_tasks;
queueMicrotask(() => {
if (tasks === micro_tasks) run_micro_tasks();
});
}
micro_tasks.push(fn);
}
function flush_tasks() {
while (micro_tasks.length > 0) run_micro_tasks();
}
var STATUS_MASK = ~(DIRTY | MAYBE_DIRTY | CLEAN);
function set_signal_status(signal, status) {
signal.f = signal.f & STATUS_MASK | status;
}
function update_derived_status(derived) {
if ((derived.f & 512) !== 0 || derived.deps === null) set_signal_status(derived, CLEAN);
else set_signal_status(derived, MAYBE_DIRTY);
}
function defer_effect(effect, dirty_reactions) {
if ((effect.f & 2048) !== 0) dirty_reactions.set(effect, DIRTY);
else if ((effect.f & 4096) !== 0 && dirty_reactions.get(effect) !== 2048) dirty_reactions.set(effect, MAYBE_DIRTY);
set_signal_status(effect, CLEAN);
}
function remove_textarea_child(dom) {
if (hydrating && get_first_child(dom) !== null) clear_text_content(dom);
}
var listening_to_form_reset = false;
function add_form_reset_listener() {
if (!listening_to_form_reset) {
listening_to_form_reset = true;
document.addEventListener("reset", (evt) => {
Promise.resolve().then(() => {
if (!evt.defaultPrevented) for (const e of evt.target.elements) e[FORM_RESET_HANDLER]?.();
});
}, { capture: true });
}
}
function without_reactive_context(fn) {
var previous_reaction = active_reaction;
var previous_effect = active_effect;
set_active_reaction(null);
set_active_effect(null);
try {
return fn();
} finally {
set_active_reaction(previous_reaction);
set_active_effect(previous_effect);
}
}
function listen_to_event_and_reset_event(element, event, handler, on_reset = handler) {
element.addEventListener(event, () => without_reactive_context(handler));
const prev = element[FORM_RESET_HANDLER];
if (prev) element[FORM_RESET_HANDLER] = () => {
prev();
on_reset(true);
};
else element[FORM_RESET_HANDLER] = () => on_reset(true);
add_form_reset_listener();
}
function flatten(blockers, sync, async, fn) {
const d = is_runes() ? derived : derived_safe_equal;
var pending = blockers.filter((b) => !b.settled);
var deriveds = sync.map(d);
if (async.length === 0 && pending.length === 0) {
fn(deriveds);
return;
}
var parent = active_effect;
var restore = capture();
var blocker_promise = pending.length === 1 ? pending[0].promise : pending.length > 1 ? Promise.all(pending.map((b) => b.promise)) : null;
function finish(async) {
if ((parent.f & 16384) !== 0) return;
restore();
try {
fn([...deriveds, ...async]);
} catch (error) {
invoke_error_boundary(error, parent);
}
unset_context();
}
var decrement_pending = increment_pending();
if (async.length === 0) {
blocker_promise.then(() => finish([])).finally(decrement_pending);
return;
}
function run() {
Promise.all(async.map((expression) => async_derived(expression))).then(finish).catch((error) => invoke_error_boundary(error, parent)).finally(decrement_pending);
}
if (blocker_promise) blocker_promise.then(() => {
if ((parent.f & 16384) !== 0) {
decrement_pending();
return;
}
restore();
run();
unset_context();
});
else run();
}
function capture() {
var previous_effect = active_effect;
var previous_reaction = active_reaction;
var previous_component_context = component_context;
var previous_batch = current_batch;
return function restore(activate_batch = true) {
set_active_effect(previous_effect);
set_active_reaction(previous_reaction);
set_component_context(previous_component_context);
if (activate_batch && (previous_effect.f & 16384) === 0) {
previous_batch?.activate();
previous_batch?.apply();
}
};
}
function unset_context(deactivate_batch = true) {
set_active_effect(null);
set_active_reaction(null);
set_component_context(null);
if (deactivate_batch) current_batch?.deactivate();
}
function increment_pending() {
var effect = active_effect;
var boundary = effect.b;
var batch = current_batch;
var blocking = !!boundary?.is_rendered();
boundary?.update_pending_count(1, batch);
batch.increment(blocking, effect);
return () => {
boundary?.update_pending_count(-1, batch);
batch.decrement(blocking, effect);
};
}
function derived(fn) {
var flags = 2 | DIRTY;
if (active_effect !== null) active_effect.f |= EFFECT_PRESERVED;
return {
ctx: component_context,
deps: null,
effects: null,
equals,
f: flags,
fn,
reactions: null,
rv: 0,
v: UNINITIALIZED,
wv: 0,
parent: active_effect,
ac: null
};
}
var OBSOLETE = Symbol("obsolete");
function async_derived(fn, label, location) {
let parent = active_effect;
if (parent === null) async_derived_orphan();
var promise = void 0;
var signal = source(UNINITIALIZED);
var should_suspend = !active_reaction;
var deferreds = new Set();
async_effect(() => {
var effect = active_effect;
var d = deferred();
promise = d.promise;
try {
Promise.resolve(fn()).then(d.resolve, (e) => {
if (e !== STALE_REACTION) d.reject(e);
}).finally(unset_context);
} catch (error) {
d.reject(error);
unset_context();
}
var batch = current_batch;
if (should_suspend) {
if ((effect.f & 32768) !== 0) var decrement_pending = increment_pending();
if (parent.b?.is_rendered()) batch.async_deriveds.get(effect)?.reject(OBSOLETE);
else for (const d of deferreds.values()) d.reject(OBSOLETE);
deferreds.add(d);
batch.async_deriveds.set(effect, d);
}
const handler = (value, error = void 0) => {
decrement_pending?.();
deferreds.delete(d);
if (error === OBSOLETE) return;
batch.activate();
if (error) {
signal.f |= ERROR_VALUE;
internal_set(signal, error);
} else {
if ((signal.f & 8388608) !== 0) signal.f ^= ERROR_VALUE;
internal_set(signal, value);
}
batch.deactivate();
};
d.promise.then(handler, (e) => handler(null, e || "unknown"));
});
teardown(() => {
for (const d of deferreds) d.reject(OBSOLETE);
});
return new Promise((fulfil) => {
function next(p) {
function go() {
if (p === promise) fulfil(signal);
else next(promise);
}
p.then(go, go);
}
next(promise);
});
}
function user_derived(fn) {
const d = derived(fn);
if (!async_mode_flag) push_reaction_value(d);
return d;
}
function derived_safe_equal(fn) {
const signal = derived(fn);
signal.equals = safe_equals;
return signal;
}
function destroy_derived_effects(derived) {
var effects = derived.effects;
if (effects !== null) {
derived.effects = null;
for (var i = 0; i < effects.length; i += 1) destroy_effect(effects[i]);
}
}
function execute_derived(derived) {
var value;
var prev_active_effect = active_effect;
var parent = derived.parent;
if (!is_destroying_effect && parent !== null && derived.v !== UNINITIALIZED && (parent.f & 24576) !== 0) {
derived_inert();
return derived.v;
}
set_active_effect(parent);
try {
destroy_derived_effects(derived);
value = update_reaction(derived);
} finally {
set_active_effect(prev_active_effect);
}
return value;
}
function update_derived(derived) {
var value = execute_derived(derived);
if (!derived.equals(value)) {
derived.wv = increment_write_version();
if (!current_batch?.is_fork || derived.deps === null) {
if (current_batch !== null) {
current_batch.capture(derived, value, true);
previous_batch?.capture(derived, value, true);
} else derived.v = value;
if (derived.deps === null) {
set_signal_status(derived, CLEAN);
return;
}
}
}
if (is_destroying_effect) return;
if (batch_values !== null) {
if (effect_tracking() || current_batch?.is_fork) batch_values.set(derived, value);
} else update_derived_status(derived);
}
function freeze_derived_effects(derived) {
if (derived.effects === null) return;
for (const e of derived.effects) if (e.teardown || e.ac) {
e.teardown?.();
if (e.ac !== null) without_reactive_context(() => {
e.ac.abort(STALE_REACTION);
e.ac = null;
});
if (e.fn !== null) e.teardown = noop;
remove_reactions(e, 0);
destroy_effect_children(e);
}
}
function unfreeze_derived_effects(derived) {
if (derived.effects === null) return;
for (const e of derived.effects) if (e.teardown && e.fn !== null) update_effect(e);
}
var first_batch = null;
var last_batch = null;
var current_batch = null;
var previous_batch = null;
var batch_values = null;
var last_scheduled_effect = null;
var is_flushing_sync = false;
var is_processing = false;
var collected_effects = null;
var legacy_updates = null;
var flush_count = 0;
var uid = 1;
var Batch = class Batch {
id = uid++;
started = false;
linked = true;
prev = null;
next = null;
async_deriveds = new Map();
current = new Map();
previous = new Map();
#commit_callbacks = new Set();
#discard_callbacks = new Set();
#pending = 0;
#blocking_pending = new Map();
#deferred = null;
#scheduled = [];
#new_effects = [];
#dirty_reactions = new Map();
#skipped_branches = new Map();
#unskipped_branches = new Set();
is_fork = false;
#decrement_queued = false;
constructor() {
if (last_batch === null) first_batch = last_batch = this;
else {
last_batch.next = this;
this.prev = last_batch;
}
last_batch = this;
}
#is_deferred() {
if (this.is_fork) return true;
for (const effect of this.#blocking_pending.keys()) if (!this.#is_skipped(effect)) return true;
return false;
}
#is_skipped(effect) {
for (var e = effect; e !== null; e = e.parent) if (this.#skipped_branches.has(e)) return true;
return false;
}
skip_effect(effect) {
if (!this.#skipped_branches.has(effect)) this.#skipped_branches.set(effect, {
d: [],
m: []
});
this.#unskipped_branches.delete(effect);
}
unskip_effect(effect, callback = (e) => this.schedule(e)) {
var tracked = this.#skipped_branches.get(effect);
if (tracked) {
this.#skipped_branches.delete(effect);
for (var e of tracked.d) {
set_signal_status(e, DIRTY);
callback(e);
}
for (e of tracked.m) {
set_signal_status(e, MAYBE_DIRTY);
callback(e);
}
}
this.#unskipped_branches.add(effect);
}
#resolve() {
var roots = [];
for (const effect of this.#scheduled) {
if ((effect.f & 16384) !== 0 || (effect.f & 6144) === 0) continue;
var e = effect;
var covered = false;
while (e.parent !== null) {
e = e.parent;
var flags = e.f;
if ((flags & 96) !== 0) {
if ((flags & 1024) === 0) {
covered = true;
break;
}
e.f ^= CLEAN;
}
}
if (!covered) roots.push(e);
}
this.#scheduled = [];
return roots;
}
#process() {
this.started = true;
for (const [e, status] of this.#dirty_reactions) {
set_signal_status(e, status);
this.schedule(e);
}
this.apply();
var effects = collected_effects = [];
var render_effects = [];
var updates = legacy_updates = [];
while (this.#scheduled.length > 0) {
if (flush_count++ > 1e3) {
this.#unlink();
infinite_loop_guard();
}
for (const root of this.#resolve()) try {
this.#traverse(root, effects, render_effects);
} catch (e) {
reset_all(root);
if (!this.#is_deferred()) this.discard();
throw e;
}
}
current_batch = null;
if (updates.length > 0) {
var batch = Batch.ensure();
for (const e of updates) batch.schedule(e);
}
collected_effects = null;
legacy_updates = null;
if (this.#is_deferred()) {
this.#defer_effects(render_effects);
this.#defer_effects(effects);
for (const [e, t] of this.#skipped_branches) reset_branch(e, t);
if (updates.length > 0) current_batch.#process();
return;
}
const earlier_batch = this.#find_earlier_batch();
if (earlier_batch) {
this.#defer_effects(render_effects);
this.#defer_effects(effects);
earlier_batch.#merge(this);
return;
}
this.#dirty_reactions.clear();
for (const fn of this.#commit_callbacks) fn(this);
this.#commit_callbacks.clear();
previous_batch = this;
flush_queued_effects(render_effects);
flush_queued_effects(effects);
previous_batch = null;
this.#deferred?.resolve();
var next_batch = current_batch;
if (this.#pending === 0 && (this.#scheduled.length === 0 || next_batch !== null)) {
this.#unlink();
if (async_mode_flag) {
this.#commit();
current_batch = next_batch;
}
}
if (next_batch !== null) {
old_values.clear();
next_batch.#process();
}
}
#traverse(root, effects, render_effects) {
root.f ^= CLEAN;
var effect = root.first;
while (effect !== null) {
var flags = effect.f;
var is_branch = (flags & 96) !== 0;
if (!(is_branch && (flags & 1024) !== 0 || (flags & 8192) !== 0 || this.#skipped_branches.has(effect)) && effect.fn !== null) {
if (is_branch) effect.f ^= CLEAN;
else if ((flags & 4) !== 0) effects.push(effect);
else if (async_mode_flag && (flags & 16777224) !== 0) render_effects.push(effect);
else if (is_dirty(effect)) {
if ((flags & 16) !== 0) this.add_dirty_reaction(effect, MAYBE_DIRTY);
update_effect(effect);
}
var child = effect.first;
if (child !== null) {
effect = child;
continue;
}
}
while (effect !== null) {
var next = effect.next;
if (next !== null) {
effect = next;
break;
}
effect = effect.parent;
}
}
}
#find_earlier_batch() {
for (var batch = this.prev; batch !== null; batch = batch.prev) if (!batch.is_fork && this.#intersects(batch)) return batch;
return null;
}
#intersects(batch) {
for (const [source, [, is_derived]] of this.current) {
if (is_derived) continue;
if (batch.current.has(source)) return true;
}
return false;
}
#merge(batch) {
for (const [source, value] of batch.current) {
if (!this.previous.has(source) && batch.previous.has(source)) this.previous.set(source, batch.previous.get(source));
this.current.set(source, value);
}
for (const [effect, deferred] of batch.async_deriveds) {
const d = this.async_deriveds.get(effect);
if (d) deferred.promise.then(d.resolve).catch(d.reject);
}
batch.async_deriveds.clear();
this.transfer_reactions(batch.#dirty_reactions);
const mark = (value) => {
var reactions = value.reactions;
if (reactions === null) return;
if ((value.f & 2) !== 0 && (value.f & 6144) === 0) return;
for (const reaction of reactions) {
var flags = reaction.f;
if ((flags & 2) !== 0) mark(reaction);
else {
var effect = reaction;
if (flags & 4194320 && !this.async_deriveds.has(effect)) {
this.#dirty_reactions.delete(effect);
set_signal_status(effect, DIRTY);
this.schedule(effect);
}
}
}
};
for (const source of this.current.keys()) mark(source);
this.oncommit(() => batch.discard());
batch.#unlink();
current_batch = this;
this.#process();
}
#defer_effects(effects) {
for (var i = 0; i < effects.length; i += 1) defer_effect(effects[i], this.#dirty_reactions);
}
capture(source, value, is_derived = false) {
if (source.v !== UNINITIALIZED && !this.previous.has(source)) this.previous.set(source, source.v);
if ((source.f & 8388608) === 0) {
this.current.set(source, [value, is_derived]);
batch_values?.set(source, value);
}
if (!this.is_fork) source.v = value;
}
activate() {
current_batch = this;
}
deactivate() {
current_batch = null;
batch_values = null;
}
flush() {
try {
is_processing = true;
current_batch = this;
this.#process();
} finally {
flush_count = 0;
last_scheduled_effect = null;
collected_effects = null;
legacy_updates = null;
is_processing = false;
current_batch = null;
batch_values = null;
old_values.clear();
}
}
discard() {
for (const fn of this.#discard_callbacks) fn(this);
this.#discard_callbacks.clear();
for (const deferred of this.async_deriveds.values()) deferred.reject(OBSOLETE);
this.#unlink();
this.#deferred?.resolve();
}
register_created_effect(effect) {
this.#new_effects.push(effect);
}
#commit() {
for (let batch = first_batch; batch !== null; batch = batch.next) {
var is_earlier = batch.id < this.id;
var sources = [];
for (const [source, [value, is_derived]] of this.current) {
if (batch.current.has(source)) {
var batch_value = batch.current.get(source)[0];
if (is_earlier && value !== batch_value) batch.current.set(source, [value, is_derived]);
else continue;
}
sources.push(source);
}
if (is_earlier) for (const [effect, deferred] of this.async_deriveds) {
const d = batch.async_deriveds.get(effect);
if (d) deferred.promise.then(d.resolve).catch(d.reject);
}
var current = [...batch.current.keys()].filter((source) => !batch.current.get(source)[1]);
if (!batch.started || current.length === 0) continue;
var others = current.filter((source) => !this.current.has(source));
if (others.length === 0) {
if (is_earlier) batch.discard();
} else if (sources.length > 0) {
if (is_earlier) for (const unskipped of this.#unskipped_branches) batch.unskip_effect(unskipped, (e) => {
if ((e.f & 4194320) !== 0) batch.schedule(e);
else batch.#defer_effects([e]);
});
batch.activate();
var marked = new Set();
var checked = new Map();
for (var source of sources) mark_effects(source, others, marked, checked);
checked = new Map();
var current_unequal = [...batch.current].filter(([c, v1]) => {
const v2 = this.current.get(c);
if (!v2) return true;
return v2[0] !== v1[0] || v2[1] !== v1[1];
}).map(([c]) => c);
if (current_unequal.length > 0) {
for (const effect of this.#new_effects) if ((effect.f & 155648) === 0 && depends_on(effect, current_unequal, checked)) {
if ((effect.f & 4194320) !== 0) {
set_signal_status(effect, DIRTY);
batch.schedule(effect);
} else batch.add_dirty_reaction(effect, DIRTY);
}
}
if (batch.#scheduled.length > 0 && !batch.#decrement_queued) {
batch.apply();
for (var root of batch.#resolve()) batch.#traverse(root, [], []);
}
batch.deactivate();
}
}
}
increment(blocking, effect) {
this.#pending += 1;
if (blocking) {
let blocking_pending_count = this.#blocking_pending.get(effect) ?? 0;
this.#blocking_pending.set(effect, blocking_pending_count + 1);
}
}
decrement(blocking, effect) {
this.#pending -= 1;
if (blocking) {
let blocking_pending_count = this.#blocking_pending.get(effect) ?? 0;
if (blocking_pending_count === 1) this.#blocking_pending.delete(effect);
else this.#blocking_pending.set(effect, blocking_pending_count - 1);
}
if (this.#decrement_queued) return;
this.#decrement_queued = true;
queue_micro_task(() => {
this.#decrement_queued = false;
if (this.linked) this.flush();
});
}
transfer_reactions(dirty_reactions) {
for (const [effect, status] of dirty_reactions) this.add_dirty_reaction(effect, status);
dirty_reactions.clear();
}
add_dirty_reaction(effect, status) {
if (status === 2048 || this.#dirty_reactions.get(effect) !== 2048) this.#dirty_reactions.set(effect, status);
}
oncommit(fn) {
this.#commit_callbacks.add(fn);
}
ondiscard(fn) {
this.#discard_callbacks.add(fn);
}
settled() {
return (this.#deferred ??= deferred()).promise;
}
static ensure() {
if (current_batch === null) {
const batch = current_batch = new Batch();
if (!is_processing && !is_flushing_sync) queue_micro_task(() => {
if (!batch.started) batch.flush();
});
}
return current_batch;
}
apply() {
if (!async_mode_flag || !this.is_fork && this.prev === null && this.next === null) {
batch_values = null;
return;
}
batch_values = new Map();
for (const [source, [value]] of this.current) batch_values.set(source, value);
for (let batch = first_batch; batch !== null; batch = batch.next) {
if (batch === this || batch.is_fork) continue;
if (batch.id >= this.id || !batch.#intersects(this)) {
for (const [source, previous] of batch.previous) if (!batch_values.has(source)) batch_values.set(source, previous);
}
}
}
schedule(effect) {
last_scheduled_effect = effect;
if (effect.b?.is_pending && (effect.f & 16777228) !== 0 && (effect.f & 32768) === 0) {
effect.b.defer_effect(effect);
return;
}
this.#scheduled.push(effect);
}
#unlink() {
if (!this.linked) return;
var prev = this.prev;
var next = this.next;
if (prev === null) first_batch = next;
else prev.next = next;
if (next === null) last_batch = prev;
else next.prev = prev;
this.linked = false;
}
};
function flushSync(fn) {
var was_flushing_sync = is_flushing_sync;
var prev_previous_batch = previous_batch;
previous_batch = null;
is_flushing_sync = true;
try {
var result;
if (fn) {
flushSync();
result = fn();
}
while (true) {
flush_tasks();
if (current_batch === null) return result;
current_batch.flush();
}
} finally {
is_flushing_sync = was_flushing_sync;
previous_batch = prev_previous_batch;
}
}
function infinite_loop_guard() {
try {
effect_update_depth_exceeded();
} catch (error) {
invoke_error_boundary(error, last_scheduled_effect);
}
}
var eager_block_effects = null;
function flush_queued_effects(effects) {
var length = effects.length;
if (length === 0) return;
var i = 0;
while (i < length) {
var effect = effects[i++];
if ((effect.f & 24576) === 0 && is_dirty(effect)) {
eager_block_effects = new Set();
update_effect(effect);
if (effect.deps === null && effect.first === null && effect.nodes === null && effect.teardown === null && effect.ac === null) unlink_effect(effect);
if (eager_block_effects?.size > 0) {
old_values.clear();
for (const e of eager_block_effects) {
if ((e.f & 24576) !== 0) continue;
const ordered_effects = [e];
let ancestor = e.parent;
while (ancestor !== null) {
if (eager_block_effects.has(ancestor)) {
eager_block_effects.delete(ancestor);
ordered_effects.push(ancestor);
}
ancestor = ancestor.parent;
}
for (let j = ordered_effects.length - 1; j >= 0; j--) {
const e = ordered_effects[j];
if ((e.f & 24576) !== 0) continue;
update_effect(e);
}
}
eager_block_effects.clear();
}
}
}
eager_block_effects = null;
}
function mark_effects(value, sources, marked, checked) {
if (marked.has(value)) return;
marked.add(value);
if (value.reactions !== null) for (const reaction of value.reactions) {
const flags = reaction.f;
if ((flags & 2) !== 0) mark_effects(reaction, sources, marked, checked);
else if ((flags & 4194320) !== 0 && (flags & 2048) === 0 && depends_on(reaction, sources, checked)) {
set_signal_status(reaction, DIRTY);
schedule_effect(reaction);
}
}
}
function depends_on(reaction, sources, checked) {
const depends = checked.get(reaction);
if (depends !== void 0) return depends;
if (reaction.deps !== null) for (const dep of reaction.deps) {
if (includes.call(sources, dep)) return true;
if ((dep.f & 2) !== 0 && depends_on(dep, sources, checked)) {
checked.set(dep, true);
return true;
}
}
checked.set(reaction, false);
return false;
}
function schedule_effect(effect) {
current_batch.schedule(effect);
}
function reset_branch(effect, tracked) {
if ((effect.f & 32) !== 0 && (effect.f & 1024) !== 0) return;
if ((effect.f & 2048) !== 0) tracked.d.push(effect);
else if ((effect.f & 4096) !== 0) tracked.m.push(effect);
set_signal_status(effect, CLEAN);
var e = effect.first;
while (e !== null) {
reset_branch(e, tracked);
e = e.next;
}
}
function reset_all(effect) {
set_signal_status(effect, CLEAN);
var e = effect.first;
while (e !== null) {
reset_all(e);
e = e.next;
}
}
var eager_effects = new Set();
var old_values = new Map();
var eager_effects_deferred = false;
function source(v, stack) {
return {
f: 0,
v,
reactions: null,
equals,
rv: 0,
wv: 0
};
}
function state(v, stack) {
const s = source(v, stack);
push_reaction_value(s);
return s;
}
function mutable_source(initial_value, immutable = false, trackable = true) {
const s = source(initial_value);
if (!immutable) s.equals = safe_equals;
if (legacy_mode_flag && trackable && component_context !== null && component_context.l !== null) (component_context.l.s ??= []).push(s);
return s;
}
function set(source, value, should_proxy = false) {
if (active_reaction !== null && (!untracking || (active_reaction.f & 131072) !== 0) && is_runes() && (active_reaction.f & 4325394) !== 0 && (current_sources === null || !current_sources.has(source))) state_unsafe_mutation();
return internal_set(source, should_proxy ? proxy(value) : value, legacy_updates);
}
var seen = null;
var count_deps = 0;
function internal_set(source, value, updated_during_traversal = null) {
if (!source.equals(value)) {
if (is_destroying_effect) old_values.set(source, value);
else if (!old_values.has(source)) old_values.set(source, source.v);
var batch = Batch.ensure();
batch.capture(source, value);
if ((source.f & 2) !== 0) {
const derived = source;
if ((source.f & 2048) !== 0) execute_derived(derived);
if (batch_values === null) update_derived_status(derived);
}
source.wv = increment_write_version();
seen = null;
count_deps = 0;
mark_reactions(source, DIRTY, updated_during_traversal);
seen = null;
if (is_runes() && active_effect !== null && (active_effect.f & 1024) !== 0 && (active_effect.f & 96) === 0) {
if (untracked_writes === null) set_untracked_writes([source]);
else untracked_writes.push(source);
}
if (!batch.is_fork && eager_effects.size > 0 && !eager_effects_deferred) flush_eager_effects();
}
return value;
}
function flush_eager_effects() {
eager_effects_deferred = false;
for (const effect of eager_effects) {
if ((effect.f & 1024) !== 0) set_signal_status(effect, MAYBE_DIRTY);
let dirty;
try {
dirty = is_dirty(effect);
} catch {
dirty = true;
}
if (dirty) update_effect(effect);
}
eager_effects.clear();
}
function increment(source) {
set(source, source.v + 1);
}
function mark_reactions(signal, status, updated_during_traversal) {
var reactions = signal.reactions;
if (reactions === null) return;
var runes = is_runes();
var length = reactions.length;
count_deps += length;
if (count_deps > 1e5 && seen === null) seen = new Set();
if (seen !== null) {
if (seen.has(signal)) return;
seen.add(signal);
}
for (var i = 0; i < length; i++) {
var reaction = reactions[i];
var flags = reaction.f;
if (!runes && reaction === active_effect) continue;
var not_dirty = (flags & DIRTY) === 0;
if (not_dirty) set_signal_status(reaction, status);
if ((flags & 131072) !== 0) eager_effects.add(reaction);
else if ((flags & 2) !== 0) {
var derived = reaction;
batch_values?.delete(derived);
mark_reactions(derived, MAYBE_DIRTY, updated_during_traversal);
} else if (not_dirty) {
var effect = reaction;
if ((flags & 16) !== 0 && eager_block_effects !== null) eager_block_effects.add(effect);
if (updated_during_traversal !== null) updated_during_traversal.push(effect);
else schedule_effect(effect);
}
}
}
function proxy(value) {
if (typeof value !== "object" || value === null || STATE_SYMBOL in value || COMPONENT_SYMBOL in value) return value;
const prototype = get_prototype_of(value);
if (prototype !== object_prototype && prototype !== array_prototype) return value;
var sources = new Map();
var is_proxied_array = is_array(value);
var version = state(0);
var stack = null;
var parent_version = update_version;
var with_parent = (fn) => {
if (update_version === parent_version) return fn();
var reaction = active_reaction;
var version = update_version;
set_active_reaction(null);
set_update_version(parent_version);
var result = fn();
set_active_reaction(reaction);
set_update_version(version);
return result;
};
if (is_proxied_array) sources.set("length", state(value.length, stack));
return new Proxy(value, {
defineProperty(_, prop, descriptor) {
if (!("value" in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) state_descriptors_fixed();
var s = sources.get(prop);
if (s === void 0) with_parent(() => {
var s = state(descriptor.value, stack);
sources.set(prop, s);
return s;
});
else set(s, descriptor.value, true);
return true;
},
deleteProperty(target, prop) {
var s = sources.get(prop);
if (s === void 0) {
if (prop in target) {
const s = with_parent(() => state(UNINITIALIZED, stack));
sources.set(prop, s);
increment(version);
}
} else {
set(s, UNINITIALIZED);
increment(version);
}
return true;
},
get(target, prop, receiver) {
if (prop === STATE_SYMBOL) return value;
var s = sources.get(prop);
var exists = prop in target;
if (s === void 0 && (!exists || get_descriptor(target, prop)?.writable)) {
s = with_parent(() => {
return state(proxy(exists ? target[prop] : UNINITIALIZED), stack);
});
sources.set(prop, s);
}
if (s !== void 0) {
var v = get(s);
return v === UNINITIALIZED ? void 0 : v;
}
return Reflect.get(target, prop, receiver);
},
getOwnPropertyDescriptor(target, prop) {
this.has?.(target, prop);
var descriptor = Reflect.getOwnPropertyDescriptor(target, prop);
var s = sources.get(prop);
if (s !== void 0) {
var value = get(s);
if (value === UNINITIALIZED) return;
if (descriptor && "value" in descriptor) descriptor.value = value;
else return {
enumerable: true,
configurable: true,
value,
writable: true
};
}
return descriptor;
},
has(target, prop) {
if (prop === STATE_SYMBOL) return true;
var s = sources.get(prop);
var has = s !== void 0 && s.v !== UNINITIALIZED || Reflect.has(target, prop);
if (s !== void 0 || (active_effect !== null || active_reaction !== null) && (!has || get_descriptor(target, prop)?.writable)) {
if (s === void 0) {
s = with_parent(() => {
return state(has ? proxy(target[prop]) : UNINITIALIZED, stack);
});
sources.set(prop, s);
}
if (get(s) === UNINITIALIZED) return false;
}
return has;
},
set(target, prop, value, receiver) {
var s = sources.get(prop);
var has = prop in target;
if (is_proxied_array && prop === "length") for (var i = value; i < s.v; i += 1) {
var other_s = sources.get(i + "");
if (other_s !== void 0) set(other_s, UNINITIALIZED);
else if (i in target) {
other_s = with_parent(() => state(UNINITIALIZED, stack));
sources.set(i + "", other_s);
}
}
if (s === void 0) {
if (!has || get_descriptor(target, prop)?.writable) {
s = with_parent(() => state(void 0, stack));
set(s, proxy(value));
sources.set(prop, s);
}
} else {
has = s.v !== UNINITIALIZED;
var p = with_parent(() => proxy(value));
set(s, p);
}
var descriptor = Reflect.getOwnPropertyDescriptor(target, prop);
if (descriptor?.set) descriptor.set.call(receiver, value);
if (!has) {
if (is_proxied_array && typeof prop === "string") {
var ls = sources.get("length");
var n = Number(prop);
if (Number.isInteger(n) && n >= ls.v) set(ls, n + 1);
}
increment(version);
}
return true;
},
ownKeys(target) {
get(version);
var own_keys = Reflect.ownKeys(target).filter((key) => {
var source = sources.get(key);
return source === void 0 || source.v !== UNINITIALIZED;
});
for (var [key, source] of sources) if (source.v !== UNINITIALIZED && !(key in target)) own_keys.push(key);
return own_keys;
},
setPrototypeOf() {
state_prototype_fixed();
}
});
}
function get_proxied_value(value) {
try {
if (value !== null && typeof value === "object" && STATE_SYMBOL in value) return value[STATE_SYMBOL];
} catch {}
return value;
}
function is(a, b) {
return Object.is(get_proxied_value(a), get_proxied_value(b));
}
var $window;
var is_firefox;
var first_child_getter;
var next_sibling_getter;
function init_operations() {
if ($window !== void 0) return;
$window = window;
is_firefox = /Firefox/.test(navigator.userAgent);
var element_prototype = Element.prototype;
var node_prototype = Node.prototype;
var text_prototype = Text.prototype;
first_child_getter = get_descriptor(node_prototype, "firstChild").get;
next_sibling_getter = get_descriptor(node_prototype, "nextSibling").get;
if (is_extensible(element_prototype)) {
element_prototype[CLASS_CACHE] = void 0;
element_prototype[ATTRIBUTES_CACHE] = null;
element_prototype[STYLE_CACHE] = void 0;
element_prototype.__e = void 0;
}
if (is_extensible(text_prototype)) text_prototype[TEXT_CACHE] = void 0;
}
function create_text(value = "") {
return document.createTextNode(value);
}
function get_first_child(node) {
return first_child_getter.call(node);
}
function get_next_sibling(node) {
return next_sibling_getter.call(node);
}
function child(node, is_text) {
if (!hydrating) return get_first_child(node);
var child = get_first_child(hydrate_node);
if (child === null) child = hydrate_node.appendChild(create_text());
else if (is_text && child.nodeType !== 3) {
var text = create_text();
child?.before(text);
set_hydrate_node(text);
return text;
}
if (is_text) merge_text_nodes(child);
set_hydrate_node(child);
return child;
}
function first_child(node, is_text = false) {
if (!hydrating) {
var first = get_first_child(node);
if (first instanceof Comment && first.data === "") return get_next_sibling(first);
return first;
}
if (is_text) {
if (hydrate_node?.nodeType !== 3) {
var text = create_text();
hydrate_node?.before(text);
set_hydrate_node(text);
return text;
}
merge_text_nodes(hydrate_node);
}
return hydrate_node;
}
function only_child(node, is_text = false) {
if (!hydrating) return get_first_child(node);
var first = child(node, is_text);
reset(node);
return first;
}
function sibling(node, count = 1, is_text = false) {
let next_sibling = hydrating ? hydrate_node : node;
var last_sibling;
while (count--) {
last_sibling = next_sibling;
next_sibling = get_next_sibling(next_sibling);
}
if (!hydrating) return next_sibling;
if (is_text) {
if (next_sibling?.nodeType !== 3) {
var text = create_text();
if (next_sibling === null) last_sibling?.after(text);
else next_sibling.before(text);
set_hydrate_node(text);
return text;
}
merge_text_nodes(next_sibling);
}
set_hydrate_node(next_sibling);
return next_sibling;
}
function clear_text_content(node) {
node.textContent = "";
}
function should_defer_append() {
if (!async_mode_flag) return false;
if (eager_block_effects !== null) return false;
return (active_effect.f & REACTION_RAN) !== 0;
}
function create_element(tag, namespace, is) {
if (namespace == null || namespace === "http://www.w3.org/1999/xhtml") return is ? document.createElement(tag, { is }) : document.createElement(tag);
return is ? document.createElementNS(namespace, tag, { is }) : document.createElementNS(namespace, tag);
}
function merge_text_nodes(text) {
if (text.nodeValue.length < 65536) return;
let next = text.nextSibling;
while (next !== null && next.nodeType === 3) {
next.remove();
text.nodeValue += next.nodeValue;
next = text.nextSibling;
}
}
function handle_error(error) {
var effect = active_effect;
if (effect === null) {
active_reaction.f |= ERROR_VALUE;
return error;
}
if ((effect.f & 32768) === 0 && (effect.f & 4) === 0) throw error;
invoke_error_boundary(error, effect);
}
function invoke_error_boundary(error, effect) {
if (error === HYDRATION_ERROR) throw error;
if (effect !== null && (effect.f & 16384) !== 0) return;
while (effect !== null) {
if ((effect.f & 128) !== 0 && (effect.f & 33570816) === 0) {
if ((effect.f & 32768) === 0) throw error;
try {
effect.b.error(error);
return;
} catch (e) {
error = e;
}
}
effect = effect.parent;
}
throw error;
}
function push_effect(effect, parent_effect) {
var parent_last = parent_effect.last;
if (parent_last === null) parent_effect.last = parent_effect.first = effect;
else {
parent_last.next = effect;
effect.prev = parent_last;
parent_effect.last = effect;
}
}
function create_effect(type, fn) {
var parent = active_effect;
if (parent !== null && (parent.f & 8192) !== 0) type |= INERT;
var effect = {
ctx: component_context,
deps: null,
nodes: null,
f: type | DIRTY | 512,
first: null,
fn,
last: null,
next: null,
parent,
b: parent && parent.b,
prev: null,
teardown: null,
wv: 0,
ac: null
};
current_batch?.register_created_effect(effect);
var e = effect;
if ((type & 4) !== 0) {
if (collected_effects !== null) collected_effects.push(effect);
else Batch.ensure().schedule(effect);
} else if (fn !== null) {
try {
update_effect(effect);
} catch (e) {
destroy_effect(effect);
throw e;
}
if (e.deps === null && e.teardown === null && e.nodes === null && e.first === e.last && (e.f & 524288) === 0) {
e = e.first;
if ((type & 16) !== 0 && (type & 65536) !== 0 && e !== null) e.f |= EFFECT_TRANSPARENT;
}
}
if (e !== null) {
e.parent = parent;
if (parent !== null) push_effect(e, parent);
if (active_reaction !== null && (active_reaction.f & 2) !== 0 && (type & 64) === 0) {
var derived = active_reaction;
(derived.effects ??= []).push(e);
}
}
return effect;
}
function effect_tracking() {
return active_reaction !== null && !untracking;
}
function teardown(fn) {
const effect = create_effect(8, null);
set_signal_status(effect, CLEAN);
effect.teardown = fn;
return effect;
}
function create_user_effect(fn) {
return create_effect(4 | USER_EFFECT, fn);
}
function component_root(fn) {
Batch.ensure();
const effect = create_effect(64 | EFFECT_PRESERVED, fn);
return (options = {}) => {
return new Promise((fulfil) => {
if (options.outro) pause_effect(effect, () => {
destroy_effect(effect);
fulfil(void 0);
});
else {
destroy_effect(effect);
fulfil(void 0);
}
});
};
}
function effect(fn) {
return create_effect(4, fn);
}
function async_effect(fn) {
return create_effect(ASYNC | EFFECT_PRESERVED, fn);
}
function render_effect(fn, flags = 0) {
return create_effect(8 | flags, fn);
}
function template_effect(fn, sync = [], async = [], blockers = []) {
flatten(blockers, sync, async, (values) => {
create_effect(8, () => {
fn(...values.map(get));
});
});
}
function block(fn, flags = 0) {
return create_effect(16 | flags, fn);
}
function branch(fn) {
return create_effect(32 | EFFECT_PRESERVED, fn);
}
function execute_effect_teardown(effect) {
var teardown = effect.teardown;
if (teardown !== null) {
const previously_destroying_effect = is_destroying_effect;
const previous_reaction = active_reaction;
set_is_destroying_effect(true);
set_active_reaction(null);
try {
teardown.call(null);
} catch (error) {
invoke_error_boundary(error, effect.parent);
} finally {
set_is_destroying_effect(previously_destroying_effect);
set_active_reaction(previous_reaction);
}
}
}
function destroy_effect_children(signal, remove_dom = false) {
var effect = signal.first;
signal.first = signal.last = null;
while (effect !== null) {
const controller = effect.ac;
if (controller !== null) without_reactive_context(() => {
controller.abort(STALE_REACTION);
});
var next = effect.next;
if ((effect.f & 64) !== 0) effect.parent = null;
else destroy_effect(effect, remove_dom);
effect = next;
}
}
function destroy_block_effect_children(signal) {
var effect = signal.first;
while (effect !== null) {
var next = effect.next;
if ((effect.f & 32) === 0) destroy_effect(effect);
effect = next;
}
}
function destroy_effect(effect, remove_dom = true) {
var removed = false;
if ((remove_dom || (effect.f & 262144) !== 0) && effect.nodes !== null && effect.nodes.end !== null) {
remove_effect_dom(effect.nodes.start, effect.nodes.end);
removed = true;
}
effect.f |= DESTROYING;
destroy_effect_children(effect, remove_dom && !removed);
remove_reactions(effect, 0);
var transitions = effect.nodes && effect.nodes.t;
if (transitions !== null) for (const transition of transitions) transition.stop();
execute_effect_teardown(effect);
effect.f ^= DESTROYING;
effect.f |= DESTROYED;
var parent = effect.parent;
if (parent !== null && parent.first !== null) unlink_effect(effect);
effect.next = effect.prev = effect.teardown = effect.ctx = effect.deps = effect.fn = effect.nodes = effect.ac = effect.b = null;
}
function remove_effect_dom(node, end) {
while (node !== null) {
var next = node === end ? null : get_next_sibling(node);
node.remove();
node = next;
}
}
function unlink_effect(effect) {
var parent = effect.parent;
var prev = effect.prev;
var next = effect.next;
if (prev !== null) prev.next = next;
if (next !== null) next.prev = prev;
if (parent !== null) {
if (parent.first === effect) parent.first = next;
if (parent.last === effect) parent.last = prev;
}
}
function pause_effect(effect, callback, destroy = true) {
var transitions = [];
effect.f |= 256;
pause_children(effect, transitions, true);
var fn = () => {
if (destroy) destroy_effect(effect);
if (callback) callback();
};
var remaining = transitions.length;
if (remaining > 0) {
var check = () => --remaining || fn();
for (var transition of transitions) transition.out(check);
} else fn();
}
function pause_children(effect, transitions, local) {
if ((effect.f & 8192) !== 0) return;
effect.f ^= INERT;
var t = effect.nodes && effect.nodes.t;
if (t !== null) {
for (const transition of t) if (transition.is_global || local) transitions.push(transition);
}
var child = effect.first;
while (child !== null) {
var sibling = child.next;
if ((child.f & 64) === 0) {
var transparent = (child.f & 65536) !== 0 || (child.f & 32) !== 0 && (effect.f & 16) !== 0;
pause_children(child, transitions, transparent ? local : false);
}
child = sibling;
}
}
function resume_effect(effect) {
effect.f &= -257;
resume_children(effect, true);
}
function resume_children(effect, local) {
if ((effect.f & 256) !== 0) return;
if ((effect.f & 8192) === 0) return;
effect.f ^= INERT;
if ((effect.f & 1024) === 0) {
set_signal_status(effect, DIRTY);
Batch.ensure().schedule(effect);
}
var child = effect.first;
while (child !== null) {
var sibling = child.next;
var transparent = (child.f & 65536) !== 0 || (child.f & 32) !== 0;
resume_children(child, transparent ? local : false);
child = sibling;
}
var t = effect.nodes && effect.nodes.t;
if (t !== null) {
for (const transition of t) if (transition.is_global || local) transition.in();
}
}
function move_effect(effect, fragment) {
if (!effect.nodes) return;
var node = effect.nodes.start;
var end = effect.nodes.end;
while (node !== null) {
var next = node === end ? null : get_next_sibling(node);
fragment.append(node);
node = next;
}
}
var captured_signals = null;
var is_destroying_effect = false;
function set_is_destroying_effect(value) {
is_destroying_effect = value;
}
var active_reaction = null;
var untracking = false;
function set_active_reaction(reaction) {
active_reaction = reaction;
}
var active_effect = null;
function set_active_effect(effect) {
active_effect = effect;
}
var current_sources = null;
function push_reaction_value(value) {
if (active_reaction !== null && (!async_mode_flag && (active_reaction.f & 2097152) !== 0 || (active_reaction.f & 2) !== 0)) (current_sources ??= new Set()).add(value);
}
var new_deps = null;
var skipped_deps = 0;
var untracked_writes = null;
function set_untracked_writes(value) {
untracked_writes = value;
}
var write_version = 1;
var read_version = 0;
var update_version = read_version;
function set_update_version(value) {
update_version = value;
}
function increment_write_version() {
return ++write_version;
}
function is_dirty(reaction) {
var flags = reaction.f;
if ((flags & 2048) !== 0) return true;
if ((flags & 4096) !== 0) {
var dependencies = reaction.deps;
var length = dependencies.length;
for (var i = 0; i < length; i++) {
var dependency = dependencies[i];
if (is_dirty(dependency)) update_derived(dependency);
if (dependency.wv > reaction.wv) return true;
}
if ((flags & 512) !== 0 && batch_values === null) set_signal_status(reaction, CLEAN);
}
return false;
}
function schedule_possible_effect_self_invalidation(signal, effect, root = true) {
var reactions = signal.reactions;
if (reactions === null) return;
if (!async_mode_flag && current_sources !== null && current_sources.has(signal)) return;
for (var i = 0; i < reactions.length; i++) {
var reaction = reactions[i];
if ((reaction.f & 2) !== 0) schedule_possible_effect_self_invalidation(reaction, effect, false);
else if (effect === reaction) {
if (root) set_signal_status(reaction, DIRTY);
else if ((reaction.f & 1024) !== 0) set_signal_status(reaction, MAYBE_DIRTY);
schedule_effect(reaction);
}
}
}
function update_reaction(reaction) {
var previous_deps = new_deps;
var previous_skipped_deps = skipped_deps;
var previous_untracked_writes = untracked_writes;
var previous_reaction = active_reaction;
var previous_sources = current_sources;
var previous_component_context = component_context;
var previous_untracking = untracking;
var previous_update_version = update_version;
var flags = reaction.f;
new_deps = null;
skipped_deps = 0;
untracked_writes = null;
active_reaction = (flags & 96) === 0 ? reaction : null;
current_sources = null;
set_component_context(reaction.ctx);
untracking = false;
update_version = ++read_version;
if (reaction.ac !== null) {
without_reactive_context(() => {
reaction.ac.abort(STALE_REACTION);
});
reaction.ac = null;
}
try {
reaction.f |= REACTION_IS_UPDATING;
var fn = reaction.fn;
var result = fn();
reaction.f |= REACTION_RAN;
var deps = update_dependencies(reaction);
if (is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & 6146) === 0) for (var i = 0; i < untracked_writes.length; i++) schedule_possible_effect_self_invalidation(untracked_writes[i], reaction);
if (previous_reaction !== null && previous_reaction !== reaction) {
read_version++;
if (previous_reaction.deps !== null) for (let i = 0; i < previous_skipped_deps; i += 1) previous_reaction.deps[i].rv = read_version;
if (previous_deps !== null) for (const dep of previous_deps) dep.rv = read_version;
if (untracked_writes !== null) {
if (previous_untracked_writes === null) previous_untracked_writes = untracked_writes;
else previous_untracked_writes.push(...untracked_writes);
}
}
if ((reaction.f & 8388608) !== 0) reaction.f ^= ERROR_VALUE;
return result;
} catch (error) {
update_dependencies(reaction);
return handle_error(error);
} finally {
reaction.f ^= REACTION_IS_UPDATING;
new_deps = previous_deps;
skipped_deps = previous_skipped_deps;
untracked_writes = previous_untracked_writes;
active_reaction = previous_reaction;
current_sources = previous_sources;
set_component_context(previous_component_context);
untracking = previous_untracking;
update_version = previous_update_version;
}
}
function update_dependencies(reaction) {
var deps = reaction.deps;
var is_fork = current_batch?.is_fork;
if (new_deps !== null) {
var i;
if (!is_fork) remove_reactions(reaction, skipped_deps);
if (deps !== null && skipped_deps > 0) {
deps.length = skipped_deps + new_deps.length;
for (i = 0; i < new_deps.length; i++) deps[skipped_deps + i] = new_deps[i];
} else reaction.deps = deps = new_deps;
if (effect_tracking() && (reaction.f & 512) !== 0) for (i = skipped_deps; i < deps.length; i++) (deps[i].reactions ??= []).push(reaction);
} else if (!is_fork && deps !== null && skipped_deps < deps.length) {
remove_reactions(reaction, skipped_deps);
deps.length = skipped_deps;
}
return deps;
}
function remove_reaction(signal, dependency) {
let reactions = dependency.reactions;
if (reactions !== null) {
var index = index_of.call(reactions, signal);
if (index !== -1) {
var new_length = reactions.length - 1;
if (new_length === 0) reactions = dependency.reactions = null;
else {
reactions[index] = reactions[new_length];
reactions.pop();
}
}
}
if (reactions === null && (dependency.f & 2) !== 0 && (new_deps === null || !includes.call(new_deps, dependency))) {
var derived = dependency;
if ((derived.f & 512) !== 0) derived.f ^= 512;
if (derived.v !== UNINITIALIZED) update_derived_status(derived);
if (derived.ac !== null) without_reactive_context(() => {
derived.ac.abort(STALE_REACTION);
derived.ac = null;
set_signal_status(derived, DIRTY);
});
freeze_derived_effects(derived);
remove_reactions(derived, 0);
}
}
function remove_reactions(signal, start_index) {
var dependencies = signal.deps;
if (dependencies === null) return;
for (var i = start_index; i < dependencies.length; i++) remove_reaction(signal, dependencies[i]);
}
function update_effect(effect) {
var flags = effect.f;
if ((flags & 16384) !== 0) return;
set_signal_status(effect, CLEAN);
var previous_effect = active_effect;
active_effect = effect;
try {
if ((flags & 16777232) !== 0) destroy_block_effect_children(effect);
else destroy_effect_children(effect);
execute_effect_teardown(effect);
var teardown = update_reaction(effect);
effect.teardown = typeof teardown === "function" ? teardown : null;
effect.wv = write_version;
} finally {
active_effect = previous_effect;
}
}
async function tick() {
if (async_mode_flag) return new Promise((f) => {
requestAnimationFrame(() => f());
setTimeout(() => f());
});
await Promise.resolve();
flushSync();
}
function get(signal) {
var is_derived = (signal.f & 2) !== 0;
captured_signals?.add(signal);
if (active_reaction !== null && !untracking) {
if (!(active_effect !== null && (active_effect.f & 16384) !== 0) && (current_sources === null || !current_sources.has(signal))) {
var deps = active_reaction.deps;
if ((active_reaction.f & 2097152) !== 0) {
if (signal.rv < read_version) {
signal.rv = read_version;
if (new_deps === null && deps !== null && deps[skipped_deps] === signal) skipped_deps++;
else if (new_deps === null) new_deps = [signal];
else new_deps.push(signal);
}
} else {
active_reaction.deps ??= [];
if (!includes.call(active_reaction.deps, signal)) active_reaction.deps.push(signal);
var reactions = signal.reactions;
if (reactions === null) signal.reactions = [active_reaction];
else if (!includes.call(reactions, active_reaction)) reactions.push(active_reaction);
}
}
}
if (is_destroying_effect && old_values.has(signal)) return old_values.get(signal);
if (is_derived) {
var derived = signal;
if (is_destroying_effect) {
var value = derived.v;
if ((derived.f & 1024) === 0 && derived.reactions !== null || depends_on_old_values(derived)) value = execute_derived(derived);
old_values.set(derived, value);
return value;
}
var should_connect = (derived.f & 512) === 0 && !untracking && active_reaction !== null && (active_reaction.f & 512) !== 0;
var is_new = (derived.f & REACTION_RAN) === 0;
if (is_dirty(derived)) {
if (should_connect) derived.f |= 512;
update_derived(derived);
}
if (should_connect && !is_new) {
unfreeze_derived_effects(derived);
reconnect(derived);
}
}
if (batch_values?.has(signal)) return batch_values.get(signal);
if ((signal.f & 8388608) !== 0) throw signal.v;
return signal.v;
}
function reconnect(derived) {
derived.f |= 512;
if (derived.deps === null) return;
for (const dep of derived.deps) {
var reactions = dep.reactions;
if (reactions === null) dep.reactions = [derived];
else if (!includes.call(reactions, derived)) reactions.push(derived);
if ((dep.f & 2) !== 0 && (dep.f & 512) === 0) {
unfreeze_derived_effects(dep);
reconnect(dep);
}
}
}
function depends_on_old_values(derived) {
if (derived.v === UNINITIALIZED) return true;
if (derived.deps === null) return false;
for (const dep of derived.deps) {
if (old_values.has(dep)) return true;
if ((dep.f & 2) !== 0 && depends_on_old_values(dep)) return true;
}
return false;
}
function untrack(fn) {
var previous_untracking = untracking;
try {
untracking = true;
return fn();
} finally {
untracking = previous_untracking;
}
}
var PASSIVE_EVENTS = ["touchstart", "touchmove"];
function is_passive_event(name) {
return PASSIVE_EVENTS.includes(name);
}
var event_symbol = Symbol("events");
var all_registered_events = new Set();
var root_event_handles = new Set();
function create_event(event_name, dom, handler, options = {}) {
function target_handler(event) {
if (!options.capture) handle_event_propagation.call(dom, event);
if (!event.cancelBubble) return without_reactive_context(() => {
return handler?.call(this, event);
});
}
if (event_name.startsWith("pointer") || event_name.startsWith("touch") || event_name === "wheel") {
target_handler.__removed = false;
queue_micro_task(() => {
if (!target_handler.__removed) dom.addEventListener(event_name, target_handler, options);
});
} else dom.addEventListener(event_name, target_handler, options);
return target_handler;
}
function event(event_name, dom, handler, capture, passive) {
var options = {
capture,
passive
};
var target_handler = create_event(event_name, dom, handler, options);
if (dom === document.body || dom === window || dom === document || dom instanceof HTMLMediaElement) teardown(() => {
target_handler.__removed = true;
dom.removeEventListener(event_name, target_handler, options);
});
}
function delegated(event_name, element, handler) {
(element[event_symbol] ??= {})[event_name] = handler;
}
function delegate(events) {
for (var i = 0; i < events.length; i++) all_registered_events.add(events[i]);
for (var fn of root_event_handles) fn(events);
}
var last_propagated_event = null;
var last_propagated_event_clear_scheduled = false;
function handle_event_propagation(event) {
var handler_element = this;
var owner_document = handler_element.ownerDocument;
var event_name = event.type;
var path = event.composedPath?.() || [];
var current_target = path[0] || event.target;
last_propagated_event = event;
if (!last_propagated_event_clear_scheduled) {
last_propagated_event_clear_scheduled = true;
setTimeout(() => {
last_propagated_event_clear_scheduled = false;
last_propagated_event = null;
});
}
var path_idx = 0;
var handled_at = last_propagated_event === event && event[event_symbol];
if (handled_at) {
var at_idx = path.indexOf(handled_at);
if (at_idx !== -1 && (handler_element === document || handler_element === window)) {
event[event_symbol] = handler_element;
return;
}
var handler_idx = path.indexOf(handler_element);
if (handler_idx === -1) return;
if (at_idx <= handler_idx) path_idx = at_idx;
}
current_target = path[path_idx] || event.target;
if (current_target === handler_element) return;
define_property(event, "currentTarget", {
configurable: true,
get() {
return current_target || owner_document;
}
});
var previous_reaction = active_reaction;
var previous_effect = active_effect;
set_active_reaction(null);
set_active_effect(null);
try {
var throw_error;
var other_errors = [];
while (current_target !== null) {
if (current_target === handler_element) break;
try {
var delegated = current_target[event_symbol]?.[event_name];
if (delegated != null && (!current_target.disabled || event.target === current_target)) delegated.call(current_target, event);
} catch (error) {
if (throw_error) other_errors.push(error);
else throw_error = error;
}
if (event.cancelBubble) break;
path_idx++;
current_target = path_idx < path.length ? path[path_idx] : null;
}
if (throw_error) {
for (let error of other_errors) queueMicrotask(() => {
throw error;
});
throw throw_error;
}
} finally {
event[event_symbol] = handler_element;
delete event.currentTarget;
set_active_reaction(previous_reaction);
set_active_effect(previous_effect);
}
}
var policy = globalThis?.window?.trustedTypes && globalThis.window.trustedTypes.createPolicy("svelte-trusted-html", { createHTML: (html) => {
return html;
} });
function create_trusted_html(html) {
return policy?.createHTML(html) ?? html;
}
function create_fragment_from_html(html) {
var elem = create_element("template");
elem.innerHTML = create_trusted_html(html.replaceAll("", ""));
return elem.content;
}
function assign_nodes(start, end) {
var effect = active_effect;
if (effect.nodes === null) effect.nodes = {
start,
end,
a: null,
t: null
};
}
function from_html(content, flags) {
var is_fragment = (flags & 1) !== 0;
var use_import_node = (flags & 2) !== 0;
var node;
var has_start = !content.startsWith("");
return () => {
if (hydrating) {
assign_nodes(hydrate_node, null);
return hydrate_node;
}
if (node === void 0) {
node = create_fragment_from_html(has_start ? content : "" + content);
if (!is_fragment) node = get_first_child(node);
}
var clone = use_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true);
if (is_fragment) {
var start = get_first_child(clone);
var end = clone.lastChild;
assign_nodes(start, end);
} else assign_nodes(clone, clone);
return clone;
};
}
function text(value = "") {
if (!hydrating) {
var t = create_text(value + "");
assign_nodes(t, t);
return t;
}
var node = hydrate_node;
if (node.nodeType !== 3) {
node.before(node = create_text());
set_hydrate_node(node);
} else merge_text_nodes(node);
assign_nodes(node, node);
return node;
}
function comment() {
if (hydrating) {
assign_nodes(hydrate_node, null);
return hydrate_node;
}
var frag = document.createDocumentFragment();
var start = document.createComment("");
var anchor = create_text();
frag.append(start, anchor);
assign_nodes(start, anchor);
return frag;
}
function append(anchor, dom) {
if (hydrating) {
var effect = active_effect;
if ((effect.f & 32768) === 0 || effect.nodes.end === null) effect.nodes.end = hydrate_node;
hydrate_next();
return;
}
if (anchor === null) return;
anchor.before(dom);
}
function createSubscriber(start) {
let subscribers = 0;
let version = source(0);
let stop;
return () => {
if (effect_tracking()) {
get(version);
render_effect(() => {
if (subscribers === 0) stop = untrack(() => start(() => increment(version)));
subscribers += 1;
return () => {
queue_micro_task(() => {
subscribers -= 1;
if (subscribers === 0) {
stop?.();
stop = void 0;
increment(version);
}
});
};
});
}
};
}
var flags = EFFECT_TRANSPARENT | EFFECT_PRESERVED;
function boundary(node, props, children, transform_error) {
new Boundary(node, props, children, transform_error);
}
var Boundary = class {
parent;
is_pending = false;
transform_error;
#anchor;
#hydrate_open = hydrating ? hydrate_node : null;
#props;
#children;
#effect;
#main_effect = null;
#pending_effect = null;
#failed_effect = null;
#offscreen_fragment = null;
#local_pending_count = 0;
#pending_count = 0;
#pending_count_update_queued = false;
#dirty_reactions = new Map();
#effect_pending = null;
#effect_pending_subscriber = createSubscriber(() => {
this.#effect_pending = source(this.#local_pending_count);
return () => {
this.#effect_pending = null;
};
});
constructor(node, props, children, transform_error) {
this.#anchor = node;
this.#props = props;
this.#children = (anchor) => {
var effect = active_effect;
effect.b = this;
effect.f |= 128;
children(anchor);
};
this.parent = active_effect.b;
this.transform_error = transform_error ?? this.parent?.transform_error ?? ((e) => e);
this.#effect = block(() => {
if (hydrating) {
const comment_data = read_hydration_instruction(this.#hydrate_open);
hydrate_next();
const server_rendered_pending = comment_data === "[!";
if (comment_data.startsWith("[?")) {
const serialized_error = JSON.parse(comment_data.slice(2));
this.#hydrate_failed_content(serialized_error);
} else if (server_rendered_pending) this.#hydrate_pending_content();
else this.#hydrate_resolved_content();
} else this.#render();
}, flags);
if (hydrating) this.#anchor = hydrate_node;
}
#hydrate_resolved_content() {
try {
this.#main_effect = branch(() => this.#children(this.#anchor));
} catch (error) {
this.error(error);
}
}
#hydrate_failed_content(error) {
const failed = this.#props.failed;
const { reset, invoke_onerror } = this.#create_reset(error);
queue_micro_task(invoke_onerror);
if (!failed) return;
this.#failed_effect = branch(() => {
failed(this.#anchor, () => error, () => reset);
});
}
#create_reset(error) {
var did_reset = false;
var calling_on_error = false;
const reset = () => {
if (this.#is_destroyed()) return;
if (did_reset) {
svelte_boundary_reset_noop();
return;
}
did_reset = true;
if (calling_on_error) svelte_boundary_reset_onerror();
if (this.#failed_effect !== null) pause_effect(this.#failed_effect, () => {
this.#failed_effect = null;
});
this.#run(() => {
this.#render();
});
};
const invoke_onerror = () => {
if (this.#is_destroyed()) return;
try {
calling_on_error = true;
this.#props.onerror?.(error, reset);
calling_on_error = false;
} catch (err) {
invoke_error_boundary(err, this.#effect && this.#effect.parent);
}
};
return {
reset,
invoke_onerror
};
}
#is_destroyed() {
return (this.#effect.f & (DESTROYED | DESTROYING)) !== 0;
}
#hydrate_pending_content() {
const pending = this.#props.pending;
if (!pending) return;
this.is_pending = true;
this.#pending_effect = branch(() => pending(this.#anchor));
queue_micro_task(() => {
if (this.#is_destroyed()) return;
var fragment = this.#offscreen_fragment = document.createDocumentFragment();
var anchor = create_text();
var handled = false;
fragment.append(anchor);
this.#main_effect = this.#run(() => {
try {
return branch(() => this.#children(anchor));
} catch (error) {
try {
this.error(error);
handled = true;
} catch (error) {
invoke_error_boundary(error, this.#effect.parent);
}
return null;
}
});
if (this.#main_effect === null) {
this.#offscreen_fragment = null;
if (handled) this.#resolve(current_batch);
return;
}
if (this.#pending_count === 0) {
this.#anchor.before(fragment);
this.#offscreen_fragment = null;
pause_effect(this.#pending_effect, () => {
this.#pending_effect = null;
});
this.#resolve(current_batch);
}
});
}
#render() {
try {
this.is_pending = this.has_pending_snippet();
this.#pending_count = 0;
this.#local_pending_count = 0;
this.#main_effect = branch(() => {
this.#children(this.#anchor);
});
if (this.#pending_count > 0) {
var fragment = this.#offscreen_fragment = document.createDocumentFragment();
move_effect(this.#main_effect, fragment);
const pending = this.#props.pending;
this.#pending_effect = branch(() => pending(this.#anchor));
} else this.#resolve(current_batch);
} catch (error) {
this.error(error);
}
}
#resolve(batch) {
this.is_pending = false;
batch.transfer_reactions(this.#dirty_reactions);
}
defer_effect(effect) {
defer_effect(effect, this.#dirty_reactions);
}
is_rendered() {
return !this.is_pending && (!this.parent || this.parent.is_rendered());
}
has_pending_snippet() {
return !!this.#props.pending;
}
#run(fn) {
var previous_effect = active_effect;
var previous_reaction = active_reaction;
var previous_ctx = component_context;
set_active_effect(this.#effect);
set_active_reaction(this.#effect);
set_component_context(this.#effect.ctx);
try {
Batch.ensure();
return fn();
} finally {
set_active_effect(previous_effect);
set_active_reaction(previous_reaction);
set_component_context(previous_ctx);
}
}
#update_pending_count(d, batch) {
if (!this.has_pending_snippet()) {
if (this.parent) this.parent.#update_pending_count(d, batch);
return;
}
this.#pending_count += d;
if (this.#pending_count === 0) {
this.#resolve(batch);
if (this.#pending_effect) pause_effect(this.#pending_effect, () => {
this.#pending_effect = null;
});
if (this.#offscreen_fragment) {
this.#anchor.before(this.#offscreen_fragment);
this.#offscreen_fragment = null;
}
}
}
update_pending_count(d, batch) {
this.#update_pending_count(d, batch);
this.#local_pending_count += d;
if (!this.#effect_pending || this.#pending_count_update_queued) return;
this.#pending_count_update_queued = true;
queue_micro_task(() => {
this.#pending_count_update_queued = false;
if (this.#effect_pending) internal_set(this.#effect_pending, this.#local_pending_count);
});
}
get_effect_pending() {
this.#effect_pending_subscriber();
return get(this.#effect_pending);
}
error(error) {
if (error === HYDRATION_ERROR) throw error;
if (!this.#props.onerror && !this.#props.failed) throw error;
if (current_batch?.is_fork) {
if (this.#main_effect) current_batch.skip_effect(this.#main_effect);
if (this.#pending_effect) current_batch.skip_effect(this.#pending_effect);
if (this.#failed_effect) current_batch.skip_effect(this.#failed_effect);
current_batch.oncommit(() => {
if (!this.#is_destroyed()) this.#handle_error(error);
});
} else this.#handle_error(error);
}
#handle_error(error) {
if (this.#main_effect) {
destroy_effect(this.#main_effect);
this.#main_effect = null;
}
if (this.#pending_effect) {
destroy_effect(this.#pending_effect);
this.#pending_effect = null;
}
if (this.#failed_effect) {
destroy_effect(this.#failed_effect);
this.#failed_effect = null;
}
if (hydrating) {
set_hydrate_node(this.#hydrate_open);
next();
set_hydrate_node(skip_nodes());
}
let failed = this.#props.failed;
const handle_error_result = (transformed_error) => {
if (this.#is_destroyed()) return;
const { reset, invoke_onerror } = this.#create_reset(transformed_error);
invoke_onerror();
if (failed && !this.#is_destroyed()) this.#failed_effect = this.#run(() => {
try {
return branch(() => {
var effect = active_effect;
effect.b = this;
effect.f |= 128;
failed(this.#anchor, () => transformed_error, () => reset);
});
} catch (error) {
invoke_error_boundary(error, this.#effect.parent);
return null;
}
});
};
queue_micro_task(() => {
if (this.#is_destroyed()) return;
var result;
try {
result = this.transform_error(error);
} catch (e) {
invoke_error_boundary(e, this.#effect && this.#effect.parent);
return;
}
if (result !== null && typeof result === "object" && typeof result.then === "function") result.then(handle_error_result, (e) => invoke_error_boundary(e, this.#effect && this.#effect.parent));
else handle_error_result(result);
});
}
};
function set_text(text, value) {
var str = value == null ? "" : typeof value === "object" ? `${value}` : value;
if (str !== (text[TEXT_CACHE] ??= text.nodeValue)) {
text[TEXT_CACHE] = str;
text.nodeValue = `${str}`;
}
}
function mount(component, options) {
return _mount(component, options);
}
var listeners = new Map();
function _mount(Component, { target, anchor, props = {}, events, context, intro = true, transformError }) {
init_operations();
var component = void 0;
var unmount = component_root(() => {
var anchor_node = anchor ?? target.appendChild(create_text());
boundary(anchor_node, { pending: () => {} }, (anchor_node) => {
push({});
var ctx = component_context;
if (context) ctx.c = context;
if (events) props.$$events = events;
if (hydrating) assign_nodes(anchor_node, null);
component = Component(anchor_node, props) || mark_as_component();
if (hydrating) {
active_effect.nodes.end = hydrate_node;
if (hydrate_node === null || hydrate_node.nodeType !== 8 || hydrate_node.data !== "]") {
hydration_mismatch();
throw HYDRATION_ERROR;
}
}
pop();
}, transformError);
var registered_events = new Set();
var event_handle = (events) => {
for (var i = 0; i < events.length; i++) {
var event_name = events[i];
if (registered_events.has(event_name)) continue;
registered_events.add(event_name);
var passive = is_passive_event(event_name);
for (const node of [target, document]) {
var counts = listeners.get(node);
if (counts === void 0) {
counts = new Map();
listeners.set(node, counts);
}
var count = counts.get(event_name);
if (count === void 0) {
node.addEventListener(event_name, handle_event_propagation, { passive });
counts.set(event_name, 1);
} else counts.set(event_name, count + 1);
}
}
};
event_handle(array_from(all_registered_events));
root_event_handles.add(event_handle);
return () => {
for (var event_name of registered_events) for (const node of [target, document]) {
var counts = listeners.get(node);
var count = counts.get(event_name);
if (--count == 0) {
node.removeEventListener(event_name, handle_event_propagation);
counts.delete(event_name);
if (counts.size === 0) listeners.delete(node);
} else counts.set(event_name, count);
}
root_event_handles.delete(event_handle);
if (anchor_node !== anchor) anchor_node.parentNode?.removeChild(anchor_node);
};
});
mounted_components.set(component, unmount);
return component;
}
var mounted_components = new WeakMap();
function unmount(component, options) {
const fn = mounted_components.get(component);
if (fn) {
mounted_components.delete(component);
return fn(options);
}
return Promise.resolve();
}
var BranchManager = class {
anchor;
#batches = new Map();
#onscreen = new Map();
#offscreen = new Map();
#outroing = new Set();
#transition = true;
constructor(anchor, transition = true) {
this.anchor = anchor;
this.#transition = transition;
}
#commit = (batch) => {
if (!this.#batches.has(batch)) return;
var key = this.#batches.get(batch);
var onscreen = this.#onscreen.get(key);
if (onscreen) {
resume_effect(onscreen);
this.#outroing.delete(key);
} else {
var offscreen = this.#offscreen.get(key);
if (offscreen) {
resume_effect(offscreen.effect);
this.#onscreen.set(key, offscreen.effect);
this.#offscreen.delete(key);
offscreen.fragment.lastChild.remove();
this.anchor.before(offscreen.fragment);
onscreen = offscreen.effect;
}
}
for (const [b, k] of this.#batches) {
this.#batches.delete(b);
if (b === batch) break;
const offscreen = this.#offscreen.get(k);
if (offscreen) {
destroy_effect(offscreen.effect);
this.#offscreen.delete(k);
}
}
for (const [k, effect] of this.#onscreen) {
if (k === key || this.#outroing.has(k)) continue;
const on_destroy = () => {
if (Array.from(this.#batches.values()).includes(k)) {
var fragment = document.createDocumentFragment();
move_effect(effect, fragment);
fragment.append(create_text());
this.#offscreen.set(k, {
effect,
fragment
});
} else destroy_effect(effect);
this.#outroing.delete(k);
this.#onscreen.delete(k);
};
if (this.#transition || !onscreen) {
this.#outroing.add(k);
pause_effect(effect, on_destroy, false);
} else on_destroy();
}
};
#discard = (batch) => {
this.#batches.delete(batch);
const keys = Array.from(this.#batches.values());
for (const [k, branch] of this.#offscreen) if (!keys.includes(k)) {
destroy_effect(branch.effect);
this.#offscreen.delete(k);
}
};
ensure(key, fn) {
var batch = current_batch;
var defer = should_defer_append();
if (fn && !this.#onscreen.has(key) && !this.#offscreen.has(key)) {
if (defer) {
var fragment = document.createDocumentFragment();
var target = create_text();
fragment.append(target);
this.#offscreen.set(key, {
effect: branch(() => fn(target)),
fragment
});
} else this.#onscreen.set(key, branch(() => fn(this.anchor)));
}
this.#batches.set(batch, key);
if (defer) {
for (const [k, effect] of this.#onscreen) if (k === key) batch.unskip_effect(effect);
else batch.skip_effect(effect);
for (const [k, branch] of this.#offscreen) if (k === key) batch.unskip_effect(branch.effect);
else batch.skip_effect(branch.effect);
batch.oncommit(this.#commit);
batch.ondiscard(this.#discard);
} else {
if (hydrating) this.anchor = hydrate_node;
this.#commit(batch);
}
}
};
function if_block(node, fn, elseif = false) {
var marker;
if (hydrating) {
marker = hydrate_node;
hydrate_next();
}
var branches = new BranchManager(node);
var flags = elseif ? EFFECT_TRANSPARENT : 0;
function update_branch(key, fn) {
if (hydrating) {
var data = read_hydration_instruction(marker);
if (key !== parseInt(data.substring(1))) {
var anchor = skip_nodes();
set_hydrate_node(anchor);
branches.anchor = anchor;
set_hydrating(false);
branches.ensure(key, fn);
set_hydrating(true);
return;
}
}
branches.ensure(key, fn);
}
block(() => {
var has_branch = false;
fn((fn, key = 0) => {
has_branch = true;
update_branch(key, fn);
});
if (!has_branch) update_branch(-1, null);
}, flags);
}
function index(_, i) {
return i;
}
function pause_effects(state, to_destroy, controlled_anchor) {
var transitions = [];
var length = to_destroy.length;
var group;
var remaining = to_destroy.length;
for (var i = 0; i < length; i++) {
let effect = to_destroy[i];
pause_effect(effect, () => {
if (group) {
group.pending.delete(effect);
group.done.add(effect);
if (group.pending.size === 0) {
var groups = state.outrogroups;
destroy_effects(state, array_from(group.done));
groups.delete(group);
if (groups.size === 0) state.outrogroups = null;
}
} else remaining -= 1;
}, false);
}
if (remaining === 0) {
var fast_path = transitions.length === 0 && controlled_anchor !== null && state.pending.size === 0;
if (fast_path) {
var anchor = controlled_anchor;
var parent_node = anchor.parentNode;
clear_text_content(parent_node);
parent_node.append(anchor);
state.items.clear();
}
destroy_effects(state, to_destroy, !fast_path);
} else {
group = {
pending: new Set(to_destroy),
done: new Set()
};
(state.outrogroups ??= new Set()).add(group);
}
}
function destroy_effects(state, to_destroy, remove_dom = true) {
var preserved_effects;
if (state.pending.size > 0) {
preserved_effects = new Set();
for (const keys of state.pending.values()) for (const key of keys) preserved_effects.add(state.items.get(key).e);
}
for (var i = 0; i < to_destroy.length; i++) {
var e = to_destroy[i];
if (preserved_effects?.has(e)) {
e.f |= EFFECT_OFFSCREEN;
move_effect(e, document.createDocumentFragment());
} else destroy_effect(to_destroy[i], remove_dom);
}
}
var offscreen_anchor;
function each(node, flags, get_collection, get_key, render_fn, fallback_fn = null) {
var anchor = node;
var items = new Map();
if ((flags & 4) !== 0) {
var parent_node = node;
anchor = hydrating ? set_hydrate_node(get_first_child(parent_node)) : parent_node.appendChild(create_text());
}
if (hydrating) hydrate_next();
var fallback = null;
var each_array = derived_safe_equal(() => {
var collection = get_collection();
return is_array(collection) ? collection : collection == null ? [] : array_from(collection);
});
var pending = new Map();
var first_run = true;
function commit(batch) {
if ((state.effect.f & 16384) !== 0) return;
state.pending.delete(batch);
var array = get(each_array);
state.fallback = fallback;
reconcile(state, array, anchor, flags, get_key);
if (fallback !== null) {
if (array.length === 0) {
if ((fallback.f & 33554432) === 0) resume_effect(fallback);
else {
fallback.f ^= EFFECT_OFFSCREEN;
move(fallback, null, anchor);
}
} else pause_effect(fallback, () => {
fallback = null;
});
}
}
function discard(batch) {
state.pending.delete(batch);
}
var state = {
effect: block(() => {
var array = get(each_array);
var length = array.length;
let mismatch = false;
if (hydrating) {
if (read_hydration_instruction(anchor) === "[!" !== (length === 0)) {
anchor = skip_nodes();
set_hydrate_node(anchor);
set_hydrating(false);
mismatch = true;
}
}
var keys = new Set();
var batch = current_batch;
var defer = should_defer_append();
for (var index = 0; index < length; index += 1) {
if (hydrating && hydrate_node.nodeType === 8 && hydrate_node.data === "]") {
anchor = hydrate_node;
mismatch = true;
set_hydrating(false);
}
var value = array[index];
var key = get_key(value, index);
var item = first_run ? null : items.get(key);
if (item) {
if (item.v) internal_set(item.v, value);
if (item.i) internal_set(item.i, index);
if (defer) batch.unskip_effect(item.e);
} else {
item = create_item(items, first_run ? anchor : offscreen_anchor ??= create_text(), value, key, index, render_fn, flags, get_collection);
if (!first_run) item.e.f |= EFFECT_OFFSCREEN;
items.set(key, item);
}
keys.add(key);
}
if (length === 0 && fallback_fn && !fallback) {
if (first_run) fallback = branch(() => fallback_fn(anchor));
else {
fallback = branch(() => fallback_fn(offscreen_anchor ??= create_text()));
fallback.f |= EFFECT_OFFSCREEN;
}
}
if (length > keys.size) each_key_duplicate("", "", "");
if (hydrating && length > 0) set_hydrate_node(skip_nodes());
if (!first_run) {
pending.set(batch, keys);
if (defer) {
for (const [key, item] of items) if (!keys.has(key)) batch.skip_effect(item.e);
batch.oncommit(commit);
batch.ondiscard(discard);
} else commit(batch);
}
if (mismatch) set_hydrating(true);
get(each_array);
}),
flags,
items,
pending,
outrogroups: null,
fallback
};
first_run = false;
if (hydrating) anchor = hydrate_node;
}
function skip_to_branch(effect) {
while (effect !== null && (effect.f & 32) === 0) effect = effect.next;
return effect;
}
function reconcile(state, array, anchor, flags, get_key) {
var is_animated = (flags & 8) !== 0;
var length = array.length;
var items = state.items;
var current = skip_to_branch(state.effect.first);
var seen;
var prev = null;
var to_animate;
var matched = [];
var stashed = [];
var value;
var key;
var effect;
var i;
if (is_animated) for (i = 0; i < length; i += 1) {
value = array[i];
key = get_key(value, i);
effect = items.get(key).e;
if ((effect.f & 33554432) === 0) {
effect.nodes?.a?.measure();
(to_animate ??= new Set()).add(effect);
}
}
for (i = 0; i < length; i += 1) {
value = array[i];
key = get_key(value, i);
effect = items.get(key).e;
if (state.outrogroups !== null) for (const group of state.outrogroups) {
group.pending.delete(effect);
group.done.delete(effect);
}
if ((effect.f & 8192) !== 0) {
resume_effect(effect);
if (is_animated) {
effect.nodes?.a?.unfix();
(to_animate ??= new Set()).delete(effect);
}
}
if ((effect.f & 33554432) !== 0) {
effect.f ^= EFFECT_OFFSCREEN;
if (effect === current) move(effect, null, anchor);
else {
var next = prev ? prev.next : current;
if (effect === state.effect.last) state.effect.last = effect.prev;
if (effect.prev) effect.prev.next = effect.next;
if (effect.next) effect.next.prev = effect.prev;
link(state, prev, effect);
link(state, effect, next);
move(effect, next, anchor);
prev = effect;
matched = [];
stashed = [];
current = skip_to_branch(prev.next);
continue;
}
}
if (effect !== current) {
if (seen !== void 0 && seen.has(effect)) {
if (matched.length < stashed.length) {
var start = stashed[0];
var j;
prev = start.prev;
var a = matched[0];
var b = matched[matched.length - 1];
for (j = 0; j < matched.length; j += 1) move(matched[j], start, anchor);
for (j = 0; j < stashed.length; j += 1) seen.delete(stashed[j]);
link(state, a.prev, b.next);
link(state, prev, a);
link(state, b, start);
current = start;
prev = b;
i -= 1;
matched = [];
stashed = [];
} else {
seen.delete(effect);
move(effect, current, anchor);
link(state, effect.prev, effect.next);
link(state, effect, prev === null ? state.effect.first : prev.next);
link(state, prev, effect);
prev = effect;
}
continue;
}
matched = [];
stashed = [];
while (current !== null && current !== effect) {
(seen ??= new Set()).add(current);
stashed.push(current);
current = skip_to_branch(current.next);
}
if (current === null) continue;
}
if ((effect.f & 33554432) === 0) matched.push(effect);
prev = effect;
current = skip_to_branch(effect.next);
}
if (state.outrogroups !== null) {
for (const group of state.outrogroups) if (group.pending.size === 0) {
destroy_effects(state, array_from(group.done));
state.outrogroups?.delete(group);
}
if (state.outrogroups.size === 0) state.outrogroups = null;
}
if (current !== null || seen !== void 0) {
var to_destroy = [];
if (seen !== void 0) {
for (effect of seen) if ((effect.f & 8192) === 0) to_destroy.push(effect);
}
while (current !== null) {
if ((current.f & 8192) === 0 && current !== state.fallback) to_destroy.push(current);
current = skip_to_branch(current.next);
}
var destroy_length = to_destroy.length;
if (destroy_length > 0) {
var controlled_anchor = (flags & 4) !== 0 && length === 0 ? anchor : null;
if (is_animated) {
for (i = 0; i < destroy_length; i += 1) to_destroy[i].nodes?.a?.measure();
for (i = 0; i < destroy_length; i += 1) to_destroy[i].nodes?.a?.fix();
}
pause_effects(state, to_destroy, controlled_anchor);
}
}
if (is_animated) queue_micro_task(() => {
if (to_animate === void 0) return;
for (effect of to_animate) effect.nodes?.a?.apply();
});
}
function create_item(items, anchor, value, key, index, render_fn, flags, get_collection) {
var v = (flags & 1) !== 0 ? (flags & 16) === 0 ? mutable_source(value, false, false) : source(value) : null;
var i = (flags & 2) !== 0 ? source(index) : null;
return {
v,
i,
e: branch(() => {
render_fn(anchor, v ?? value, i ?? index, get_collection);
return () => {
items.delete(key);
};
})
};
}
function move(effect, next, anchor) {
if (!effect.nodes) return;
var node = effect.nodes.start;
var end = effect.nodes.end;
var dest = next && (next.f & 33554432) === 0 ? next.nodes.start : anchor;
while (node !== null) {
var next_node = get_next_sibling(node);
dest.before(node);
if (node === end) return;
node = next_node;
}
}
function link(state, prev, next) {
if (prev === null) state.effect.first = next;
else prev.next = next;
if (next === null) state.effect.last = prev;
else next.prev = prev;
}
function html(node, get_value, is_controlled = false, svg = false, mathml = false, skip_warning = false) {
var anchor = node;
var value = "";
if (is_controlled) {
var parent_node = node;
if (hydrating) anchor = set_hydrate_node(get_first_child(parent_node));
}
template_effect(() => {
var effect = active_effect;
if (value === (value = get_value() ?? "")) {
if (hydrating) hydrate_next();
return;
}
if (is_controlled && !hydrating) {
effect.nodes = null;
parent_node.innerHTML = value;
if (value !== "") assign_nodes(get_first_child(parent_node), parent_node.lastChild);
return;
}
if (effect.nodes !== null) {
remove_effect_dom(effect.nodes.start, effect.nodes.end);
effect.nodes = null;
}
if (value === "") return;
if (hydrating) {
hydrate_node.data;
var next = hydrate_next();
var last = next;
while (next !== null && (next.nodeType !== 8 || next.data !== "")) {
last = next;
next = get_next_sibling(next);
}
if (next === null) {
hydration_mismatch();
throw HYDRATION_ERROR;
}
assign_nodes(hydrate_node, last);
anchor = set_hydrate_node(next);
return;
}
var wrapper = create_element(svg ? "svg" : mathml ? "math" : "template", svg ? NAMESPACE_SVG : mathml ? NAMESPACE_MATHML : void 0);
wrapper.innerHTML = value;
var node = svg || mathml ? wrapper : wrapper.content;
assign_nodes(get_first_child(node), node.lastChild);
if (svg || mathml) while (get_first_child(node)) anchor.before(get_first_child(node));
else anchor.before(node);
});
}
function append_styles(anchor, css) {
effect(() => {
anchor = active_effect?.parent?.nodes?.start ?? anchor;
var root = anchor.getRootNode();
var target = root.host ? root : root.head ?? root.ownerDocument.head;
if (!target.querySelector("#" + css.hash)) {
const style = create_element("style");
style.id = css.hash;
style.textContent = css.code;
target.appendChild(style);
}
});
}
var whitespace = [..." \n\r\f\xA0\v"];
function to_class(value, hash, directives) {
var classname = value == null ? "" : "" + value;
if (hash) classname = classname ? classname + " " + hash : hash;
if (directives) {
for (var key of Object.keys(directives)) if (directives[key]) classname = classname ? classname + " " + key : key;
else if (classname.length) {
var len = key.length;
var a = 0;
while ((a = classname.indexOf(key, a)) >= 0) {
var b = a + len;
if ((a === 0 || whitespace.includes(classname[a - 1])) && (b === classname.length || whitespace.includes(classname[b]))) classname = (a === 0 ? "" : classname.substring(0, a)) + classname.substring(b + 1);
else a = b;
}
}
}
return classname === "" ? null : classname;
}
function set_class(dom, is_html, value, hash, prev_classes, next_classes) {
var prev = dom[CLASS_CACHE];
if (hydrating || prev !== value || prev === void 0) {
var next_class_name = to_class(value, hash, next_classes);
if (!hydrating || next_class_name !== dom.getAttribute("class")) {
if (next_class_name == null) dom.removeAttribute("class");
else if (is_html) dom.className = next_class_name;
else dom.setAttribute("class", next_class_name);
}
dom[CLASS_CACHE] = value;
} else if (next_classes && prev_classes !== next_classes) for (var key in next_classes) {
var is_present = !!next_classes[key];
if (prev_classes == null || is_present !== !!prev_classes[key]) dom.classList.toggle(key, is_present);
}
return next_classes;
}
function set_selected(option, selected) {
if (selected) {
if (!option.hasAttribute("selected")) option.setAttribute("selected", "");
} else option.removeAttribute("selected");
}
function apply_default_select_value(select, preserve) {
var value = select.__defaultValue;
var multiple = select.multiple;
var values = multiple ? value ?? [] : null;
if (multiple && !is_array(values)) return;
var index = select.selectedIndex;
var selected = preserve && multiple ? new Set(select.selectedOptions) : null;
for (var option of select.options) {
var option_value = get_option_value(option);
set_selected(option, multiple ? values.includes(option_value) : is(option_value, value));
}
if (!preserve) return;
if (selected !== null) for (option of select.options) {
var was_selected = selected.has(option);
if (option.selected !== was_selected) option.selected = was_selected;
}
else if (select.selectedIndex !== index) select.selectedIndex = index;
}
function select_option(select, value, mounting = false) {
if (select.multiple) {
if (value == void 0) return;
if (!is_array(value)) return select_multiple_invalid_value();
for (var option of select.options) option.selected = value.includes(get_option_value(option));
return;
}
for (option of select.options) if (is(get_option_value(option), value)) {
option.selected = true;
return;
}
if (!mounting || value !== void 0) select.selectedIndex = -1;
}
function init_select(select) {
var observer = new MutationObserver((entries) => {
if (entries.every(is_selectedcontent_mutation)) return;
if ("__defaultValue" in select) apply_default_select_value(select, false);
if ("__value" in select) select_option(select, select.__value);
});
observer.observe(select, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["value"]
});
teardown(() => {
observer.disconnect();
});
}
function bind_select_value(select, get, set = get) {
var batches = new WeakSet();
var mounting = true;
listen_to_event_and_reset_event(select, "change", (is_reset) => {
var query = is_reset ? "[selected]" : ":checked";
var value;
if (select.multiple) value = [].map.call(select.querySelectorAll(query), get_option_value);
else {
var selected_option = select.querySelector(query) ?? select.querySelector("option:not([disabled])");
value = selected_option && get_option_value(selected_option);
}
set(value);
select.__value = value;
if (current_batch !== null) batches.add(current_batch);
});
effect(() => {
var value = get();
if (select === document.activeElement) {
var batch = async_mode_flag ? previous_batch : current_batch;
if (batches.has(batch)) return;
}
select_option(select, value, mounting);
if (mounting && value === void 0) {
var selected_option = select.querySelector(":checked");
if (selected_option !== null) {
value = get_option_value(selected_option);
set(value);
}
}
select.__value = value;
mounting = false;
});
}
function get_option_value(option) {
if ("__value" in option) return option.__value;
else return option.value;
}
function is_selectedcontent_mutation(entry) {
if (entry.target.closest("selectedcontent") !== null) return true;
if (entry.type === "childList") {
var nodes = [...entry.addedNodes, ...entry.removedNodes];
return nodes.length > 0 && nodes.every((node) => node.nodeName === "SELECTEDCONTENT");
}
return false;
}
var IS_CUSTOM_ELEMENT = Symbol("is custom element");
var IS_HTML = Symbol("is html");
var LINK_TAG = IS_XHTML ? "link" : "LINK";
function remove_input_defaults(input) {
if (!hydrating) return;
var already_removed = false;
var remove_defaults = () => {
if (already_removed) return;
already_removed = true;
if (input.hasAttribute("value")) {
var value = input.value;
set_attribute(input, "value", null);
input.value = value;
}
if (input.hasAttribute("checked")) {
var checked = input.checked;
set_attribute(input, "checked", null);
input.checked = checked;
}
};
input[FORM_RESET_HANDLER] = remove_defaults;
queue_micro_task(remove_defaults);
add_form_reset_listener();
}
function set_attribute(element, attribute, value, skip_warning) {
var attributes = get_attributes(element);
if (hydrating) {
attributes[attribute] = element.getAttribute(attribute);
if (attribute === "src" || attribute === "srcset" || attribute === "href" && element.nodeName === LINK_TAG) {
if (!skip_warning);
return;
}
}
var previous = attributes[attribute];
if (previous === (attributes[attribute] = value)) return;
if (attribute === "loading") element[LOADING_ATTR_SYMBOL] = value;
if (value == null) element.removeAttribute(attribute);
else if (typeof value !== "string" && get_setters(element).has(attribute)) element[attribute] = value;
else if (!(hydrating && (typeof value === "number" || typeof value === "boolean") && previous === String(value))) element.setAttribute(attribute, value);
}
function get_attributes(element) {
return element[ATTRIBUTES_CACHE] ??= {
[IS_CUSTOM_ELEMENT]: element.nodeName.includes("-"),
[IS_HTML]: element.namespaceURI === NAMESPACE_HTML
};
}
var setters_cache = new Map();
function get_setters(element) {
var cache_key = element.getAttribute("is") || element.nodeName;
var setters = setters_cache.get(cache_key);
if (setters) return setters;
setters_cache.set(cache_key, setters = new Set());
var descriptors;
var proto = element;
var element_proto = Element.prototype;
while (element_proto !== proto) {
descriptors = get_descriptors(proto);
for (var key in descriptors) if (descriptors[key].set && key !== "innerHTML" && key !== "textContent" && key !== "innerText") setters.add(key);
proto = get_prototype_of(proto);
}
return setters;
}
function bind_value(input, get, set = get) {
var batches = new WeakSet();
listen_to_event_and_reset_event(input, "input", async (is_reset) => {
var value = is_reset ? input.defaultValue : input.value;
value = is_numberlike_input(input) ? to_number(value) : value;
set(value);
if (current_batch !== null) batches.add(current_batch);
await tick();
if (value !== (value = get())) {
var start = input.selectionStart;
var end = input.selectionEnd;
var length = input.value.length;
input.value = value ?? "";
if (end !== null) {
var new_length = input.value.length;
if (start === end && end === length && new_length > length) {
input.selectionStart = new_length;
input.selectionEnd = new_length;
} else {
input.selectionStart = start;
input.selectionEnd = Math.min(end, new_length);
}
}
}
});
if (hydrating && input.defaultValue !== input.value || untrack(get) == null && input.value) {
set(is_numberlike_input(input) ? to_number(input.value) : input.value);
if (current_batch !== null) batches.add(current_batch);
}
render_effect(() => {
var value = get();
if (input === document.activeElement) {
var batch = async_mode_flag ? previous_batch : current_batch;
if (batches.has(batch)) return;
}
if (is_numberlike_input(input) && value === to_number(input.value)) return;
if (input.type === "date" && !value && !input.value) return;
if (value !== input.value) input.value = value ?? "";
});
}
var pending = new Set();
function bind_group(inputs, group_index, input, get, set = get) {
var is_checkbox = input.getAttribute("type") === "checkbox";
var binding_group = inputs;
let hydration_mismatch = false;
if (group_index !== null) for (var index of group_index) binding_group = binding_group[index] ??= [];
binding_group.push(input);
listen_to_event_and_reset_event(input, "change", () => {
var value = input.__value;
if (is_checkbox) value = get_binding_group_value(binding_group, value, input.checked);
set(value);
}, () => set(is_checkbox ? [] : null));
render_effect(() => {
var value = get();
if (hydrating && input.defaultChecked !== input.checked) {
hydration_mismatch = true;
return;
}
if (is_checkbox) {
value = value || [];
input.checked = value.includes(input.__value);
} else input.checked = is(input.__value, value);
});
teardown(() => {
var index = binding_group.indexOf(input);
if (index !== -1) binding_group.splice(index, 1);
});
if (!pending.has(binding_group)) {
pending.add(binding_group);
queue_micro_task(() => {
binding_group.sort((a, b) => a.compareDocumentPosition(b) === 4 ? -1 : 1);
pending.delete(binding_group);
});
}
queue_micro_task(() => {
if (hydration_mismatch) {
var value;
if (is_checkbox) value = get_binding_group_value(binding_group, value, input.checked);
else value = binding_group.find((input) => input.checked)?.__value;
set(value);
}
});
}
function bind_checked(input, get, set = get) {
listen_to_event_and_reset_event(input, "change", (is_reset) => {
set(is_reset ? input.defaultChecked : input.checked);
});
if (hydrating && input.defaultChecked !== input.checked || untrack(get) == null) set(input.checked);
render_effect(() => {
var value = get();
input.checked = Boolean(value);
});
}
function get_binding_group_value(group, __value, checked) {
var value = new Set();
for (var i = 0; i < group.length; i += 1) if (group[i].checked) value.add(group[i].__value);
if (!checked) value.delete(__value);
return Array.from(value);
}
function is_numberlike_input(input) {
var type = input.type;
return type === "number" || type === "range";
}
function to_number(value) {
return value === "" ? null : +value;
}
var _GM_addValueChangeListener = (() => typeof GM_addValueChangeListener != "undefined" ? GM_addValueChangeListener : void 0)();
var _GM_getValue = (() => typeof GM_getValue != "undefined" ? GM_getValue : void 0)();
var _GM_registerMenuCommand = (() => typeof GM_registerMenuCommand != "undefined" ? GM_registerMenuCommand : void 0)();
var _GM_setValue = (() => typeof GM_setValue != "undefined" ? GM_setValue : void 0)();
var _GM_xmlhttpRequest = (() => typeof GM_xmlhttpRequest != "undefined" ? GM_xmlhttpRequest : void 0)();
var store = {
get: (key, fallback) => _GM_getValue(key, fallback),
set: (key, value) => _GM_setValue(key, value)
};
function onStoreChange(key, onChange) {
if (typeof _GM_addValueChangeListener !== "function") return;
_GM_addValueChangeListener(key, (_key, _old, _value, remote) => {
if (remote) onChange();
});
}
function registerMenuCommand(label, onClick) {
if (typeof _GM_registerMenuCommand === "function") _GM_registerMenuCommand(label, onClick);
}
var FETCH_TIMEOUT_MS = 15e3;
var fetchText = (url) => new Promise((resolve, reject) => {
_GM_xmlhttpRequest({
method: "GET",
url,
timeout: FETCH_TIMEOUT_MS,
onload: (r) => r.status >= 200 && r.status < 300 ? resolve(r.responseText) : reject(new Error(`HTTP ${r.status}`)),
onerror: () => reject(new Error("network error")),
ontimeout: () => reject(new Error("timeout"))
});
});
function streamRequest(request, onText) {
let abort = () => {};
return {
abort: () => abort(),
done: new Promise((resolve, reject) => {
const common = {
method: request.method,
url: request.url,
headers: request.headers,
data: request.body,
onerror: () => reject(new Error("network error")),
onabort: () => reject(new DOMException("aborted", "AbortError"))
};
if (_GM_xmlhttpRequest.RESPONSE_TYPE_STREAM) {
let started = false;
const handle = _GM_xmlhttpRequest({
...common,
responseType: "stream",
onloadstart: async (r) => {
if (started) return;
started = true;
const reader = r.response.getReader();
const decoder = new TextDecoder();
let body = "";
try {
for (;;) {
const { value, done: end } = await reader.read();
if (end) break;
body += decoder.decode(value, { stream: true });
onText(body);
}
resolve({
status: r.status,
body: body + decoder.decode()
});
} catch (error) {
reject(error);
}
}
});
abort = () => handle.abort();
} else {
const handle = _GM_xmlhttpRequest({
...common,
onprogress: (r) => {
if (r.responseText) onText(r.responseText);
},
onload: (r) => resolve({
status: r.status,
body: r.responseText
})
});
abort = () => handle.abort();
}
})
};
}
function sendRequest(request) {
return new Promise((resolve, reject) => {
_GM_xmlhttpRequest({
method: request.method,
url: request.url,
headers: request.headers,
data: request.body,
anonymous: true,
timeout: FETCH_TIMEOUT_MS,
onload: (r) => resolve({
status: r.status,
body: r.responseText
}),
onerror: () => reject(new Error("network error")),
ontimeout: () => reject(new Error("timeout"))
});
});
}
function fetchPage(url) {
return new Promise((resolve, reject) => {
_GM_xmlhttpRequest({
method: "GET",
url,
responseType: "arraybuffer",
anonymous: true,
timeout: FETCH_TIMEOUT_MS,
onload: (r) => {
if (r.status < 200 || r.status >= 300) return reject(new Error(`HTTP ${r.status}`));
const type = /^content-type:\s*(.*)$/im.exec(r.responseHeaders ?? "")?.[1] ?? null;
if (type && !/html|xml|text\/plain/i.test(type)) return reject(new Error(type));
resolve(new DOMParser().parseFromString(decodeHtml(new Uint8Array(r.response), type), "text/html"));
},
onerror: () => reject(new Error("network error")),
ontimeout: () => reject(new Error("timeout"))
});
});
}
if (typeof window !== "undefined") ((window.__svelte ??= {}).v ??= new Set()).add("5");
var root$2 = from_html(``);
var root_1$1 = from_html(``);
var root_2$1 = from_html(` `, 1);
var root_3$1 = from_html(`
`); var root_8$1 = from_html(`
`, 1); var root_6 = from_html(``); var root_7 = from_html(``); var root_8 = from_html(``); var root_9 = from_html(`
`); var root_10 = from_html(`
`); var root_13 = from_html(`
`, 1); var root_15 = from_html(` `, 1); var $$css = { hash: "svelte-dfcql8", code: ":host {--bg: #ffffff;--fg: #16181d;--dim: #5c6370;--line: #e3e7ed;--accent: #1a4fd6;--field: #f5f6f8;}\n /* The host carries the engine page's theme, which may differ from the system's. */:host([data-theme='dark']) {--bg: #171a21;--fg: #e4e7ec;--dim: #9aa3b2;--line: #2a303b;--accent: #a9c1ff;--field: #1f242d;}.backdrop.svelte-dfcql8 {position:fixed;inset:0;z-index:2147483646;background:rgba(0, 0, 0, 0.2);}.drawer.svelte-dfcql8 {position:fixed;top:0;right:0;bottom:0;z-index:2147483647;box-sizing:border-box;width:min(400px, 100vw);overflow-y:auto;padding:20px 24px 32px;background:var(--bg);color:var(--fg);box-shadow:-8px 0 24px rgba(0, 0, 0, 0.15);font:14px/1.6 'IBM Plex Sans', 'PingFang SC', 'Noto Sans SC', system-ui, sans-serif;}\n @media (max-width: 600px) {.drawer.svelte-dfcql8 {top:auto;left:0;width:100vw;max-height:85vh;border-radius:16px 16px 0 0;}\n }header.svelte-dfcql8 {display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;}h2.svelte-dfcql8 {margin:0;font-size:17px;font-weight:600;}h3.svelte-dfcql8 {margin:0 0 8px;font-size:14px;font-weight:600;}section.svelte-dfcql8 {padding:16px 0;border-top:1px solid var(--line);}fieldset.svelte-dfcql8 {margin:0 0 12px;padding:0;border:0;}legend.svelte-dfcql8 {margin-bottom:4px;color:var(--dim);}.row.svelte-dfcql8 {display:flex;align-items:center;gap:8px;min-height:32px;cursor:pointer;}.stack.svelte-dfcql8 {display:flex;flex-direction:column;gap:6px;margin-top:12px;}.label.svelte-dfcql8 {min-width:3em;color:var(--dim);}h3.sub.svelte-dfcql8 {margin-top:16px;}.subscription.svelte-dfcql8 {padding:6px 0;border-bottom:1px solid var(--line);}.subscription.svelte-dfcql8 .hint:where(.svelte-dfcql8) {margin:0 0 2px 26px;}.subscription.svelte-dfcql8 .link:where(.svelte-dfcql8) {margin-left:26px;}.add.svelte-dfcql8 {margin-top:8px;}.actions.svelte-dfcql8 {gap:16px;}input.text.svelte-dfcql8 {flex:1;min-width:0;padding:6px 8px;border:1px solid var(--line);border-radius:6px;background:var(--field);color:var(--fg);font:13px 'IBM Plex Mono', ui-monospace, monospace;}.visually-hidden.svelte-dfcql8 {position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);}input.number.svelte-dfcql8 {width:4em;padding:4px 6px;border:1px solid var(--line);border-radius:6px;background:var(--field);color:var(--fg);font:inherit;}select.svelte-dfcql8 {padding:4px 8px;border:1px solid var(--line);border-radius:6px;background:var(--field);color:var(--fg);font:inherit;}textarea.svelte-dfcql8 {box-sizing:border-box;width:100%;padding:8px 10px;border:1px solid var(--line);border-radius:8px;background:var(--field);color:var(--fg);font:13px/1.5 'IBM Plex Mono', ui-monospace, monospace;resize:vertical;}.hint.svelte-dfcql8 {margin:8px 0 0;color:var(--dim);font-size:13px;}.hint.svelte-dfcql8 code {font-family:'IBM Plex Mono', ui-monospace, monospace;font-size:12px;}.sites.svelte-dfcql8 {margin:0;padding:0;list-style:none;}.sites.svelte-dfcql8 li:where(.svelte-dfcql8) {display:flex;align-items:center;justify-content:space-between;gap:12px;min-height:36px;border-bottom:1px solid var(--line);}.host.svelte-dfcql8 {font:13px 'IBM Plex Mono', ui-monospace, monospace;overflow-wrap:anywhere;}button.link.svelte-dfcql8 {flex:none;padding:4px 0;border:0;background:none;color:var(--accent);font:inherit;cursor:pointer;}button.icon.svelte-dfcql8 {width:36px;height:36px;border:0;border-radius:8px;background:none;color:var(--fg);cursor:pointer;}button.icon.svelte-dfcql8:hover {background:var(--field);}button.svelte-dfcql8:focus-visible,\n input.svelte-dfcql8:focus-visible,\n select.svelte-dfcql8:focus-visible,\n textarea.svelte-dfcql8:focus-visible {outline:2px solid var(--accent);outline-offset:2px;}" }; function Settings($$anchor, $$props) { push($$props, true); append_styles($$anchor, $$css); const binding_group = []; const binding_group_1 = []; const binding_group_2 = []; let settings = state(proxy({ ...$$props.settings })); const SITE_RULE = /^\*:\/\/\*\.([^/]+)\/\*$/; let blockedSites = user_derived(() => get(settings).rules.split("\n").map((line) => line.trim().match(SITE_RULE)?.[1]).filter((host) => !!host)); function commit() { $$props.onchange({ ...get(settings) }); } function unblock(host) { get(settings).rules = removeRule(get(settings).rules, `*://*.${host}/*`); commit(); } let newSubscription = state(""); let refreshing = state(false); let statusVersion = state(0); function addSubscription() { const urls = get(newSubscription).split(/\s+/).filter((u) => /^https?:\/\//.test(u)); if (!urls.length) return; get(settings).subscriptions = [...get(settings).subscriptions, { urls, enabled: true }]; set(newSubscription, ""); commit(); } function removeSubscription(index) { get(settings).subscriptions = get(settings).subscriptions.filter((_, i) => i !== index); commit(); } async function refreshAll() { set(refreshing, true); await $$props.refreshSubscriptions(); set(refreshing, false); set(statusVersion, get(statusVersion) + 1); } function describe(sub, _version) { const status = $$props.subscriptionStatus(sub); if (status.error && !status.fetchedAt) return t("subs.failed", { error: status.error }); if (!status.fetchedAt) return t("subs.notFetched"); const when = new Date(status.fetchedAt).toLocaleString(); return t("subs.status", { count: status.ruleCount, when }) + (status.error ? t("subs.lastFailed") : ""); } let provider = user_derived(() => AI_PROVIDERS.find((p) => p.id === get(settings).aiProvider) ?? AI_PROVIDERS.at(-1)); let models = state(proxy([])); let modelsMessage = state(""); function chooseProvider() { if (get(provider).id !== "custom") { get(settings).aiBaseUrl = get(provider).baseUrl; get(settings).aiModel = get(provider).model; } get(settings).aiApiKey = ""; set(models, [], true); set(modelsMessage, ""); commit(); } async function loadModels() { set(modelsMessage, ""); try { set(models, await $$props.listModels({ baseUrl: get(settings).aiBaseUrl, apiKey: get(settings).aiApiKey, model: get(settings).aiModel }), true); set(modelsMessage, t("aiset.models", { count: get(models).length }), true); } catch (error) { set(modelsMessage, t("aiset.modelsFailed", { error: error.message }), true); } } let themeText = state(null); let themeMessage = state(""); async function copyTheme() { const json = exportTheme(get(settings)); try { await navigator.clipboard.writeText(json); set(themeMessage, t("theme.copied"), true); } catch { set(themeText, json, true); set(themeMessage, ""); } } function applyTheme() { const result = parseTheme(get(themeText) ?? ""); if ("problem" in result) { set(themeMessage, t(result.problem), true); return; } Object.assign(get(settings), result.theme); set(themeText, null); set(themeMessage, t("theme.imported"), true); commit(); } let dav = proxy($$props.sync.config()); let syncStatus = state(proxy($$props.sync.status())); let syncing = state(false); let davReady = user_derived(() => dav.enabled && !!dav.url.trim() && !!dav.username.trim()); function saveDav() { $$props.sync.setConfig({ ...dav }); } async function syncNow() { set(syncing, true); set(syncStatus, await $$props.sync.now(), true); set(syncing, false); set(settings, { ...$$props.getSettings() }, true); } function describeSync(status) { const when = status.at ? t("sync.last", { when: new Date(status.at).toLocaleString() }) : t("sync.never"); if (!status.error) return when; return `${t("sync.failed", { error: status.error === "auth" ? t("sync.auth") : status.error })} ${status.at ? when : ""}`.trim(); } function onkeydown(event) { if (event.key === "Escape") $$props.onclose(); } var fragment = root_15(); event("keydown", $window, onkeydown); var div = first_child(fragment); var aside = sibling(div, 2); var header = child(aside); var h2 = child(header); var text = only_child(h2, true); var button = sibling(h2, 2); reset(header); var section = sibling(header, 2); var h3 = child(section); var text_1 = only_child(h3, true); var label = sibling(h3, 2); var input = child(label); remove_input_defaults(input); var text_2 = only_child(sibling(input, 2), true); reset(label); var node = sibling(label, 2); var consequent = ($$anchor) => { var fragment_1 = root(); var label_1 = first_child(fragment_1); var span_1 = child(label_1); var text_3 = only_child(span_1, true); var select = sibling(span_1, 2); var option = child(select); var text_4 = only_child(option, true); option.value = option.__value = "1"; var option_1 = sibling(option); var text_5 = only_child(option_1, true); option_1.value = option_1.__value = "2"; var option_2 = sibling(option_1); var text_6 = only_child(option_2, true); option_2.value = option_2.__value = "3"; reset(select); init_select(select); reset(label_1); var fieldset = sibling(label_1, 2); var legend = child(fieldset); var text_7 = only_child(legend, true); var label_2 = sibling(legend, 2); var input_1 = child(label_2); remove_input_defaults(input_1); input_1.value = input_1.__value = "card"; var text_8 = only_child(sibling(input_1, 2), true); reset(label_2); var label_3 = sibling(label_2, 2); var input_2 = child(label_3); remove_input_defaults(input_2); input_2.value = input_2.__value = "raised"; var text_9 = only_child(sibling(input_2, 2), true); reset(label_3); var label_4 = sibling(label_3, 2); var input_3 = child(label_4); remove_input_defaults(input_3); input_3.value = input_3.__value = "line"; var text_10 = only_child(sibling(input_3, 2), true); reset(label_4); reset(fieldset); var fieldset_1 = sibling(fieldset, 2); var legend_1 = child(fieldset_1); var text_11 = only_child(legend_1, true); var label_5 = sibling(legend_1, 2); var input_4 = child(label_5); remove_input_defaults(input_4); input_4.value = input_4.__value = "compact"; var text_12 = only_child(sibling(input_4, 2), true); reset(label_5); var label_6 = sibling(label_5, 2); var input_5 = child(label_6); remove_input_defaults(input_5); input_5.value = input_5.__value = "comfortable"; var text_13 = only_child(sibling(input_5, 2), true); reset(label_6); reset(fieldset_1); template_effect(($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10) => { set_text(text_3, $0); set_text(text_4, $1); set_text(text_5, $2); set_text(text_6, $3); set_text(text_7, $4); set_text(text_8, $5); set_text(text_9, $6); set_text(text_10, $7); set_text(text_11, $8); set_text(text_12, $9); set_text(text_13, $10); }, [ () => t("appearance.columns"), () => t("appearance.columns1"), () => t("appearance.columns2"), () => t("appearance.columns3"), () => t("appearance.theme"), () => t("appearance.card"), () => t("appearance.raised"), () => t("appearance.line"), () => t("appearance.density"), () => t("appearance.compact"), () => t("appearance.comfortable") ]); delegated("change", select, commit); bind_select_value(select, () => get(settings).columns, ($$value) => get(settings).columns = $$value); delegated("change", input_1, commit); bind_group(binding_group, [], input_1, () => get(settings).cardStyle, ($$value) => get(settings).cardStyle = $$value); delegated("change", input_2, commit); bind_group(binding_group, [], input_2, () => get(settings).cardStyle, ($$value) => get(settings).cardStyle = $$value); delegated("change", input_3, commit); bind_group(binding_group, [], input_3, () => get(settings).cardStyle, ($$value) => get(settings).cardStyle = $$value); delegated("change", input_4, commit); bind_group(binding_group_1, [], input_4, () => get(settings).density, ($$value) => get(settings).density = $$value); delegated("change", input_5, commit); bind_group(binding_group_1, [], input_5, () => get(settings).density, ($$value) => get(settings).density = $$value); append($$anchor, fragment_1); }; if_block(node, ($$render) => { if (get(settings).layout) $$render(consequent); }); var label_7 = sibling(node, 2); var input_6 = child(label_7); remove_input_defaults(input_6); var text_14 = only_child(sibling(input_6, 2), true); reset(label_7); var label_8 = sibling(label_7, 2); var span_8 = child(label_8); var text_15 = only_child(span_8, true); var textarea = sibling(span_8, 2); remove_textarea_child(textarea); reset(label_8); var p_1 = sibling(label_8, 2); html(p_1, () => t("theme.cssHint"), true); reset(p_1); var div_1 = sibling(p_1, 2); var button_1 = child(div_1); var text_16 = only_child(button_1, true); var node_1 = sibling(button_1, 2); var consequent_1 = ($$anchor) => { var button_2 = root_1(); var text_17 = only_child(button_2, true); template_effect(($0) => set_text(text_17, $0), [() => t("theme.import")]); delegated("click", button_2, () => (set(themeText, ""), set(themeMessage, ""))); append($$anchor, button_2); }; if_block(node_1, ($$render) => { if (get(themeText) === null) $$render(consequent_1); }); reset(div_1); var node_2 = sibling(div_1, 2); var consequent_2 = ($$anchor) => { var fragment_2 = root_2(); var textarea_1 = first_child(fragment_2); remove_textarea_child(textarea_1); var div_2 = sibling(textarea_1, 2); var button_3 = child(div_2); var text_18 = only_child(button_3, true); var button_4 = sibling(button_3, 2); var text_19 = only_child(button_4, true); reset(div_2); template_effect(($0, $1, $2, $3) => { set_attribute(textarea_1, "aria-label", $0); set_attribute(textarea_1, "placeholder", $1); set_text(text_18, $2); set_text(text_19, $3); }, [ () => t("theme.import"), () => t("theme.importPlaceholder"), () => t("theme.apply"), () => t("theme.cancel") ]); bind_value(textarea_1, () => get(themeText), ($$value) => set(themeText, $$value)); delegated("click", button_3, applyTheme); delegated("click", button_4, () => (set(themeText, null), set(themeMessage, ""))); append($$anchor, fragment_2); }; if_block(node_2, ($$render) => { if (get(themeText) !== null) $$render(consequent_2); }); var text_20 = only_child(sibling(node_2, 2), true); reset(section); var section_1 = sibling(section, 2); var h3_1 = child(section_1); var text_21 = only_child(h3_1, true); var label_9 = sibling(h3_1, 2); var input_7 = child(label_9); remove_input_defaults(input_7); var text_22 = only_child(sibling(input_7, 2), true); reset(label_9); var node_3 = sibling(label_9, 2); var consequent_3 = ($$anchor) => { var label_10 = root_3(); var span_10 = child(label_10); var text_23 = only_child(span_10, true); var input_8 = sibling(span_10, 2); remove_input_defaults(input_8); var text_24 = only_child(sibling(input_8, 2), true); reset(label_10); template_effect(($0, $1) => { set_text(text_23, $0); set_text(text_24, $1); }, [() => t("paging.limitBefore"), () => t("paging.limitAfter")]); delegated("change", input_8, commit); bind_value(input_8, () => get(settings).autoPageLimit, ($$value) => get(settings).autoPageLimit = $$value); append($$anchor, label_10); }; if_block(node_3, ($$render) => { if (get(settings).autoPage) $$render(consequent_3); }); reset(section_1); var section_2 = sibling(section_1, 2); var h3_2 = child(section_2); var text_25 = only_child(h3_2, true); var label_11 = sibling(h3_2, 2); var input_9 = child(label_11); remove_input_defaults(input_9); var text_26 = only_child(sibling(input_9, 2), true); reset(label_11); reset(section_2); var section_3 = sibling(section_2, 2); var h3_3 = child(section_3); var text_27 = only_child(h3_3, true); var label_12 = sibling(h3_3, 2); var input_10 = child(label_12); remove_input_defaults(input_10); var text_28 = only_child(sibling(input_10, 2), true); reset(label_12); var p_3 = sibling(label_12, 2); var text_29 = only_child(p_3, true); var label_13 = sibling(p_3, 2); var span_14 = child(label_13); var text_30 = only_child(span_14, true); var select_1 = sibling(span_14, 2); var option_3 = child(select_1); var text_31 = only_child(option_3, true); option_3.value = option_3.__value = "engine"; var option_4 = sibling(option_3); var text_32 = only_child(option_4, true); option_4.value = option_4.__value = "new"; var option_5 = sibling(option_4); var text_33 = only_child(option_5, true); option_5.value = option_5.__value = "same"; reset(select_1); init_select(select_1); reset(label_13); reset(section_3); var section_4 = sibling(section_3, 2); var h3_4 = child(section_4); var text_34 = only_child(h3_4, true); var label_14 = sibling(h3_4, 2); var input_11 = child(label_14); remove_input_defaults(input_11); var text_35 = only_child(sibling(input_11, 2), true); reset(label_14); var node_4 = sibling(label_14, 2); var consequent_4 = ($$anchor) => { var label_15 = root_4(); var input_12 = child(label_15); remove_input_defaults(input_12); var text_36 = only_child(sibling(input_12, 2), true); reset(label_15); template_effect(($0) => set_text(text_36, $0), [() => t("official.pin")]); delegated("change", input_12, commit); bind_checked(input_12, () => get(settings).pinOfficial, ($$value) => get(settings).pinOfficial = $$value); append($$anchor, label_15); }; if_block(node_4, ($$render) => { if (get(settings).markOfficial) $$render(consequent_4); }); var p_4 = sibling(node_4, 2); var text_37 = only_child(p_4, true); var node_5 = sibling(p_4, 2); var consequent_5 = ($$anchor) => { var fragment_3 = root_5(); var label_16 = first_child(fragment_3); var span_17 = child(label_16); var text_38 = only_child(span_17, true); var input_13 = sibling(span_17, 2); remove_input_defaults(input_13); reset(label_16); var text_39 = only_child(sibling(label_16, 2), true); template_effect(($0, $1) => { set_text(text_38, $0); set_text(text_39, $1); }, [() => t("official.proxy"), () => t("official.proxyHint")]); delegated("change", input_13, commit); bind_value(input_13, () => get(settings).githubProxy, ($$value) => get(settings).githubProxy = $$value); append($$anchor, fragment_3); }; if_block(node_5, ($$render) => { if (get(settings).markOfficial) $$render(consequent_5); }); reset(section_4); var section_5 = sibling(section_4, 2); var h3_5 = child(section_5); var text_40 = only_child(h3_5, true); var p_6 = sibling(h3_5, 2); var text_41 = only_child(p_6, true); var label_17 = sibling(p_6, 2); var span_18 = child(label_17); var text_42 = only_child(span_18, true); var select_2 = sibling(span_18, 2); each(select_2, 21, () => AI_PROVIDERS, (p) => p.id, ($$anchor, p) => { var option_6 = root_6(); var text_43 = only_child(option_6, true); var option_6_value = {}; template_effect(($0) => { set_text(text_43, $0); if (option_6_value !== (option_6_value = get(p).id)) option_6.value = (option_6.__value = option_6_value) ?? ""; }, [() => get(p).id === "custom" ? t("aiset.custom") : get(p).name]); append($$anchor, option_6); }); reset(select_2); init_select(select_2); reset(label_17); var label_18 = sibling(label_17, 2); var span_19 = child(label_18); var text_44 = only_child(span_19, true); var input_14 = sibling(span_19, 2); remove_input_defaults(input_14); reset(label_18); var node_6 = sibling(label_18, 2); var consequent_6 = ($$anchor) => { var p_7 = root_7(); var a = child(p_7); var text_45 = only_child(a, true); reset(p_7); template_effect(($0) => { set_attribute(a, "href", get(provider).keyUrl); set_text(text_45, $0); }, [() => t("aiset.getKey")]); append($$anchor, p_7); }; if_block(node_6, ($$render) => { if (get(provider).keyUrl) $$render(consequent_6); }); var label_19 = sibling(node_6, 2); var span_20 = child(label_19); var text_46 = only_child(span_20, true); var input_15 = sibling(span_20, 2); remove_input_defaults(input_15); reset(label_19); var label_20 = sibling(label_19, 2); var span_21 = child(label_20); var text_47 = only_child(span_21, true); var input_16 = sibling(span_21, 2); remove_input_defaults(input_16); reset(label_20); var datalist = sibling(label_20, 2); each(datalist, 20, () => get(models), (model) => model, ($$anchor, model) => { var option_7 = root_8(); var option_7_value = {}; template_effect(() => { if (option_7_value !== (option_7_value = model)) option_7.value = (option_7.__value = option_7_value) ?? ""; }); append($$anchor, option_7); }); reset(datalist); var div_3 = sibling(datalist, 2); var button_5 = child(div_3); var text_48 = only_child(button_5, true); reset(div_3); var node_7 = sibling(div_3, 2); var consequent_7 = ($$anchor) => { var p_8 = root_9(); var text_49 = only_child(p_8, true); template_effect(() => set_text(text_49, get(modelsMessage))); append($$anchor, p_8); }; if_block(node_7, ($$render) => { if (get(modelsMessage)) $$render(consequent_7); }); var text_50 = only_child(sibling(node_7, 2), true); reset(section_5); var section_6 = sibling(section_5, 2); var h3_6 = child(section_6); var text_51 = only_child(h3_6, true); var fieldset_2 = sibling(h3_6, 2); var legend_2 = child(fieldset_2); var text_52 = only_child(legend_2, true); var label_21 = sibling(legend_2, 2); var input_17 = child(label_21); remove_input_defaults(input_17); input_17.value = input_17.__value = "collapse"; var text_53 = only_child(sibling(input_17, 2), true); reset(label_21); var label_22 = sibling(label_21, 2); var input_18 = child(label_22); remove_input_defaults(input_18); input_18.value = input_18.__value = "hide"; var text_54 = only_child(sibling(input_18, 2), true); reset(label_22); reset(fieldset_2); var node_8 = sibling(fieldset_2, 2); var consequent_8 = ($$anchor) => { var ul = root_11(); each(ul, 20, () => get(blockedSites), (host) => host, ($$anchor, host) => { var li = root_10(); var span_24 = child(li); var text_55 = only_child(span_24, true); var button_6 = sibling(span_24, 2); var text_56 = only_child(button_6, true); reset(li); template_effect(($0) => { set_text(text_55, host); set_text(text_56, $0); }, [() => t("blocking.unblock")]); delegated("click", button_6, () => unblock(host)); append($$anchor, li); }); reset(ul); template_effect(($0) => set_attribute(ul, "aria-label", $0), [() => t("blocking.sites")]); append($$anchor, ul); }; var alternate = ($$anchor) => { var p_10 = root_12(); var text_57 = only_child(p_10, true); template_effect(($0) => set_text(text_57, $0), [() => t("blocking.none")]); append($$anchor, p_10); }; if_block(node_8, ($$render) => { if (get(blockedSites).length) $$render(consequent_8); else $$render(alternate, -1); }); var h3_7 = sibling(node_8, 2); var text_58 = only_child(h3_7, true); var node_9 = sibling(h3_7, 2); each(node_9, 19, () => get(settings).subscriptions, (sub) => sub.urls[0], ($$anchor, sub, i) => { var div_4 = root_13(); var label_23 = child(div_4); var input_19 = child(label_23); remove_input_defaults(input_19); var text_59 = only_child(sibling(input_19, 2), true); reset(label_23); var p_11 = sibling(label_23, 2); var text_60 = only_child(p_11); var button_7 = sibling(p_11, 2); var text_61 = only_child(button_7, true); reset(div_4); template_effect(($0, $1, $2) => { set_text(text_59, get(sub).urls[0]); set_text(text_60, `${$0 ?? ""}${$1 ?? ""}`); set_text(text_61, $2); }, [ () => describe(get(sub), get(statusVersion)), () => get(sub).urls.length > 1 ? t("subs.mirrors", { count: get(sub).urls.length - 1 }) : "", () => t("subs.remove") ]); delegated("change", input_19, commit); bind_checked(input_19, () => get(sub).enabled, ($$value) => get(sub).enabled = $$value); delegated("click", button_7, () => removeSubscription(get(i))); append($$anchor, div_4); }); var div_5 = sibling(node_9, 2); var label_24 = child(div_5); var text_62 = only_child(label_24, true); var input_20 = sibling(label_24, 2); remove_input_defaults(input_20); var button_8 = sibling(input_20, 2); var text_63 = only_child(button_8, true); reset(div_5); var node_10 = sibling(div_5, 2); var consequent_9 = ($$anchor) => { var button_9 = root_1(); var text_64 = only_child(button_9, true); template_effect(($0) => { button_9.disabled = get(refreshing); set_text(text_64, $0); }, [() => get(refreshing) ? t("subs.refreshing") : t("subs.refresh")]); delegated("click", button_9, refreshAll); append($$anchor, button_9); }; if_block(node_10, ($$render) => { if (get(settings).subscriptions.length) $$render(consequent_9); }); var p_12 = sibling(node_10, 2); var text_65 = only_child(p_12, true); var label_25 = sibling(p_12, 2); var span_26 = child(label_25); var text_66 = only_child(span_26, true); var textarea_2 = sibling(span_26, 2); remove_textarea_child(textarea_2); reset(label_25); var p_13 = sibling(label_25, 2); html(p_13, () => t("rules.hint"), true); reset(p_13); reset(section_6); var section_7 = sibling(section_6, 2); var h3_8 = child(section_7); var text_67 = only_child(h3_8, true); var label_26 = sibling(h3_8, 2); var input_21 = child(label_26); remove_input_defaults(input_21); var text_68 = only_child(sibling(input_21, 2), true); reset(label_26); var p_14 = sibling(label_26, 2); var text_69 = only_child(p_14, true); var node_11 = sibling(p_14, 2); var consequent_10 = ($$anchor) => { var fragment_4 = root_14(); var label_27 = first_child(fragment_4); var span_28 = child(label_27); var text_70 = only_child(span_28, true); var input_22 = sibling(span_28, 2); remove_input_defaults(input_22); reset(label_27); var label_28 = sibling(label_27, 2); var span_29 = child(label_28); var text_71 = only_child(span_29, true); var input_23 = sibling(span_29, 2); remove_input_defaults(input_23); reset(label_28); var label_29 = sibling(label_28, 2); var span_30 = child(label_29); var text_72 = only_child(span_30, true); var input_24 = sibling(span_30, 2); remove_input_defaults(input_24); reset(label_29); var p_15 = sibling(label_29, 2); var text_73 = only_child(p_15, true); var div_6 = sibling(p_15, 2); var button_10 = child(div_6); var text_74 = only_child(button_10, true); reset(div_6); var text_75 = only_child(sibling(div_6, 2), true); template_effect(($0, $1, $2, $3, $4, $5) => { set_text(text_70, $0); set_text(text_71, $1); set_text(text_72, $2); set_text(text_73, $3); button_10.disabled = !get(davReady) || get(syncing); set_text(text_74, $4); set_text(text_75, $5); }, [ () => t("sync.url"), () => t("sync.username"), () => t("sync.password"), () => t("sync.passwordHint"), () => get(syncing) ? t("sync.running") : t("sync.now"), () => describeSync(get(syncStatus)) ]); delegated("change", input_22, saveDav); bind_value(input_22, () => dav.url, ($$value) => dav.url = $$value); delegated("change", input_23, saveDav); bind_value(input_23, () => dav.username, ($$value) => dav.username = $$value); delegated("change", input_24, saveDav); bind_value(input_24, () => dav.password, ($$value) => dav.password = $$value); delegated("click", button_10, syncNow); append($$anchor, fragment_4); }; if_block(node_11, ($$render) => { if (dav.enabled) $$render(consequent_10); }); reset(section_7); reset(aside); template_effect(($0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42) => { set_text(text, $0); set_attribute(button, "aria-label", $1); set_text(text_1, $2); set_text(text_2, $3); set_text(text_14, $4); set_text(text_15, $5); set_text(text_16, $6); set_text(text_20, $7); set_text(text_21, $8); set_text(text_22, $9); set_text(text_25, $10); set_text(text_26, $11); set_text(text_27, $12); set_text(text_28, $13); set_text(text_29, $14); set_text(text_30, $15); set_text(text_31, $16); set_text(text_32, $17); set_text(text_33, $18); set_text(text_34, $19); set_text(text_35, $20); set_text(text_37, $21); set_text(text_40, $22); set_text(text_41, $23); set_text(text_42, $24); set_text(text_44, $25); set_text(text_46, $26); set_text(text_47, $27); set_text(text_48, $28); set_text(text_50, $29); set_text(text_51, $30); set_text(text_52, $31); set_text(text_53, $32); set_text(text_54, $33); set_text(text_58, $34); set_text(text_62, $35); set_attribute(input_20, "placeholder", $36); set_text(text_63, $37); set_text(text_65, $38); set_text(text_66, $39); set_text(text_67, $40); set_text(text_68, $41); set_text(text_69, $42); }, [ () => t("settings.title"), () => t("settings.close"), () => t("appearance.title"), () => t("appearance.layout"), () => t("appearance.collapseAi"), () => t("theme.css"), () => t("theme.export"), () => get(themeMessage) || t("theme.shareHint"), () => t("paging.title"), () => t("paging.auto"), () => t("ads.title"), () => t("ads.remove"), () => t("links.title"), () => t("links.clean"), () => t("links.googleHint"), () => t("links.open"), () => t("links.openEngine"), () => t("links.openNew"), () => t("links.openSame"), () => t("official.title"), () => t("official.mark"), () => t("official.hint"), () => t("aiset.title"), () => t("aiset.hint"), () => t("aiset.provider"), () => t("aiset.key"), () => t("aiset.baseUrl"), () => t("aiset.model"), () => t("aiset.listModels"), () => t("aiset.firstRequest"), () => t("blocking.title"), () => t("blocking.action"), () => t("blocking.collapse"), () => t("blocking.hide"), () => t("subs.title"), () => t("subs.address"), () => t("subs.placeholder"), () => t("subs.add"), () => t("subs.hint"), () => t("rules.title"), () => t("sync.title"), () => t("sync.enable"), () => t("sync.hint") ]); delegated("click", div, function(...$$args) { $$props.onclose?.apply(this, $$args); }); delegated("click", button, function(...$$args) { $$props.onclose?.apply(this, $$args); }); delegated("change", input, commit); bind_checked(input, () => get(settings).layout, ($$value) => get(settings).layout = $$value); delegated("change", input_6, commit); bind_checked(input_6, () => get(settings).collapseAiAnswers, ($$value) => get(settings).collapseAiAnswers = $$value); delegated("input", textarea, commit); bind_value(textarea, () => get(settings).customCss, ($$value) => get(settings).customCss = $$value); delegated("click", button_1, copyTheme); delegated("change", input_7, commit); bind_checked(input_7, () => get(settings).autoPage, ($$value) => get(settings).autoPage = $$value); delegated("change", input_9, commit); bind_checked(input_9, () => get(settings).removeAds, ($$value) => get(settings).removeAds = $$value); delegated("change", input_10, commit); bind_checked(input_10, () => get(settings).cleanLinks, ($$value) => get(settings).cleanLinks = $$value); delegated("change", select_1, commit); bind_select_value(select_1, () => get(settings).openLinks, ($$value) => get(settings).openLinks = $$value); delegated("change", input_11, commit); bind_checked(input_11, () => get(settings).markOfficial, ($$value) => get(settings).markOfficial = $$value); delegated("change", select_2, chooseProvider); bind_select_value(select_2, () => get(settings).aiProvider, ($$value) => get(settings).aiProvider = $$value); delegated("change", input_14, commit); bind_value(input_14, () => get(settings).aiApiKey, ($$value) => get(settings).aiApiKey = $$value); delegated("change", input_15, commit); bind_value(input_15, () => get(settings).aiBaseUrl, ($$value) => get(settings).aiBaseUrl = $$value); delegated("change", input_16, commit); bind_value(input_16, () => get(settings).aiModel, ($$value) => get(settings).aiModel = $$value); delegated("click", button_5, loadModels); delegated("change", input_17, commit); bind_group(binding_group_2, [], input_17, () => get(settings).blockAction, ($$value) => get(settings).blockAction = $$value); delegated("change", input_18, commit); bind_group(binding_group_2, [], input_18, () => get(settings).blockAction, ($$value) => get(settings).blockAction = $$value); delegated("keydown", input_20, (e) => e.key === "Enter" && addSubscription()); bind_value(input_20, () => get(newSubscription), ($$value) => set(newSubscription, $$value)); delegated("click", button_8, addSubscription); delegated("input", textarea_2, commit); bind_value(textarea_2, () => get(settings).rules, ($$value) => get(settings).rules = $$value); delegated("change", input_21, saveDav); bind_checked(input_21, () => dav.enabled, ($$value) => dav.enabled = $$value); append($$anchor, fragment); pop(); } delegate([ "click", "change", "input", "keydown" ]); var GEAR_ICON = ""; function isSettingsOpen() { return !!open; } var open = null; function closeSettings() { if (!open) return; unmount(open.app); open.host.remove(); open = null; } function openSettings(options) { if (open) return; const host = document.createElement("div"); host.id = "bettersearch-settings"; host.dataset.theme = options.getTheme(); document.documentElement.append(host); open = { host, app: mount(Settings, { target: host.attachShadow({ mode: "open" }), props: { settings: options.getSettings(), onchange: options.onChange, onclose: closeSettings, refreshSubscriptions: options.refreshSubscriptions, subscriptionStatus: options.subscriptionStatus, listModels: options.listModels, sync: options.sync, getSettings: options.getSettings } }) }; } function toggleSettings(options) { if (open) closeSettings(); else openSettings(options); } var GEAR_ROOM = 52; function addGearButton(bar, options) { if (!bar || document.querySelector(".bs-gear")) return; const button = document.createElement("button"); button.type = "button"; button.className = "bs-gear"; button.title = t("gear.title"); button.setAttribute("aria-label", t("settings.title")); button.innerHTML = GEAR_ICON; Object.assign(button.style, { position: "absolute", top: "50%", right: "-52px", transform: "translateY(-50%)", width: "40px", height: "40px", padding: "0", border: "0", borderRadius: "50%", background: "transparent", color: "inherit", cursor: "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center" }); button.addEventListener("click", () => toggleSettings(options)); if (bar.getBoundingClientRect().right + GEAR_ROOM > document.documentElement.clientWidth) { Object.assign(button.style, { position: "fixed", top: "auto", right: "16px", bottom: "calc(16px + env(safe-area-inset-bottom))", transform: "none", width: "44px", height: "44px", zIndex: "2147483645", background: "var(--bs-gear-bg)", boxShadow: "0 2px 8px rgba(0, 0, 0, .2)" }); document.body.append(button); return; } if (getComputedStyle(bar).position === "static") bar.style.position = "relative"; bar.append(button); } function pageIsDark() { for (const el of [document.body, document.documentElement]) { if (!el) continue; const rgb = getComputedStyle(el).backgroundColor.match(/[\d.]+/g)?.map(Number); if (!rgb || rgb.length < 3 || rgb[3] === 0) continue; const [r, g, b] = rgb; return .2126 * r + .7152 * g + .0722 * b < 128; } const scheme = getComputedStyle(document.documentElement).colorScheme; return /dark/.test(scheme) && (!/light/.test(scheme) || matchMedia("(prefers-color-scheme: dark)").matches); } function syncTheme() { const theme = pageIsDark() ? "dark" : "light"; if (document.documentElement.dataset.bsTheme !== theme) document.documentElement.dataset.bsTheme = theme; return theme; } var CONFIG_KEY = "sync:webdav"; var DOC_KEY = "sync:doc"; var STATUS_KEY = "sync:status"; var INTERVAL_MS = 6e5; var DEBOUNCE_MS = 5e3; var Sync = class { options; timer = 0; running = null; constructor(options) { this.options = options; } config() { return store.get(CONFIG_KEY, { enabled: false, url: "", username: "", password: "" }); } setConfig(config) { store.set(CONFIG_KEY, config); if (!config.enabled) clearTimeout(this.timer); } status() { return store.get(STATUS_KEY, { at: null, error: null }); } ready() { const c = this.config(); return c.enabled && !!c.url.trim() && !!c.username.trim(); } changed(settings) { if (!this.ready()) return; const previous = store.get(DOC_KEY, null); const doc = stampLocal(previous, settings, Date.now()); if (previous && sameContent(doc, previous)) return; store.set(DOC_KEY, doc); this.schedule(); } start() { if (this.ready() && Date.now() - (this.status().at ?? 0) >= INTERVAL_MS) this.schedule(0); } schedule(delay = DEBOUNCE_MS) { clearTimeout(this.timer); this.timer = window.setTimeout(() => { if (this.options.busy()) this.schedule(); else this.now(); }, delay); } now() { clearTimeout(this.timer); this.running ??= this.run().finally(() => this.running = null); return this.running; } async run() { const config = this.config(); let status; try { const settings = this.options.settings(); const now = Date.now(); const { doc } = await runSync(sendRequest, config, stampLocal(store.get(DOC_KEY, null), settings, now), now); if (this.options.settings() === settings) { store.set(DOC_KEY, { ...doc, history: void 0 }); const next = applyDoc(settings, doc); if (JSON.stringify(next) !== JSON.stringify(settings)) this.options.apply(next); } else this.schedule(); status = { at: Date.now(), error: null }; } catch (error) { status = { at: this.status().at, error: error.message }; } store.set(STATUS_KEY, status); return status; } }; var DURATION_MS = 6e3; var current = null; function dismiss() { if (!current) return; clearTimeout(current.timer); current.el.remove(); current = null; } function showToast(message, action) { dismiss(); const el = document.createElement("div"); el.className = CLASSES.toast; el.setAttribute("role", "status"); const text = document.createElement("span"); text.textContent = message; el.append(text); if (action) { const button = document.createElement("button"); button.type = "button"; button.textContent = action.label; button.addEventListener("click", () => { dismiss(); action.run(); }); el.append(button); } document.body.append(el); current = { el, timer: window.setTimeout(dismiss, DURATION_MS) }; } function run(adapter) { let settings = loadSettings(store); const sites = new SiteDirectory(store, fetchText, (shard) => shardUrls(shard, settings.githubProxy), () => page.apply()); const page = new Page(adapter, { sites: () => settings.markOfficial ? sites : null, assistant: new Assistant({ settings: () => settings, sources: () => page.sources(), openSettings: () => openSettings(panel) }), onBlockSite(host) { const rule = siteRule(host); update({ ...settings, rules: addRule(settings.rules, rule) }); showToast(t("block.toast", { site: siteOf(host) }), { label: t("block.undo"), run: () => update({ ...settings, rules: removeRule(settings.rules, rule) }) }); } }); const pager = new Pager(adapter); const sync = new Sync({ settings: () => settings, apply(next) { update(next); refreshSubscriptions(); }, busy: isSettingsOpen }); const allRules = () => combinedRules(store, settings.rules, settings.subscriptions); async function refreshSubscriptions(force = false) { const now = Date.now(); const due = settings.subscriptions.filter((s) => s.enabled && (force || isStale(cachedList(store, s), now))); if (!due.length) return; await Promise.all(due.map((s) => refreshSubscription(store, s, fetchText))); page.update(settings, allRules()); } const panel = { getSettings: () => settings, getTheme: syncTheme, onChange: (next) => { const added = next.subscriptions.length > settings.subscriptions.length; update(next); if (added) refreshSubscriptions(); }, refreshSubscriptions: () => refreshSubscriptions(true), sync: { config: () => sync.config(), setConfig: (config) => sync.setConfig(config), status: () => sync.status(), now: () => sync.now() }, async listModels(config) { const { status, body } = await sendRequest(modelsRequest(config)); if (status < 200 || status >= 300) throw new Error(errorMessage(body) ?? `HTTP ${status}`); return parseModels(body); }, subscriptionStatus: (sub) => { const list = cachedList(store, sub); const failure = lastFailure(store, sub); return { fetchedAt: list?.fetchedAt ?? null, ruleCount: list ? list.rules.split("\n").filter((l) => l.trim() && !l.trim().startsWith("#")).length : 0, error: failure?.message ?? null }; } }; function applyGlobal() { document.documentElement.classList.toggle(NO_ADS_CLASS, settings.removeAds); document.documentElement.dataset.bsEngine = adapter.id; setCustomCss(settings.customCss); } function update(next) { saveSettings(store, next); show(next); sync.changed(next); } function show(next) { settings = next; page.grid.invalidate(); applyGlobal(); page.update(settings, allRules()); pager.sync(settings); } function refresh() { injectStyle(adapter.adSelectors, LAYOUT_CSS + pagerCss(adapter.paginationSelector)); syncTheme(); page.apply(); pager.sync(settings); addGearButton(adapter.searchBar(document), panel); } function start() { syncTheme(); page.update(settings, allRules()); pager.sync(settings); addGearButton(adapter.searchBar(document), panel); refreshSubscriptions(); sync.start(); new MutationObserver(refresh).observe(document.body, { childList: true, subtree: true }); let resizeTimer = 0; window.addEventListener("resize", () => { clearTimeout(resizeTimer); resizeTimer = window.setTimeout(() => { page.grid.invalidate(); page.apply(); }, 100); }); } onStoreChange("settings", () => show(loadSettings(store))); injectStyle(adapter.adSelectors, LAYOUT_CSS + pagerCss(adapter.paginationSelector)); applyGlobal(); registerMenuCommand(t("menu.settings"), () => toggleSettings(panel)); window.addEventListener("keydown", (event) => { if (event.altKey && event.code === "Comma") { event.preventDefault(); toggleSettings(panel); } }); if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", start, { once: true }); else start(); } setLocale(detectLocale(navigator.languages ?? [navigator.language])); var adapter = adapterForHost(location.hostname); if (adapter) { if (document.documentElement) run(adapter); else new MutationObserver((_, observer) => { if (!document.documentElement) return; observer.disconnect(); run(adapter); }).observe(document, { childList: true }); } })();