@nsnanocat/preference-panes 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api.js ADDED
@@ -0,0 +1,1622 @@
1
+ (function () {
2
+ 'use strict';
3
+
4
+ class URLSearchParams {
5
+ constructor(params, onUpdate) {
6
+ switch (typeof params) {
7
+ case "string": {
8
+ if (params.length === 0)
9
+ break;
10
+ if (params.startsWith("?"))
11
+ params = params.slice(1);
12
+ const pairs = params.split("&").map(pair => {
13
+ const separator = pair.indexOf("=");
14
+ return separator < 0 ? [pair, ""] : [pair.slice(0, separator), pair.slice(separator + 1)];
15
+ });
16
+ pairs.forEach(([key, value]) => {
17
+ this.#params.push(key ? this.#decodeQueryComponent(key) : key);
18
+ this.#values.push(this.#decodeQueryComponent(value));
19
+ });
20
+ break;
21
+ }
22
+ case "object":
23
+ if (Array.isArray(params)) {
24
+ Object.entries(params).forEach(([key, value]) => {
25
+ this.#params.push(key);
26
+ this.#values.push(value);
27
+ });
28
+ }
29
+ else if (Symbol.iterator in Object(params)) {
30
+ for (const [key, value] of params) {
31
+ this.#params.push(key);
32
+ this.#values.push(value);
33
+ }
34
+ }
35
+ break;
36
+ }
37
+ this.#updateSearchString(this.#params, this.#values);
38
+ this.#onUpdate = onUpdate;
39
+ }
40
+ // Create 2 seperate arrays for the params and values to make management and lookup easier.
41
+ #param = "";
42
+ #params = [];
43
+ #values = [];
44
+ #onUpdate;
45
+ #decodeQueryComponent(str) {
46
+ return decodeURIComponent(str.replace(/\+/g, " "));
47
+ }
48
+ #encodeQueryComponent(str) {
49
+ return encodeURIComponent(str)
50
+ .replace(/%20/g, "+")
51
+ .replace(/[!'()~]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
52
+ }
53
+ // Update the search property of the URL instance with the new params and values.
54
+ #updateSearchString(params, values) {
55
+ if (params.length === 0)
56
+ this.#param = "";
57
+ else
58
+ this.#param = params
59
+ .map((param, index) => {
60
+ switch (typeof values[index]) {
61
+ case "object":
62
+ return `${this.#encodeQueryComponent(param)}=${this.#encodeQueryComponent(JSON.stringify(values[index]))}`;
63
+ case "boolean":
64
+ case "number":
65
+ case "string":
66
+ return `${this.#encodeQueryComponent(param)}=${this.#encodeQueryComponent(values[index])}`;
67
+ case "undefined":
68
+ default:
69
+ return this.#encodeQueryComponent(param);
70
+ }
71
+ })
72
+ .join("&");
73
+ this.#onUpdate?.(this.#param);
74
+ }
75
+ // Add a given param with a given value to the end.
76
+ append(name, value) {
77
+ this.#params.push(name);
78
+ this.#values.push(value);
79
+ this.#updateSearchString(this.#params, this.#values);
80
+ }
81
+ // Remove all occurances of a given param
82
+ delete(name, value) {
83
+ while (this.#params.indexOf(name) > -1) {
84
+ this.#values.splice(this.#params.indexOf(name), 1);
85
+ this.#params.splice(this.#params.indexOf(name), 1);
86
+ }
87
+ this.#updateSearchString(this.#params, this.#values);
88
+ }
89
+ // Return an array to be structured in this way: [[param1, value1], [param2, value2]] to mimic the native method's ES6 iterator.
90
+ entries() {
91
+ return this.#params.map((param, index) => [param, this.#values[index]]);
92
+ }
93
+ // Return the value matched to the first occurance of a given param.
94
+ get(name) {
95
+ return this.#values[this.#params.indexOf(name)];
96
+ }
97
+ // Return all values matched to all occurances of a given param.
98
+ getAll(name) {
99
+ return this.#values.filter((value, index) => this.#params[index] === name);
100
+ }
101
+ // Return a boolean to indicate whether a given param exists.
102
+ has(name, value) {
103
+ return this.#params.indexOf(name) > -1;
104
+ }
105
+ // Return an array of the param names to mimic the native method's ES6 iterator.
106
+ keys() {
107
+ return this.#params;
108
+ }
109
+ // Set a given param to a given value.
110
+ set(name, value) {
111
+ if (this.#params.indexOf(name) === -1) {
112
+ this.append(name, value); // If the given param doesn't already exist, append it.
113
+ }
114
+ else {
115
+ let first = true;
116
+ const newValues = [];
117
+ // If the param already exists, change the value of the first occurance and remove any remaining occurances.
118
+ this.#params = this.#params.filter((currentParam, index) => {
119
+ if (currentParam !== name) {
120
+ newValues.push(this.#values[index]);
121
+ return true;
122
+ // If the currentParam matches the one being changed and it's the first one, keep the param and change its value to the given one.
123
+ }
124
+ else if (first) {
125
+ first = false;
126
+ newValues.push(value);
127
+ return true;
128
+ }
129
+ // If the currentParam matches the one being changed, but it's not the first, remove it.
130
+ return false;
131
+ });
132
+ this.#values = newValues;
133
+ this.#updateSearchString(this.#params, this.#values);
134
+ }
135
+ }
136
+ // Sort all key/value pairs, if any, by their keys then by their values.
137
+ sort() {
138
+ // Call entries to make sorting easier, then rewrite the params and values in the new order.
139
+ const sortedPairs = this.entries().sort();
140
+ this.#params = [];
141
+ this.#values = [];
142
+ sortedPairs.forEach(pair => {
143
+ this.#params.push(pair[0]);
144
+ this.#values.push(pair[1]);
145
+ });
146
+ this.#updateSearchString(this.#params, this.#values);
147
+ }
148
+ // Return the search string without the '?'.
149
+ toString = () => this.#param;
150
+ // Return and array of the param values to mimic the native method's ES6 iterator..
151
+ values = () => this.#values.values();
152
+ }
153
+
154
+ class URL {
155
+ constructor(url, base) {
156
+ switch (typeof url) {
157
+ case "string": {
158
+ const urlIsValid = /^(blob:|file:)?[a-zA-z]+:\/\/.*/.test(url);
159
+ const baseIsValid = base ? /^(blob:|file:)?[a-zA-z]+:\/\/.*/.test(base) : false;
160
+ // If a string is passed for url instead of location or link, then set the properties of the URL instance.
161
+ if (urlIsValid)
162
+ this.href = url;
163
+ // If the url isn't valid, but the base is, then prepend the base to the url.
164
+ else if (baseIsValid)
165
+ this.href = base + url;
166
+ // If no valid url or base is given, then throw a type error.
167
+ else
168
+ throw new TypeError('URL string is not valid. If using a relative url, a second argument needs to be passed representing the base URL. Example: new URL("relative/path", "http://www.example.com");');
169
+ break;
170
+ }
171
+ case "object":
172
+ break;
173
+ default:
174
+ throw new TypeError("Invalid argument type.");
175
+ }
176
+ }
177
+ #url = {
178
+ hash: "",
179
+ host: "",
180
+ hostname: "",
181
+ href: "",
182
+ password: "",
183
+ pathname: "",
184
+ port: Number.NaN,
185
+ protocol: "",
186
+ search: "",
187
+ searchParams: new URLSearchParams(""),
188
+ username: "",
189
+ };
190
+ // refer: http://www.ietf.org/rfc/rfc3986.txt
191
+ static #URLRegExp = /^(?<scheme>([^:\/?#]+):)?(?:\/\/(?<authority>[^\/?#]*))?(?<path>[^?#]*)(?<query>\?([^#]*))?(?<hash>#(.*))?$/;
192
+ static #AuthorityRegExp = /^(?<authentication>(?<username>[^:]*)(:(?<password>[^@]*))?@)?(?<hostname>[^:]+)(:(?<port>\d+))?$/;
193
+ get hash() {
194
+ return this.#url.hash;
195
+ }
196
+ set hash(value) {
197
+ if (value.length !== 0) {
198
+ if (value.startsWith("#"))
199
+ value = value.slice(1);
200
+ this.#url.hash = `#${encodeURIComponent(value)}`;
201
+ }
202
+ }
203
+ get host() {
204
+ return this.port.length > 0 ? `${this.hostname}:${this.port}` : this.hostname;
205
+ }
206
+ set host(value) {
207
+ [this.hostname, this.port] = value.split(":", 2);
208
+ }
209
+ get hostname() {
210
+ return encodeURIComponent(this.#url.hostname);
211
+ }
212
+ set hostname(value) {
213
+ this.#url.hostname = value ?? "";
214
+ }
215
+ get href() {
216
+ let authority = "";
217
+ if (this.username.length > 0) {
218
+ authority += this.username;
219
+ if (this.password.length > 0)
220
+ authority += `:${this.password}`;
221
+ authority += "@";
222
+ }
223
+ return `${this.protocol}//${authority}${this.host}${this.pathname}${this.search}${this.hash}`;
224
+ }
225
+ set href(value) {
226
+ if (value.startsWith("blob:") || value.startsWith("file:"))
227
+ value = value.slice(5);
228
+ const urlMatch = value.match(URL.#URLRegExp);
229
+ if (!urlMatch)
230
+ throw new TypeError("Invalid URL format.");
231
+ this.protocol = urlMatch.groups.scheme ?? "";
232
+ const authorityMatch = urlMatch.groups.authority.match(URL.#AuthorityRegExp);
233
+ this.username = authorityMatch.groups.username ?? "";
234
+ this.password = authorityMatch.groups.password ?? "";
235
+ this.hostname = authorityMatch.groups.hostname ?? "";
236
+ this.port = authorityMatch.groups.port ?? "";
237
+ this.pathname = urlMatch.groups.path ?? "";
238
+ this.search = urlMatch.groups.query ?? "";
239
+ this.hash = urlMatch.groups.hash ?? "";
240
+ }
241
+ get origin() {
242
+ return `${this.protocol}//${this.host}`;
243
+ }
244
+ get password() {
245
+ return encodeURIComponent(this.#url.password);
246
+ }
247
+ set password(value) {
248
+ if (this.username.length > 0)
249
+ this.#url.password = value ?? "";
250
+ }
251
+ get pathname() {
252
+ return `/${this.#url.pathname}`;
253
+ }
254
+ set pathname(value) {
255
+ value = `${value}`;
256
+ if (value.startsWith("/"))
257
+ value = value.slice(1);
258
+ this.#url.pathname = value;
259
+ }
260
+ get port() {
261
+ if (Number.isNaN(this.#url.port))
262
+ return "";
263
+ const port = this.#url.port.toString();
264
+ if (this.protocol === "ftp:" && port === "21")
265
+ return "";
266
+ if (this.protocol === "http:" && port === "80")
267
+ return "";
268
+ if (this.protocol === "https:" && port === "443")
269
+ return "";
270
+ return port;
271
+ }
272
+ set port(value) {
273
+ switch (value) {
274
+ case "":
275
+ this.#url.port = Number.NaN;
276
+ break;
277
+ default: {
278
+ const port = Number.parseInt(value, 10);
279
+ if (port >= 0 && port < 65535)
280
+ this.#url.port = port;
281
+ }
282
+ }
283
+ }
284
+ get protocol() {
285
+ return `${this.#url.protocol}:`;
286
+ }
287
+ set protocol(value) {
288
+ if (value.endsWith(":"))
289
+ value = value.slice(0, -1);
290
+ this.#url.protocol = value;
291
+ }
292
+ get search() {
293
+ if (this.#url.search.length > 0)
294
+ return `?${this.#url.search}`;
295
+ else
296
+ return "";
297
+ }
298
+ set search(value) {
299
+ value = `${value}`;
300
+ if (value.startsWith("?"))
301
+ value = value.slice(1);
302
+ this.#url.search = value;
303
+ this.#url.searchParams = new URLSearchParams(this.#url.search, search => {
304
+ this.#url.search = search;
305
+ });
306
+ }
307
+ get searchParams() {
308
+ return this.#url.searchParams;
309
+ }
310
+ get username() {
311
+ return encodeURIComponent(this.#url.username);
312
+ }
313
+ set username(value) {
314
+ this.#url.username = value ?? "";
315
+ }
316
+ static parse = (url, base) => new URL(url, base);
317
+ /**
318
+ * Returns the string representation of the URL.
319
+ *
320
+ * @returns {string} The href of the URL.
321
+ */
322
+ toString = () => this.href;
323
+ /**
324
+ * Converts the URL object properties to a JSON string.
325
+ *
326
+ * @returns {string} A JSON string representation of the URL object.
327
+ */
328
+ toJSON = () => JSON.stringify({
329
+ hash: this.hash,
330
+ host: this.host,
331
+ hostname: this.hostname,
332
+ href: this.href,
333
+ origin: this.origin,
334
+ password: this.password,
335
+ pathname: this.pathname,
336
+ port: this.port,
337
+ protocol: this.protocol,
338
+ search: this.search,
339
+ searchParams: this.searchParams,
340
+ username: this.username,
341
+ });
342
+ }
343
+
344
+ var assets = {"page":{"type":"text/html","body":"<!doctype html>\n<html lang=\"zh-CN\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1,viewport-fit=cover\">\n <meta name=\"color-scheme\" content=\"light dark\">\n <title>Module Preferences</title>\n <style>body { margin: 0; }</style>\n </head>\n <body>\n <main id=\"preferences\"></main>\n <script type=\"module\" src=\"/settings/assets/app.mjs?v=0.8.0\"></script>\n </body>\n</html>\n"},"/settings/assets/app.mjs":{"type":"text/javascript","body":"/**\n * 校验原始路径片段,不进行 URL 编码转换。\n * Validate raw path segments without URL encoding conversion.\n * @param {string[]} parts 原始路径片段 / Raw path segments.\n * @returns {string[]} 同一数组,不复制或修改 / The same array without copying or mutation.\n * @throws {TypeError} 空片段、非法字符或原型属性名 / Empty segments, invalid characters or prototype property names.\n */\nfunction validatePathParts(parts) {\n if (!parts.every(part => typeof part === \"string\" && /^[a-zA-Z0-9_-]+$/.test(part) && ![\"__proto__\", \"prototype\", \"constructor\"].includes(part))) throw new TypeError(\"Invalid key path\");\n return parts;\n}\n\n/**\n * BoxJS 的共同目录:模块、存储根和展示元数据都来自同一份 JSON。\n * Shared BoxJS catalog deriving modules, storage roots and metadata from one JSON document.\n */\nclass BoxJS {\n /**\n * 建立路径索引,不解析控件类型,也不读写持久化存储。\n * Index field paths without interpreting controls or accessing persistence.\n * @param {unknown} input 字段数组、单个 app 或 apps 订阅 / Field array, app or apps subscription.\n */\n constructor(input) {\n if (!input || typeof input !== \"object\") throw new TypeError(\"Expected BoxJS JSON\");\n this.document = JSON.parse(JSON.stringify(input));\n const apps = Array.isArray(this.document) ? [{ settings: this.document }] : (this.document.apps ?? [this.document]);\n if (!Array.isArray(apps)) throw new TypeError(\"Expected BoxJS apps array\");\n this.modules = new Map();\n for (const app of apps) {\n if (!app || !Array.isArray(app.settings)) throw new TypeError(\"Expected BoxJS settings array\");\n for (const entry of app.settings) {\n if (typeof entry.id !== \"string\") throw new TypeError(\"BoxJS settings require string IDs\");\n if (!entry.id.startsWith(\"@\")) {\n if (Array.isArray(this.document)) throw new TypeError(\"BoxJS settings require @root.path IDs\");\n continue;\n }\n const [storageKey, ...parts] = entry.id.slice(1).split(\".\");\n if (!storageKey || storageKey.startsWith(\"@\") || parts.length < 2) throw new TypeError(\"A BoxJS setting must be below a literal storage root and module\");\n validatePathParts(parts);\n const module = parts[0];\n let target = this.modules.get(module);\n if (!target) {\n target = { module, storageKey, entries: [], owners: new Set() };\n this.modules.set(module, target);\n }\n if (target.storageKey !== storageKey) throw new TypeError(`A module must use one storage root: ${module}`);\n target.entries.push(entry);\n target.owners.add(app);\n }\n }\n this.metadata = metadata(Array.isArray(this.document) ? {} : this.document);\n for (const target of this.modules.values()) target.metadata = target.owners.size === 1 ? metadata([...target.owners][0]) : {};\n }\n\n /**\n * 提取一个模块的原生 BoxJS,保留所属 app 的元数据。\n * Select a module's native BoxJS while retaining owning-app metadata.\n * @param {string} module 模块标识 / Module identifier.\n * @returns {unknown} 可直接用作配置 Mock 的 JSON / JSON suitable for a configuration Mock.\n */\n select(module) {\n const target = this.modules.get(module);\n if (!target) throw new TypeError(`No BoxJS settings for module: ${module}`);\n if (Array.isArray(this.document)) return target.entries;\n const apps = [...target.owners].map(app => ({ ...app, settings: app.settings.filter(entry => target.entries.includes(entry)) }));\n return this.document.apps ? { ...this.document, apps } : apps[0];\n }\n\n /**\n * 取得本次导入的唯一模块,避免把模块数据变成项目目录。\n * Get the single imported module without turning module data into a project directory.\n * @returns {object} 唯一模块的目录项 / The single module entry.\n */\n get module() {\n if (this.modules.size !== 1) throw new TypeError(\"Import BoxJS JSON for exactly one module\");\n return this.modules.values().next().value;\n }\n}\n\n/**\n * 保留标准 BoxJS 展示信息;script 仅为元数据,不执行。\n * Retain standard BoxJS presentation data; script is metadata only and never executed.\n * @param {object} source BoxJS app 或订阅 / BoxJS app or subscription.\n * @returns {object} 经过类型检查的展示信息 / Type-checked presentation metadata.\n */\nfunction metadata(source) {\n const result = {};\n for (const key of [\"id\", \"name\", \"author\", \"repo\", \"script\", \"icon\", \"description\", \"desc\", \"icons\", \"descs\"]) {\n if (source[key] === undefined) continue;\n const multiple = key === \"icons\" || key === \"descs\";\n const values = multiple ? source[key] : [source[key]];\n if (!Array.isArray(values) || values.some(item => typeof item !== \"string\")) throw new TypeError(`Invalid BoxJS app ${key}`);\n result[key] = multiple ? [...values] : source[key];\n }\n return result;\n}\n\n/**\n * 统一解析模块页的资源地址:Header 优先于查询参数,再使用模块约定。\n * Resolve module resource locations: headers override query parameters and module conventions.\n * @param {URL} url 已解析的页面请求地址 / Parsed page request URL.\n * @param {Record<string, string | undefined>} [headers] 请求头,名称不区分大小写 / Case-insensitive request headers.\n * @returns {{url: string, module: string, json: string, css: string}} 页面上下文与两个资源输入 / Page context and two resource inputs.\n */\nfunction pageInputs(url, headers = {}) {\n const match = /^\\/settings\\/([a-zA-Z0-9_-]+)\\/?$/.exec(url.pathname);\n if (!match) throw new TypeError(\"Open a concrete module URL\");\n const module = match[1];\n const values = Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));\n const json = values[\"x-preferencepanes-json\"] ?? url.searchParams.get(\"json\") ?? `/configs/${module}`;\n const css = values[\"x-preferencepanes-css\"] ?? url.searchParams.get(\"css\") ?? \"\";\n if (!json.trim()) throw new TypeError(\"JSON resource URL is required\");\n return { url: url.href, module, json, css };\n}\n\n/**\n * 创建元素,所有展示文本通过 textContent 写入。\n * Create elements and assign display text through textContent only.\n * @template {keyof HTMLElementTagNameMap} T\n * @param {T} tag 元素标签 / Element tag.\n * @param {string} className 样式类名 / CSS class.\n * @param {string} [text] 纯文本 / Plain text.\n * @returns {HTMLElementTagNameMap[T]} 创建的元素 / Created element.\n */\nfunction element(tag, className, text) {\n const node = document.createElement(tag);\n node.className = className;\n if (text !== undefined) node.textContent = text;\n return node;\n}\n\n/**\n * 元数据地址只允许 HTTP(S) 和相对地址。\n * Allow only HTTP(S) and relative metadata addresses.\n * @param {string} value 元数据地址 / Metadata address.\n * @returns {string} 完整地址 / Absolute address.\n */\nfunction resourceURL(value) {\n const url = new URL(value, document.baseURI);\n if (![\"http:\", \"https:\"].includes(url.protocol)) throw new TypeError(\"Metadata URLs must use HTTP(S)\");\n return url.href;\n}\n\n/**\n * 展示标准 BoxJS 图标;icons 保持透明/彩色语义,不解释为亮暗版本。\n * Display standard BoxJS icons, preserving transparent/color rather than light/dark semantics.\n * @param {import(\"../index.js\").BoxJSMetadata} metadata 展示信息 / Presentation metadata.\n * @param {string} className 样式 / CSS class.\n * @returns {HTMLImageElement | null} 图标或无图标 / Icon or no icon.\n */\nfunction icon(metadata, className) {\n const source = metadata.icon || metadata.icons?.[1] || metadata.icons?.[0];\n if (!source) return null;\n const image = element(\"img\", className);\n image.src = resourceURL(source);\n image.alt = \"\";\n return image;\n}\n\n/**\n * 共享加载失败视图,不创建配置表单或数据读取。\n * Share a load-error view without creating controls or reading settings.\n * @param {Error} error 失败原因 / Failure reason.\n * @param {() => unknown} retry 重试动作 / Retry action.\n * @returns {HTMLElement} 错误视图 / Error view.\n */\nfunction errorView(error, retry) {\n const view = element(\"section\", \"pp-error\");\n const button = element(\"button\", \"\", \"重新读取\");\n button.type = \"button\";\n button.onclick = retry;\n view.append(element(\"p\", \"\", `加载失败:${error.message}`), button);\n return view;\n}\n\nvar defaults = \"/* 分组列表沿用 Bilibili 设置页的行结构,样式限定在面板内。\\n * Grouped rows follow the Bilibili settings layout, scoped to the panel. */\\n.pp-panel {\\n --pp-text: #18191c;\\n --pp-background: #f6f7f8;\\n --pp-surface: #fff;\\n --pp-border: #e3e5e7;\\n --pp-muted: #9499a0;\\n --pp-accent: #fb7299;\\n font:\\n 15px / 1.5 -apple-system,\\n BlinkMacSystemFont,\\n \\\"Segoe UI\\\",\\n sans-serif;\\n color: var(--pp-text);\\n background: var(--pp-background);\\n position: relative;\\n min-height: 100vh;\\n}\\n.pp-panel * {\\n box-sizing: border-box;\\n letter-spacing: 0;\\n}\\n.pp-header {\\n height: calc(52px + env(safe-area-inset-top));\\n padding: env(safe-area-inset-top) 12px 0;\\n display: flex;\\n align-items: center;\\n background: var(--pp-surface);\\n border-bottom: 1px solid var(--pp-border);\\n position: sticky;\\n top: 0;\\n z-index: 1;\\n}\\n.pp-title {\\n font-size: 17px;\\n font-weight: 500;\\n margin: 0;\\n min-width: 0;\\n overflow-wrap: anywhere;\\n}\\n.pp-brand {\\n flex: 1;\\n min-width: 0;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n gap: 8px;\\n text-align: center;\\n}\\n.pp-brand-icon {\\n display: none;\\n flex: none;\\n width: 28px;\\n height: 28px;\\n}\\n.pp-brand-icon:not(:empty) {\\n display: block;\\n}\\n.pp-brand-icon img {\\n display: block;\\n width: 100%;\\n height: 100%;\\n object-fit: contain;\\n}\\n.pp-nav-spacer {\\n width: 44px;\\n flex: none;\\n}\\n.pp-panel button {\\n font: inherit;\\n cursor: pointer;\\n border: 0;\\n background: none;\\n color: inherit;\\n}\\n.pp-panel .pp-back {\\n width: 44px;\\n height: 44px;\\n flex: none;\\n font-size: 34px;\\n line-height: 32px;\\n padding: 0;\\n}\\n.pp-panel button:disabled {\\n opacity: 0.5;\\n cursor: wait;\\n}\\n.pp-viewport {\\n position: relative;\\n height: calc(100vh - 52px - env(safe-area-inset-top));\\n overflow: hidden;\\n}\\n:root[data-preference-panes-embedded] .pp-header {\\n display: none;\\n}\\n:root[data-preference-panes-embedded] .pp-viewport {\\n height: 100vh;\\n}\\n@supports (height: 100dvh) {\\n .pp-viewport {\\n height: calc(100dvh - 52px - env(safe-area-inset-top));\\n }\\n :root[data-preference-panes-embedded] .pp-viewport {\\n height: 100dvh;\\n }\\n}\\n.pp-fields,\\n.pp-choice-page {\\n position: absolute;\\n inset: 0;\\n overflow: auto;\\n padding: 12px max(16px, calc((100% - 688px) / 2)) calc(28px + env(safe-area-inset-bottom));\\n background: var(--pp-background);\\n}\\n.pp-panel .form-group {\\n margin: 0 0 12px;\\n}\\n.pp-panel .form-group__title {\\n font-size: 12px;\\n line-height: 17px;\\n font-weight: 400;\\n color: var(--pp-muted);\\n padding-left: 12px;\\n margin: 12px 0 6px;\\n}\\n.pp-panel .form-group__row {\\n border-radius: 8px;\\n overflow: hidden;\\n background: var(--pp-surface);\\n}\\n.pp-panel .form-row {\\n position: relative;\\n display: flex;\\n align-items: center;\\n width: 100%;\\n min-height: 46px;\\n padding: 12px;\\n border: 0;\\n border-bottom: 1px solid var(--pp-border);\\n background: var(--pp-surface);\\n gap: 12px;\\n}\\n.pp-panel .form-row:last-child {\\n border-bottom: 0;\\n}\\n.pp-panel .form-row__text {\\n flex: 1;\\n min-width: 0;\\n margin: 0;\\n display: flex;\\n flex-direction: column;\\n}\\n.pp-panel .form-row__title {\\n font-size: 15px;\\n line-height: 22px;\\n color: var(--pp-text);\\n text-align: left;\\n}\\n.pp-panel .form-row__subtitle {\\n font-size: 12px;\\n line-height: 18px;\\n color: var(--pp-muted);\\n overflow-wrap: anywhere;\\n margin-top: 2px;\\n}\\n.pp-choice-link {\\n display: flex;\\n align-items: center;\\n justify-content: flex-end;\\n gap: 8px;\\n max-width: 45%;\\n min-width: 44px;\\n min-height: 44px;\\n padding: 0;\\n text-align: right;\\n flex: 1;\\n}\\n.pp-summary {\\n color: var(--pp-muted);\\n font-size: 13px;\\n line-height: 18px;\\n display: -webkit-box;\\n -webkit-line-clamp: 2;\\n -webkit-box-orient: vertical;\\n overflow: hidden;\\n overflow-wrap: anywhere;\\n}\\n.pp-chevron {\\n color: var(--pp-muted);\\n font-size: 22px;\\n flex: none;\\n}\\n.pp-input {\\n font: inherit;\\n color: var(--pp-text);\\n background: var(--pp-surface);\\n border: 1px solid var(--pp-border);\\n border-radius: 6px;\\n padding: 8px;\\n min-width: 0;\\n max-width: 45%;\\n width: 45%;\\n}\\nselect.pp-input {\\n text-overflow: ellipsis;\\n font-size: 13px;\\n}\\n.pp-panel .pp-multiline {\\n display: block;\\n}\\n.pp-multiline .pp-input {\\n max-width: 100%;\\n width: 100%;\\n margin-top: 10px;\\n}\\n.pp-switch {\\n appearance: none;\\n -webkit-appearance: none;\\n position: relative;\\n flex: none;\\n width: 32px;\\n height: 20px;\\n max-width: none;\\n border: 0;\\n border-radius: 15px;\\n padding: 0;\\n background: #c9ccd0;\\n cursor: pointer;\\n transition: background 0.2s;\\n}\\n.pp-switch::before {\\n content: \\\"\\\";\\n position: absolute;\\n top: 3px;\\n left: 3px;\\n width: 14px;\\n height: 14px;\\n border-radius: 50%;\\n background: white;\\n transition: transform 0.2s;\\n}\\n.pp-switch:checked {\\n background: var(--pp-accent);\\n}\\n.pp-switch:checked::before {\\n transform: translateX(12px);\\n}\\n.pp-choice {\\n justify-content: space-between;\\n cursor: pointer;\\n}\\n.pp-choice input {\\n width: 20px;\\n height: 20px;\\n flex: none;\\n accent-color: var(--pp-accent);\\n margin: 0;\\n}\\n.pp-description {\\n font-size: 12px;\\n line-height: 1.6;\\n color: var(--pp-muted);\\n white-space: pre-wrap;\\n overflow-wrap: anywhere;\\n}\\n.pp-module-info {\\n display: flex;\\n gap: 12px;\\n margin: 12px 0;\\n}\\n.pp-module-icon {\\n width: 48px;\\n height: 48px;\\n object-fit: contain;\\n flex: none;\\n}\\n.pp-module-details {\\n min-width: 0;\\n overflow-wrap: anywhere;\\n}\\n.pp-module-source {\\n color: inherit;\\n text-decoration: underline;\\n}\\n.pp-maintenance {\\n margin-top: 24px;\\n}\\n.pp-actions {\\n display: flex;\\n flex-wrap: wrap;\\n gap: 8px;\\n}\\n.pp-actions button,\\n.pp-error button {\\n min-height: 44px;\\n padding: 8px 12px;\\n border-radius: 6px;\\n background: var(--pp-surface);\\n}\\n.pp-panel .pp-danger {\\n color: #e45656;\\n}\\n.pp-cache {\\n max-height: 320px;\\n overflow: auto;\\n white-space: pre-wrap;\\n overflow-wrap: anywhere;\\n}\\n.pp-toast {\\n pointer-events: none;\\n position: fixed;\\n bottom: calc(30px + env(safe-area-inset-bottom));\\n left: 50%;\\n transform: translateX(-50%);\\n max-width: 90vw;\\n padding: 10px 16px;\\n border-radius: 8px;\\n background: #333e;\\n color: white;\\n font-size: 13px;\\n z-index: 20;\\n}\\n.pp-toast[data-kind=\\\"error\\\"] {\\n background: #8d2424;\\n}\\n.pp-panel :focus-visible {\\n outline: 2px solid var(--pp-accent);\\n outline-offset: -2px;\\n}\\n@media (prefers-color-scheme: dark) {\\n .pp-panel {\\n --pp-text: #e3e5e7;\\n --pp-background: #17181a;\\n --pp-surface: #232427;\\n --pp-border: #343538;\\n }\\n}\\n:root[data-theme=\\\"dark\\\"] .pp-panel {\\n --pp-text: #e3e5e7;\\n --pp-background: #17181a;\\n --pp-surface: #232427;\\n --pp-border: #343538;\\n}\\n:root[data-theme=\\\"light\\\"] .pp-panel {\\n --pp-text: #18191c;\\n --pp-background: #f6f7f8;\\n --pp-surface: #fff;\\n --pp-border: #e3e5e7;\\n}\\n@media (prefers-reduced-motion: reduce) {\\n .pp-panel .pp-switch,\\n .pp-panel .pp-switch::before {\\n transition: none;\\n }\\n}\\n\";\n\n/**\n * 将 BoxJS 数组、app 或订阅转换为模块字段,保留原文件为唯一字段来源。\n * Normalize a BoxJS array, app or subscription using the source JSON as the field authority.\n * @param {unknown} config BoxJS JSON / BoxJS document.\n * @param {string} module API 第一段模块名 / First API path segment.\n * @returns {import(\"../index.js\").ModuleDefinition} 存储根和字段 / Storage root and fields.\n * @throws {TypeError} 配置结构、字段路径、默认值或展示属性无效 / Invalid configuration, field path, default or presentation attribute.\n */\nfunction normalizeBoxJs(config, module) {\n validatePathParts([module]);\n const target = new BoxJS(config).modules.get(module);\n if (!target) throw new TypeError(`No BoxJS settings for module: ${module}`);\n const { entries, storageKey, metadata } = target;\n const fields = [];\n for (const entry of entries) {\n const parts = entry.id.slice(1).split(\".\").slice(1);\n const type = { boolean: \"boolean\", checkboxes: \"array\", selects: \"select\", text: \"string\", textarea: \"string\", number: \"number\" }[entry.type];\n if (!type) throw new TypeError(`Unsupported BoxJS control: ${entry.type}`);\n const field = {\n key: parts.join(\".\"),\n type: type === \"select\" ? typeof entry.val : type,\n\n name: entry.name,\n description: entry.desc ?? \"\",\n control: entry.type,\n ...(entry.placeholder === undefined ? {} : { placeholder: entry.placeholder }),\n ...(entry.rows === undefined ? {} : { rows: entry.rows }),\n ...(entry.autoGrow === undefined ? {} : { autoGrow: entry.autoGrow }),\n };\n if (type === \"select\" && ![\"string\", \"number\", \"boolean\"].includes(field.type)) throw new TypeError(`Select requires a scalar val: ${entry.id}`);\n if (entry.items) field.options = entry.items.map(item => ({ key: item.key, label: item.label }));\n if (Object.hasOwn(entry, \"val\")) field.defaultValue = normalizeStoredValue(field, entry.val);\n if (\n typeof field.name !== \"string\" ||\n (field.placeholder !== undefined && typeof field.placeholder !== \"string\") ||\n (field.rows !== undefined && (!Number.isInteger(field.rows) || field.rows < 1)) ||\n (field.autoGrow !== undefined && typeof field.autoGrow !== \"boolean\") ||\n fields.some(other => other.key === field.key || other.key.startsWith(`${field.key}.`) || field.key.startsWith(`${other.key}.`))\n )\n throw new TypeError(`Invalid or overlapping BoxJS field: ${entry.id}`);\n if (field.options && (new Set(field.options.map(item => item.key)).size !== field.options.length || field.options.some(item => !scalar(item.key) || typeof item.label !== \"string\"))) throw new TypeError(`Invalid options: ${entry.id}`);\n if (Object.hasOwn(field, \"defaultValue\") && !validValue(field, field.defaultValue)) throw new TypeError(`Invalid BoxJS val: ${entry.id}`);\n fields.push(field);\n }\n if (!fields.length) throw new TypeError(`No BoxJS settings for module: ${module}`);\n const common = fields[0].key.split(\".\").slice(0, -1);\n for (const field of fields) while (!field.key.startsWith(`${common.join(\".\")}.`)) common.pop();\n return {\n module,\n storageKey,\n fields,\n settingsPath: common,\n ...(Object.keys(metadata).length ? { metadata } : {}),\n };\n}\n\n/**\n * 归一化 BoxJS 的字符串存储值,不改变普通文本内容。\n * Normalize BoxJS string persistence without changing free-text values.\n * @param {import(\"../index.js\").SettingsField} field 前端字段约束 / Frontend field constraints.\n * @param {unknown} value 存储值 / Stored value.\n * @returns {unknown} 转换后的控件值;是否允许写入由 validValue 单独校验 / Converted control value; write eligibility is checked separately by validValue.\n */\nfunction normalizeStoredValue(field, value) {\n switch (field.type) {\n case \"boolean\":\n if (value === \"true\" || value === \"false\") return value === \"true\";\n break;\n case \"number\":\n if (typeof value === \"string\" && value.trim() !== \"\") return Number(value);\n break;\n case \"array\":\n if (typeof value === \"string\") value = value === \"\" || value === \"[]\" ? [] : value.split(\",\");\n break;\n }\n if (field.options) {\n const match = item => field.options.find(option => String(option.key) === String(item))?.key ?? item;\n return field.type === \"array\" && Array.isArray(value) ? value.map(match) : match(value);\n }\n return value;\n}\n\n/**\n * 校验支持的标量范围,包括文本长度与数值有限性。\n * Validate supported scalar bounds, including text length and numeric finiteness.\n * @param {unknown} value 待检查值 / Value to inspect.\n * @returns {boolean} 是否为有效标量 / Whether the scalar is valid.\n */\nfunction scalar(value) {\n switch (typeof value) {\n case \"boolean\":\n return true;\n case \"string\":\n return value.length <= 2048;\n case \"number\":\n return Number.isFinite(value);\n default:\n return false;\n }\n}\n\n/**\n * 检查值类型、数组唯一性及声明的选项,不进行转换。\n * Check value type, array uniqueness and declared choices without coercion.\n * @param {import(\"../index.js\").SettingsField} field 前端归一化字段 / Normalized frontend field.\n * @param {unknown} value 待写入的 JSON 值 / JSON value to write.\n * @returns {boolean} 是否符合字段约束 / Whether the value satisfies field constraints.\n */\nfunction validValue(field, value) {\n if (field.type === \"array\") {\n if (!Array.isArray(value) || value.some(item => !scalar(item)) || new Set(value).size !== value.length) return false;\n } else if (typeof value !== field.type || !scalar(value)) return false;\n return !field.options || (field.type === \"array\" ? value : [value]).every(item => field.options.some(option => option.key === item));\n}\n\n/**\n * 单个模块的临时会话;离开页面后丢弃。\n * Transient module session discarded when leaving the page.\n * @typedef {object} ModuleSession\n * @property {AbortController} controller 读取请求的取消控制器 / Abort controller for reads.\n * @property {import(\"../index.js\").ModuleDefinition | null} definition 加载完成的配置,加载中为 null / Loaded configuration, or null while loading.\n * @property {import(\"./client.mjs\").ModuleSnapshot[\"values\"]} values 当前显示值 / Current display values.\n * @property {boolean} saving 是否正在写入 / Whether a mutation is in progress.\n */\n\n/**\n * 创建页面会话缓存;打开时重读,选项操作仅在 HTTP 200 后更新缓存。\n * Create a page-session cache; reload on open and mutate cache only after HTTP 200.\n * @param {import(\"./client.mjs\").PreferencesClientOptions} options 包内目录、请求与通知 / Internal catalog, requests and notifications.\n * @returns {import(\"./client.mjs\").PreferencesClient} 通用客户端 / Generic client.\n */\nfunction createPreferencesClient({ catalog, fetch: request = globalThis.fetch.bind(globalThis), notify = () => {}, timeout = 10000 }) {\n /**\n * 模块会话表\n * Module session map.\n * @type {Map<string, ModuleSession>}\n */\n const sessions = new Map();\n /**\n * 用 form 发送完整存储键;读取 404 交给调用方处理。\n * Send a complete storage key as form data; callers handle missing reads.\n * @param {string} path 完整 @root.path / Complete @root.path.\n * @param {\"get\" | \"set\" | \"delete\"} action 存储操作 / Storage operation.\n * @param {unknown} body set 值,其它操作忽略 / Set value, ignored by other operations.\n * @param {AbortSignal | undefined} signal 会话取消信号 / Session cancellation signal.\n * @returns {Promise<Response>} 未消费正文的响应 / Response with an unread body.\n * @throws {Error} 非 200 且非数据 GET 404、超时、取消或网络错误 / Non-200 status except missing-data GETs, timeout, cancellation or network error.\n */\n async function send(path, action, body, signal) {\n const controller = new AbortController();\n const abort = () => controller.abort();\n if (signal?.aborted) abort();\n signal?.addEventListener(\"abort\", abort, { once: true });\n const timer = setTimeout(abort, timeout);\n try {\n const response = await request(`/api/${action}`, {\n method: \"POST\",\n credentials: \"omit\",\n cache: \"no-store\",\n signal: controller.signal,\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams([[path, action === \"set\" ? JSON.stringify(body) : \"\"]]).toString(),\n });\n if (response.status !== 200 && !(action === \"get\" && response.status === 404)) throw new Error(`HTTP ${response.status}`);\n return response;\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", abort);\n }\n }\n /**\n * 获取独立快照,避免调用方修改内部缓存。\n * Return an independent snapshot so callers cannot mutate the cache.\n * @param {string} module 已打开模块 / Open module.\n * @returns {import(\"./client.mjs\").ModuleSnapshot} 会话快照 / Session snapshot.\n * @throws {Error} 模块未完成加载 / Module has not finished loading.\n */\n const snapshot = module => {\n const state = sessions.get(module);\n if (!state?.definition) throw new Error(\"Open the module first\");\n return structuredClone({ definition: state.definition, values: state.values });\n };\n /**\n * 串行修改单键,仅成功后更新仍存活的会话。\n * Serialize single-key mutations and update a still-active session only after success.\n * @param {string} module 已打开模块 / Open module.\n * @param {string} key 完整点分字段路径 / Complete dotted field path.\n * @param {\"set\" | \"delete\"} action 写入或删除 / Write or delete.\n * @param {unknown} value 写入值,删除时忽略 / Write value, ignored for deletion.\n * @param {\"write\" | \"delete\" | \"clearCaches\" | \"reset\"} [operation] 操作类型 / Operation kind.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n * @throws {Error} 会话、字段、值或请求错误 / Session, field, value or request error.\n */\n async function change(module, key, action, value, operation = action === \"set\" ? \"write\" : \"delete\") {\n const state = sessions.get(module);\n if (!state?.definition) throw new Error(\"Open the module first\");\n if (state.saving) throw new Error(\"A settings write is already in progress\");\n const field = state.definition.fields.find(field => field.key === key);\n state.saving = true;\n try {\n if ((operation === \"write\" || operation === \"delete\") && (!field || (action === \"set\" && !validValue(field, value)))) throw new TypeError(\"Invalid setting value\");\n await send(`@${state.definition.storageKey}.${key}`, action, value);\n if (sessions.get(module) === state) {\n switch (operation) {\n case \"write\":\n state.values[key] = structuredClone(value);\n break;\n case \"delete\":\n case \"clearCaches\":\n case \"reset\":\n for (const candidate of state.definition.fields) {\n if (candidate.key !== key && !candidate.key.startsWith(`${key}.`)) continue;\n delete state.values[candidate.key];\n if (Object.hasOwn(candidate, \"defaultValue\")) state.values[candidate.key] = structuredClone(candidate.defaultValue);\n }\n break;\n }\n }\n notify({ kind: \"success\", operation, module, key });\n } catch (error) {\n notify({ kind: \"error\", operation, module, key, message: error.message });\n throw error;\n } finally {\n state.saving = false;\n }\n }\n return {\n /**\n * 从已导入的 JSON 创建新会话,只读取一次设置值。\n * Create a session from imported JSON and read stored settings once.\n * @param {string} module 模块标识 / Module identifier.\n * @returns {Promise<import(\"./client.mjs\").ModuleSnapshot>} 新快照 / New snapshot.\n * @throws {Error} 读取失败、会话被替换或写入尚未完成 / Read failure, replaced session or unfinished write.\n */\n async open(module) {\n const binding = catalog.modules.get(module);\n if (!binding) throw new TypeError(`No BoxJS settings for module: ${module}`);\n const previous = sessions.get(module);\n if (previous?.saving) throw new Error(\"Cannot refresh while saving\");\n previous?.controller.abort();\n const state = { controller: new AbortController(), definition: null, values: {}, saving: false };\n sessions.set(module, state);\n try {\n const definition = normalizeBoxJs(catalog.select(module), module);\n const response = await send(`@${definition.storageKey}.${definition.settingsPath.join(\".\")}`, \"get\", undefined, state.controller.signal);\n let subtree = response.status === 404 ? {} : await response.json();\n if (typeof subtree === \"string\") subtree = JSON.parse(subtree);\n if (!subtree || typeof subtree !== \"object\" || Array.isArray(subtree)) throw new TypeError(\"Expected a settings subtree object\");\n if (sessions.get(module) !== state) throw new Error(\"Module session was replaced\");\n state.definition = definition;\n for (const field of definition.fields) {\n const stored = field.key\n .split(\".\")\n .slice(definition.settingsPath.length)\n .reduce((parent, part) => Object(parent)[part], subtree);\n const value = stored === undefined ? field.defaultValue : stored;\n if (value !== undefined) state.values[field.key] = normalizeStoredValue(field, value);\n }\n return snapshot(module);\n } catch (error) {\n if (sessions.get(module) === state) sessions.delete(module);\n throw error;\n }\n },\n snapshot,\n /**\n * 按需读取模块 Caches,不自动读取其它设置。\n * Read module Caches on demand without refreshing other settings.\n * @param {string} module 已打开的模块 / Open module.\n * @returns {Promise<unknown>} 缓存值,缺失为 undefined / Cache value, or undefined when absent.\n */\n async readCaches(module) {\n const state = sessions.get(module);\n if (!state?.definition) throw new Error(\"Open the module first\");\n const response = await send(`@${state.definition.storageKey}.${module}.Caches`, \"get\", undefined, state.controller.signal);\n return response.status === 404 ? undefined : response.json();\n },\n /**\n * 删除整个 Caches 节点,成功后不追加 GET。\n * Delete the entire Caches node without a follow-up GET.\n * @param {string} module 已打开模块 / Open module.\n * @returns {Promise<void>} 清理完成 / Cleanup completion.\n */\n clearCaches: module => change(module, `${module}.Caches`, \"delete\", undefined, \"clearCaches\"),\n /**\n * 删除整个模块持久化节点,以当前 BoxJS 默认值重置页面缓存。\n * Delete module persistence and reset the page cache using current BoxJS defaults.\n * @param {string} module 已打开模块 / Open module.\n * @returns {Promise<void>} 重置完成 / Reset completion.\n */\n reset: module => change(module, module, \"delete\", undefined, \"reset\"),\n /**\n * 取消读取并清除会话,不撤销已发送的写入。\n * Abort reads and clear the session without undoing dispatched writes.\n * @param {string} module 模块标识 / Module identifier.\n * @returns {void} 无返回值 / No return value.\n */\n leave(module) {\n sessions.get(module)?.controller.abort();\n sessions.delete(module);\n },\n /**\n * 写入单键并更新当前会话。\n * Write one key and update the current session.\n * @param {string} module 已打开模块 / Open module.\n * @param {string} key 点分字段路径 / Dotted field path.\n * @param {import(\"../index.js\").SettingsScalar | import(\"../index.js\").SettingsScalar[]} value 字段值 / Field value.\n * @returns {Promise<void>} 写入完成 / Write completion.\n */\n set: (module, key, value) => change(module, key, \"set\", value),\n /**\n * 删除单键覆盖值并显示默认值。\n * Delete one override and display its default value.\n * @param {string} module 已打开模块 / Open module.\n * @param {string} key 点分字段路径 / Dotted field path.\n * @returns {Promise<void>} 删除完成 / Delete completion.\n */\n remove: (module, key) => change(module, key, \"delete\"),\n };\n}\n\n/**\n * 同一文档内的主页/子页导航;iframe 各自的实例通过浏览器联合历史协作。\n * Navigate home/detail views within a document; iframe instances cooperate through joint browser history.\n */\nclass Navigation extends EventTarget {\n #container;\n #home;\n #create;\n #window;\n #key = null;\n #view;\n #retiring;\n #controller;\n #animation;\n #scroll = new WeakMap();\n #onHistory = () => this.#route();\n #onPageShow = event => {\n if (event.persisted) this.#route(true);\n };\n\n /**\n * 根视图始终保留;工厂按需提供子页,可用 signal 取消离开后的异步加载。\n * Retain the home view and create details on demand; signal cancels async work after departure.\n * @param {HTMLElement} container 由调用方布局的页面容器 / Caller-styled view container.\n * @param {HTMLElement} home 已创建的主页节点 / Existing home view.\n * @param {(key: string, signal: AbortSignal) => HTMLElement | undefined} create 子页工厂;未知路径返回 undefined / Detail factory; undefined for unknown routes.\n */\n constructor(container, home, create) {\n super();\n this.#container = container;\n this.#home = home;\n this.#create = create;\n this.#window = container.ownerDocument.defaultView;\n container.replaceChildren(home);\n this.#window.addEventListener(\"popstate\", this.#onHistory);\n this.#window.addEventListener(\"hashchange\", this.#onHistory);\n this.#window.addEventListener(\"pageshow\", this.#onPageShow);\n this.#route();\n }\n\n /**\n * 当前子页键;空字符串表示主页。\n * Current detail key; empty means home.\n */\n get current() {\n return this.#key;\n }\n\n /**\n * 是否可以返回上一级或先前文档。\n * Whether a parent view or previous document is available.\n */\n get canGoBack() {\n return Boolean(this.#key) || this.#window.history.length > 1;\n }\n\n /**\n * 加入子页历史;使用文档自身 URL,避免 srcdoc 按宿主 base URL 跳转。\n * Push a detail using the document URL, avoiding srcdoc navigation against the host base URL.\n * @param {string} key 子页键 / Detail key.\n * @returns {void} 无返回值 / No return value.\n */\n open(key) {\n if (key === this.#key) return;\n const url = new URL(this.#window.location.href);\n url.hash = encodeURIComponent(key);\n this.#window.history.pushState({ ...this.#window.history.state, preferencePanesRoute: key }, \"\", url.href);\n this.#route();\n }\n\n /**\n * 沿浏览器联合历史返回,根页可退回宿主或上个文档。\n * Go back through joint history, including a host or previous document from home.\n * @returns {void} 无返回值 / No return value.\n */\n back() {\n if (this.canGoBack) this.#window.history.back();\n }\n\n /**\n * 解析 URL 并统一处理页面切换、加载取消与动画结束后的释放。\n * Resolve the URL and coordinate transitions, cancellation and release after animation.\n * @param {boolean} [reload] 从页面缓存恢复时重新创建子页 / Recreate a detail after bfcache restoration.\n * @returns {void} 无返回值 / No return value.\n */\n #route(reload = false) {\n const url = new URL(this.#window.location.href);\n let key;\n try {\n key = decodeURIComponent(url.hash.slice(1));\n } catch (error) {\n if (!(error instanceof URIError)) throw error;\n key = \"\";\n }\n if (!reload && key === this.#key) return;\n this.#controller?.abort();\n this.#controller = new AbortController();\n const next = key ? this.#create(key, this.#controller.signal) : undefined;\n if (!next) key = \"\";\n const history = this.#window.history;\n // 直接打开子页时建立一次主页历史;刷新不重复堆叠。\n // Seed home history once for direct details, without stacking entries on reload.\n if (url.hash && history.state?.preferencePanesRoute !== key) {\n url.hash = \"\";\n history.replaceState({ ...history.state, preferencePanesRoute: \"\" }, \"\", url.href);\n if (key) {\n url.hash = encodeURIComponent(key);\n history.pushState({ ...history.state, preferencePanesRoute: key }, \"\", url.href);\n }\n }\n const previous = this.#view;\n const position = previous ? this.#window.getComputedStyle(previous).transform : \"none\";\n this.#animation?.cancel();\n this.#retiring?.remove();\n this.#retiring = previous;\n if (previous) {\n this.#scroll.set(previous, previous.scrollTop);\n previous.inert = true;\n }\n this.#key = key;\n this.#view = next;\n this.#home.inert = Boolean(next);\n if (next) {\n next.inert = false;\n this.#container.append(next);\n next.scrollTop = this.#scroll.get(next) ?? 0;\n }\n const moving = next ?? previous;\n if (moving) {\n const animation = moving.animate([{ transform: next ? \"translateX(100%)\" : position }, { transform: next ? \"translateX(0)\" : \"translateX(100%)\" }], { duration: this.#window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches ? 0 : 280, easing: \"cubic-bezier(.22,.61,.36,1)\", fill: \"forwards\" });\n this.#animation = animation;\n animation.onfinish = () => {\n if (this.#animation !== animation) return;\n this.#retiring?.remove();\n this.#retiring = undefined;\n animation.cancel();\n this.#animation = undefined;\n };\n }\n this.dispatchEvent(new Event(\"change\"));\n }\n\n /**\n * 释放监听器、加载、动画和节点;调用方可重新创建导航。\n * Release listeners, loads, animations and nodes so callers can recreate navigation.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n this.#window.removeEventListener(\"popstate\", this.#onHistory);\n this.#window.removeEventListener(\"hashchange\", this.#onHistory);\n this.#window.removeEventListener(\"pageshow\", this.#onPageShow);\n this.#controller?.abort();\n this.#animation?.cancel();\n this.#retiring?.remove();\n this.#view?.remove();\n this.#home.remove();\n }\n}\n\n/**\n * 挂载已导入 BoxJS 对应的模块表单和短暂通知。\n * Mount the imported BoxJS module form and transient notifications.\n * @param {HTMLElement} root 包内挂载元素 / Internal mount element.\n * @param {import(\"../BoxJS.mjs\").BoxJS} catalog 包内 BoxJS 目录 / Internal BoxJS catalog.\n * @returns {import(\"./index.js\").MountedPreferences} 面板生命周期句柄 / Panel lifecycle handle.\n */\nfunction mountPanel(root, catalog) {\n const title = catalog.module.metadata.name ?? catalog.module.module;\n const document = root.ownerDocument;\n const window = document.defaultView;\n const shell = element(\"div\", \"pp-panel\");\n shell.dataset.module = catalog.module.module;\n const header = element(\"header\", \"pp-header\");\n const back = element(\"button\", \"pp-back\", \"‹\");\n back.setAttribute(\"aria-label\", \"返回\");\n back.type = \"button\";\n const heading = element(\"h1\", \"pp-title\", title);\n const brand = element(\"div\", \"pp-brand\");\n const logo = element(\"span\", \"pp-brand-icon\");\n logo.setAttribute(\"aria-hidden\", \"true\");\n const image = icon(catalog.module.metadata, \"\");\n if (image) logo.append(image);\n brand.append(logo, heading);\n const viewport = element(\"div\", \"pp-viewport\");\n const toast = element(\"div\", \"pp-toast\");\n toast.setAttribute(\"role\", \"status\");\n toast.hidden = true;\n header.append(back, brand, element(\"span\", \"pp-nav-spacer\"));\n shell.append(header, viewport, toast);\n root.append(shell);\n // 嵌入模式向宿主发布导航状态,宿主不读取或修改模块内部 DOM。\n // Embedded mode publishes navigation state without host reads or mutations of the module DOM.\n const publishNavigation = () => {\n const frame = window.frameElement;\n if (!frame?.dataset.preferencePanes) return;\n frame.dispatchEvent(\n new frame.ownerDocument.defaultView.CustomEvent(\"preferencepanes:change\", {\n detail: { title: heading.textContent, module: catalog.module.module, busy: saving, canGoBack: !back.disabled },\n }),\n );\n };\n let timer,\n navigation,\n generation = 0,\n active = null,\n saving = false,\n destroyed = false;\n /**\n * 展示短暂通知,不刷新设置数据。\n * Display a transient notification without refreshing settings.\n * @param {{kind: \"success\" | \"error\", operation?: \"write\" | \"delete\" | \"clearCaches\" | \"reset\", message?: string}} event 操作结果 / Operation result.\n * @returns {void} 无返回值 / No return value.\n */\n const notify = event => {\n if (destroyed) return;\n switch (true) {\n case event.kind === \"error\":\n toast.textContent = `操作失败:${event.message}`;\n break;\n case event.operation === \"delete\":\n toast.textContent = \"删除成功\";\n break;\n case event.operation === \"clearCaches\":\n toast.textContent = \"Caches 已清空\";\n break;\n case event.operation === \"reset\":\n toast.textContent = \"模块已重置\";\n break;\n default:\n toast.textContent = \"修改成功\";\n break;\n }\n toast.dataset.kind = event.kind;\n toast.hidden = false;\n clearTimeout(timer);\n timer = setTimeout(() => {\n toast.hidden = true;\n }, 2400);\n };\n const client = createPreferencesClient({ catalog, notify });\n /**\n * 打开模块并忽略已过期的异步结果。\n * Open a module and ignore stale asynchronous results.\n * @param {string} module 模块标识 / Module identifier.\n * @returns {Promise<void>} 视图加载完成,失败显示错误视图 / View load completion; failures display an error view.\n */\n async function open(module) {\n const version = ++generation;\n active = module;\n back.disabled = window.history.length <= 1;\n heading.textContent = module;\n publishNavigation();\n viewport.replaceChildren(element(\"p\", \"pp-loading\", \"读取设置…\"));\n try {\n await client.open(module);\n if (version === generation) controls();\n } catch (error) {\n if (version !== generation) return;\n viewport.replaceChildren(errorView(error, () => open(module)));\n publishNavigation();\n }\n }\n /**\n * 从会话快照创建控件与操作按钮,不重新读取网络配置。\n * Build controls and actions from the session snapshot without fetching config again.\n * @returns {void} 无返回值 / No return value.\n */\n function controls() {\n const { definition, values } = client.snapshot(active);\n heading.textContent = definition.metadata?.name || active;\n const view = element(\"section\", \"pp-fields\");\n /**\n * 挂载后执行的多行高度更新\n * Textarea sizing callbacks run after mounting.\n * @type {Array<() => void>}\n */\n const growingInputs = [];\n const editors = new Map();\n const summaries = [];\n const groups = new Map();\n let queue = Promise.resolve(),\n pendingWrites = 0;\n /**\n * 导航组件处理页面切换,表单只更新当前标题与返回按钮。\n * Let navigation own transitions; the form only updates the title and back button.\n * @returns {void} 无返回值 / No return value.\n */\n const updateNavigation = () => {\n const editor = editors.get(navigation.current);\n heading.textContent = editor?.title ?? definition.metadata?.name ?? active;\n back.disabled = saving || !navigation.canGoBack;\n publishNavigation();\n };\n /**\n * 串行执行模块操作,保持输入可编辑。\n * Serialize module actions while keeping inputs editable.\n * @param {() => Promise<void>} action 请求或写入 / Request or mutation.\n * @param {() => void} success 成功后的局部更新 / Local update after success.\n * @param {() => void} [failure] 失败后恢复当前输入 / Restore the current input on failure.\n * @returns {Promise<void>} 操作完成 / Operation completion.\n */\n function perform(action, success, failure = () => {}) {\n pendingWrites++;\n saving = true;\n back.disabled = true;\n publishNavigation();\n return (queue = queue\n .then(action)\n .then(() => {\n if (!destroyed) success();\n })\n .catch(() => {\n /* 请求层已通知错误。\n * The request layer has already reported the error. */\n if (!destroyed) failure();\n })\n .finally(() => {\n pendingWrites--;\n saving = pendingWrites > 0;\n if (destroyed && !saving) client.leave(active);\n back.disabled = saving || !navigation.canGoBack;\n publishNavigation();\n }));\n }\n const metadata = definition.metadata;\n if (metadata) {\n const info = element(\"div\", \"pp-module-info\");\n const image = icon(metadata, \"pp-module-icon\");\n if (image) info.append(image);\n const details = element(\"div\", \"pp-module-details\");\n for (const description of [metadata.author, metadata.desc ?? metadata.description, ...(metadata.descs ?? [])]) if (description) details.append(element(\"p\", \"pp-description\", description));\n if (metadata.repo) {\n const link = element(\"a\", \"pp-module-source\", \"项目主页\");\n link.href = resourceURL(metadata.repo);\n link.target = \"_blank\";\n link.rel = \"noopener noreferrer\";\n details.append(link);\n }\n info.append(details);\n view.append(info);\n }\n for (const field of definition.fields) {\n const match = /^\\[([^\\]]+)\\]\\s*(.*)$/.exec(field.name);\n const group = match?.[1] ?? \"通用\";\n if (!groups.has(group)) {\n const section = element(\"section\", \"form-group\");\n const rows = element(\"div\", \"form-group__row\");\n section.append(element(\"h2\", \"form-group__title\", group), rows);\n groups.set(group, rows);\n view.append(section);\n }\n const row = element(\"div\", \"form-row pp-field\");\n const label = element(\"div\", \"form-row__text\");\n label.append(element(\"span\", \"form-row__title\", match?.[2] ?? field.name));\n if (field.description) label.append(element(\"span\", \"form-row__subtitle\", field.description));\n row.append(label);\n const value = values[field.key];\n /**\n * 读取尚未保存的输入\n * Read the unsaved input.\n * @type {() => unknown}\n */\n let read;\n /**\n * 更新当前控件\n * Update the current control.\n * @type {(value: unknown) => void}\n */\n let write;\n let inputContainer = row;\n let eventName = \"change\";\n switch (true) {\n case Boolean(field.options) && field.type !== \"array\": {\n const select = element(\"select\", \"pp-input\");\n select.setAttribute(\"aria-label\", field.name);\n field.options.forEach((option, index) => {\n const item = element(\"option\", \"\", option.label);\n item.value = String(index);\n select.append(item);\n });\n write = value => {\n select.selectedIndex = field.options.findIndex(option => option.key === value);\n };\n row.append(select);\n read = () => field.options[select.selectedIndex]?.key;\n break;\n }\n case field.type === \"array\" && Boolean(field.options): {\n const page = element(\"section\", \"pp-choice-page\");\n if (field.description) page.append(element(\"p\", \"pp-description\", field.description));\n const choices = element(\"div\", \"form-group__row\");\n page.append(choices);\n inputContainer = choices;\n editors.set(field.key, { node: page, title: match?.[2] ?? field.name });\n const summary = element(\"span\", \"form-row__value pp-summary\");\n const link = element(\"button\", \"pp-choice-link\");\n link.type = \"button\";\n link.setAttribute(\"aria-label\", field.name);\n link.append(summary, element(\"span\", \"pp-chevron\", \"›\"));\n row.append(link);\n const refresh = () => {\n const value = client.snapshot(active).values[field.key];\n summary.textContent =\n field.options\n .filter(option => Array.isArray(value) && value.includes(option.key))\n .map(option => option.label)\n .join(\"、\") || \"未选择\";\n };\n summaries.push(refresh);\n refresh();\n link.onclick = () => navigation.open(field.key);\n row.addEventListener(\"click\", event => {\n if (!link.contains(event.target)) link.click();\n });\n const inputs = field.options.map(option => {\n const label = element(\"label\", \"form-row pp-choice\", option.label);\n const input = element(\"input\", \"\");\n input.type = \"checkbox\";\n input.setAttribute(\"aria-label\", option.label);\n label.append(input);\n choices.append(label);\n return { input, key: option.key };\n });\n read = () => inputs.filter(option => option.input.checked).map(option => option.key);\n write = value => {\n for (const option of inputs) option.input.checked = Array.isArray(value) && value.includes(option.key);\n };\n break;\n }\n default: {\n const multiline = field.control === \"textarea\" || field.type === \"array\";\n const input = element(multiline ? \"textarea\" : \"input\", \"pp-input\");\n if (multiline) row.classList.add(\"pp-multiline\");\n input.setAttribute(\"aria-label\", field.name);\n if (field.placeholder) input.placeholder = field.placeholder;\n if (multiline && field.rows) input.rows = field.rows;\n /**\n * 在挂载后根据内容调整高度,同时保留基础行数。\n * Size mounted textareas to their contents while retaining baseline rows.\n * @returns {void} 无返回值 / No return value.\n */\n const grow = () => {\n if (!multiline || !field.autoGrow || !input.isConnected) return;\n input.style.height = \"auto\";\n const baseline = input.getBoundingClientRect().height;\n const style = window.getComputedStyle(input);\n const borders = Number.parseFloat(style.borderTopWidth) + Number.parseFloat(style.borderBottomWidth);\n input.style.height = `${Math.max(baseline, input.scrollHeight + borders)}px`;\n };\n if (multiline && field.autoGrow) {\n input.addEventListener(\"input\", grow);\n growingInputs.push(grow);\n }\n if (field.type === \"boolean\") {\n input.type = \"checkbox\";\n input.classList.add(\"pp-switch\");\n input.setAttribute(\"role\", \"switch\");\n write = value => {\n input.checked = value === true;\n };\n read = () => input.checked;\n } else {\n eventName = \"input\";\n if (!multiline) input.type = field.type === \"number\" ? \"number\" : \"text\";\n write = value => {\n input.value = field.type === \"array\" ? JSON.stringify(value ?? []) : (value ?? \"\");\n grow();\n };\n read = () => {\n switch (field.type) {\n case \"array\":\n return JSON.parse(input.value);\n case \"number\":\n return input.value === \"\" ? Number.NaN : Number(input.value);\n default:\n return input.value;\n }\n };\n }\n row.append(input);\n break;\n }\n }\n write(value);\n let inputVersion = 0;\n inputContainer.addEventListener(eventName, event => {\n if (event.isComposing) return;\n const version = ++inputVersion,\n module = active;\n let value;\n try {\n value = read();\n } catch (error) {\n notify({ kind: \"error\", message: error.message });\n return;\n }\n const restore = () => {\n if (version === inputVersion) write(client.snapshot(module).values[field.key]);\n };\n perform(\n () => client.set(module, field.key, value),\n () => {\n for (const refresh of summaries) refresh();\n },\n restore,\n );\n });\n if (eventName === \"input\") inputContainer.addEventListener(\"compositionend\", event => event.target.dispatchEvent(new window.Event(\"input\", { bubbles: true })));\n groups.get(group).append(row);\n }\n const maintenance = element(\"section\", \"pp-maintenance\");\n maintenance.append(element(\"h2\", \"pp-title\", \"模块数据\"));\n const actions = element(\"div\", \"pp-actions\");\n const cacheView = element(\"button\", \"\", \"查看 Caches\");\n const cacheClear = element(\"button\", \"\", \"清空 Caches\");\n const reset = element(\"button\", \"pp-danger\", \"重置模块\");\n const output = element(\"pre\", \"pp-cache\");\n output.hidden = true;\n output.setAttribute(\"aria-label\", \"Caches 内容\");\n for (const button of [cacheView, cacheClear, reset]) button.type = \"button\";\n cacheView.onclick = () => {\n if (saving) return;\n let value;\n return perform(\n async () => {\n try {\n value = await client.readCaches(active);\n } catch (error) {\n notify({ kind: \"error\", message: error.message });\n throw error;\n }\n },\n () => {\n output.textContent = value === undefined ? \"暂无缓存\" : JSON.stringify(value, null, 2);\n output.hidden = false;\n cacheView.textContent = \"刷新 Caches\";\n },\n );\n };\n cacheClear.onclick = () => {\n if (saving) return;\n if (!window.confirm(`清空 ${active} 的全部 Caches?`)) return;\n return perform(\n () => client.clearCaches(active),\n () => {\n output.textContent = \"暂无缓存\";\n },\n );\n };\n reset.onclick = () => {\n if (saving) return;\n if (!window.confirm(`重置 ${active}?这将删除该模块的 Settings、Caches 和其它持久化数据。`)) return;\n return perform(() => client.reset(active), controls);\n };\n actions.append(cacheView, cacheClear, reset);\n maintenance.append(actions, output);\n view.append(maintenance);\n navigation?.destroy();\n navigation = new Navigation(viewport, view, key => editors.get(key)?.node);\n navigation.addEventListener(\"change\", updateNavigation);\n for (const grow of growingInputs) grow();\n updateNavigation();\n }\n /**\n * 已加载的表单交由导航组件返回;加载阶段可以返回先前文档。\n * Loaded forms delegate back to navigation; loading views can return to the previous document.\n * @returns {void} 无返回值 / No return value.\n */\n back.onclick = () => {\n if (saving) return;\n if (navigation) navigation.back();\n else window.history.back();\n };\n open(catalog.module.module);\n return {\n /**\n * 移除监听器、定时器、会话和挂载内容。\n * Remove listeners, timers, session and mounted content.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n destroyed = true;\n navigation?.destroy();\n generation++;\n if (active && !saving) client.leave(active);\n clearTimeout(timer);\n shell.remove();\n },\n };\n}\n\n/**\n * 只挂载导入 JSON 对应的模块设置页,默认样式内置,CSS 仅用于该页。\n * Mount only the imported module's settings page with built-in defaults and optional page CSS.\n * @param {import(\"../index.js\").BoxJSInput} boxjs 单个模块的 BoxJS JSON / BoxJS JSON for one module.\n * @param {string} [css] 可选 CSS 正文 / Optional CSS text.\n * @returns {import(\"./index.js\").MountedPreferences} 模块生命周期句柄 / Module lifecycle handle.\n */\nfunction mount(boxjs, css = \"\") {\n if (typeof css !== \"string\") throw new TypeError(\"CSS must be a string\");\n const catalog = new BoxJS(boxjs);\n const metadata = catalog.module.metadata;\n const image = metadata.icon || metadata.icons?.[1] || metadata.icons?.[0];\n if (image) resourceURL(image);\n if (metadata.repo) resourceURL(metadata.repo);\n const existing = document.querySelector(\"#preferences\");\n const root = existing ?? element(\"main\", \"\");\n if (!existing) {\n root.id = \"preferences\";\n document.body.append(root);\n }\n const base = element(\"style\", \"\"),\n custom = element(\"style\", \"\");\n base.textContent = defaults;\n custom.textContent = css;\n document.head.append(base, custom);\n const previousTitle = document.title;\n const previousTheme = document.documentElement.dataset.theme;\n const theme = navigator.userAgent.match(/themeId\\/(\\d+)/)?.[1];\n if (theme) document.documentElement.dataset.theme = theme === \"2\" ? \"dark\" : \"light\";\n document.title = metadata.name ?? catalog.module.module;\n let panel;\n const view = {\n /**\n * 释放模块视图、样式与会话,不操作项目入口页。\n * Release the module view, styles and session without operating a project landing page.\n * @returns {void} 无返回值 / No return value.\n */\n destroy() {\n panel?.destroy();\n base.remove();\n custom.remove();\n if (existing) root.replaceChildren();\n else root.remove();\n document.title = previousTitle;\n if (previousTheme === undefined) delete document.documentElement.dataset.theme;\n else document.documentElement.dataset.theme = previousTheme;\n },\n };\n try {\n root.replaceChildren();\n panel = mountPanel(root, catalog);\n return view;\n } catch (error) {\n view.destroy();\n throw error;\n }\n}\n\nlet view;\n/**\n * 从 URL 或代理传递的 Header 导入 JSON/CSS,支持独立文档与 srcdoc。\n * Import JSON/CSS from the URL or proxy-carried headers in standalone and srcdoc documents.\n * @returns {Promise<void>} 启动完成 / Startup completion.\n */\nasync function start() {\n try {\n view?.destroy();\n view = undefined;\n const context = document.querySelector('meta[name=\"preference-panes-inputs\"]');\n const embedded = window.frameElement?.dataset.preferencePanes;\n let inputs;\n switch (true) {\n case embedded !== undefined:\n inputs = JSON.parse(embedded);\n document.documentElement.dataset.preferencePanesEmbedded = \"\";\n break;\n case context !== null:\n inputs = JSON.parse(decodeURIComponent(context.content));\n break;\n default:\n inputs = pageInputs(new URL(location.href));\n }\n const resources = [inputs.json, inputs.css].map(source => {\n if (!source) return null;\n const url = new URL(source, inputs.url);\n if (![\"http:\", \"https:\"].includes(url.protocol)) throw new TypeError(\"Resources must use HTTP(S) URLs\");\n return url.href;\n });\n const [data, style] = await Promise.all(resources.map(url => (url ? fetch(url, { cache: \"no-store\", credentials: \"omit\" }) : null)));\n if (data.status !== 200 || (style && style.status !== 200)) throw new Error(`HTTP ${data.status !== 200 ? data.status : style.status}`);\n const boxjs = await data.json();\n if (new BoxJS(boxjs).module.module !== inputs.module) throw new Error(\"Imported JSON does not match the module URL\");\n view = mount(boxjs, style ? await style.text() : \"\");\n } catch (error) {\n document.querySelector(\"#preferences\").replaceChildren(errorView(error, start));\n }\n}\nstart();\nwindow.addEventListener(\"pageshow\", event => {\n if (event.persisted) start();\n});\n"}};
345
+
346
+ /**
347
+ * 统一解析模块页的资源地址:Header 优先于查询参数,再使用模块约定。
348
+ * Resolve module resource locations: headers override query parameters and module conventions.
349
+ * @param {URL} url 已解析的页面请求地址 / Parsed page request URL.
350
+ * @param {Record<string, string | undefined>} [headers] 请求头,名称不区分大小写 / Case-insensitive request headers.
351
+ * @returns {{url: string, module: string, json: string, css: string}} 页面上下文与两个资源输入 / Page context and two resource inputs.
352
+ */
353
+ function pageInputs(url, headers = {}) {
354
+ const match = /^\/settings\/([a-zA-Z0-9_-]+)\/?$/.exec(url.pathname);
355
+ if (!match) throw new TypeError("Open a concrete module URL");
356
+ const module = match[1];
357
+ const values = Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));
358
+ const json = values["x-preferencepanes-json"] ?? url.searchParams.get("json") ?? `/configs/${module}`;
359
+ const css = values["x-preferencepanes-css"] ?? url.searchParams.get("css") ?? "";
360
+ if (!json.trim()) throw new TypeError("JSON resource URL is required");
361
+ return { url: url.href, module, json, css };
362
+ }
363
+
364
+ /**
365
+ * 统一生成不可缓存的响应,HEAD 始终省略正文。
366
+ * Create an uncached response, always omitting the body for HEAD.
367
+ * @param {import("../index.js").SettingsRequest} request 宿主请求 / Host request.
368
+ * @param {number} status HTTP 状态 / HTTP status.
369
+ * @param {unknown} body JSON 数据或资源正文 / JSON data or resource body.
370
+ * @param {string} [type] 媒体类型 / Media type.
371
+ * @returns {import("../index.js").SettingsResponse} 通用响应 / Common response.
372
+ */
373
+ function response(request, status, body, type = "application/json") {
374
+ return {
375
+ status,
376
+ headers: { "Content-Type": `${type}; charset=utf-8`, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" },
377
+ body: request.method === "HEAD" ? "" : type === "application/json" ? JSON.stringify(body) : body,
378
+ };
379
+ }
380
+
381
+ /* https://www.lodashjs.com */
382
+ /**
383
+ * 轻量 Lodash 工具集。
384
+ * Lightweight Lodash-like utilities.
385
+ *
386
+ * 说明:
387
+ * Notes:
388
+ * - 这是 Lodash 的“部分方法”简化实现,不等价于完整 Lodash
389
+ * - This is a simplified subset, not a full Lodash implementation
390
+ * - 各方法语义可参考 Lodash 官方文档
391
+ * - Method semantics can be referenced from official Lodash docs
392
+ * - 导入时建议使用 `Lodash as _`,遵循 lodash 官方示例惯例
393
+ * - Use `Lodash as _` when importing, following official lodash example convention
394
+ *
395
+ * 参考:
396
+ * Reference:
397
+ * - https://www.lodashjs.com
398
+ * - https://lodash.com
399
+ */
400
+ class Lodash {
401
+ /**
402
+ * HTML 特殊字符转义。
403
+ * Escape HTML special characters.
404
+ *
405
+ * @param {string} string 输入文本 / Input text.
406
+ * @returns {string}
407
+ * @see {@link https://lodash.com/docs/#escape lodash.escape}
408
+ * @see {@link https://www.lodashjs.com/docs/lodash.escape lodash.escape (中文)}
409
+ */
410
+ static escape(string) {
411
+ const map = {
412
+ "&": "&amp;",
413
+ "<": "&lt;",
414
+ ">": "&gt;",
415
+ '"': "&quot;",
416
+ "'": "&#39;",
417
+ };
418
+ return string.replace(/[&<>"']/g, m => map[m]);
419
+ }
420
+
421
+ /**
422
+ * 按路径读取对象值。
423
+ * Get object value by path.
424
+ *
425
+ * @param {object} [object={}] 目标对象 / Target object.
426
+ * @param {string|string[]} [path=""] 路径 / Path.
427
+ * @param {*} [defaultValue=undefined] 默认值 / Default value.
428
+ * @returns {*}
429
+ * @see {@link https://lodash.com/docs/#get lodash.get}
430
+ * @see {@link https://www.lodashjs.com/docs/lodash.get lodash.get (中文)}
431
+ */
432
+ static get(object = {}, path = "", defaultValue = undefined) {
433
+ // translate array case to dot case, then split with .
434
+ // a[0].b -> a.0.b -> ['a', '0', 'b']
435
+ if (!Array.isArray(path)) path = Lodash.toPath(path);
436
+
437
+ const result = path.reduce((previousValue, currentValue) => {
438
+ return Object(previousValue)[currentValue]; // null undefined get attribute will throwError, Object() can return a object
439
+ }, object);
440
+ return result === undefined ? defaultValue : result;
441
+ }
442
+
443
+ /**
444
+ * 递归合并源对象的自身可枚举属性到目标对象
445
+ * Recursively merge source enumerable properties into target object.
446
+ * @description 简化版 lodash.merge,用于合并配置对象
447
+ * @description A simplified lodash.merge for config merging.
448
+ *
449
+ * 适用情况:
450
+ * - 合并嵌套的配置/设置对象
451
+ * - 需要深度合并而非浅层覆盖的场景
452
+ * - 多个源对象依次合并到目标对象
453
+ *
454
+ * 限制:
455
+ * - 仅处理普通对象 (Plain Object),不处理 Date/RegExp 等特殊对象
456
+ * - Map/Set 仅支持同类型合并,不递归内部值
457
+ * - 数组会被直接覆盖,不会合并数组元素
458
+ * - 不处理循环引用,可能导致栈溢出
459
+ * - 不复制 Symbol 属性和不可枚举属性
460
+ * - 不保留原型链,仅处理自身属性
461
+ * - 会修改原始目标对象 (mutates target)
462
+ *
463
+ * @param {object} object - 目标对象
464
+ * @param {object} object - Target object.
465
+ * @param {...object} sources - 源对象(可多个)
466
+ * @param {...object} sources - Source objects.
467
+ * @returns {object} 返回合并后的目标对象
468
+ * @returns {object} Merged target object.
469
+ * @see {@link https://lodash.com/docs/#merge lodash.merge}
470
+ * @see {@link https://www.lodashjs.com/docs/lodash.merge lodash.merge (中文)}
471
+ * @example
472
+ * const target = { a: { b: 1 }, c: 2 };
473
+ * const source = { a: { d: 3 }, e: 4 };
474
+ * Lodash.merge(target, source);
475
+ * // => { a: { b: 1, d: 3 }, c: 2, e: 4 }
476
+ */
477
+ static merge(object, ...sources) {
478
+ if (object === null || object === undefined) return object;
479
+
480
+ for (const source of sources) {
481
+ if (source === null || source === undefined) continue;
482
+
483
+ for (const key of Object.keys(source)) {
484
+ const sourceValue = source[key];
485
+ const targetValue = object[key];
486
+
487
+ switch (true) {
488
+ case Lodash.#isPlainObject(sourceValue) && Lodash.#isPlainObject(targetValue):
489
+ // 递归合并对象
490
+ object[key] = Lodash.merge(targetValue, sourceValue);
491
+ break;
492
+ case sourceValue instanceof Map && targetValue instanceof Map:
493
+ // 合并 Map(空 Map 跳过)
494
+ if (sourceValue.size > 0) {
495
+ for (const [k, v] of sourceValue) {
496
+ targetValue.set(k, v);
497
+ }
498
+ }
499
+ break;
500
+ case sourceValue instanceof Set && targetValue instanceof Set:
501
+ // 合并 Set(空 Set 跳过)
502
+ if (sourceValue.size > 0) {
503
+ for (const v of sourceValue) {
504
+ targetValue.add(v);
505
+ }
506
+ }
507
+ break;
508
+ case Array.isArray(sourceValue) && sourceValue.length === 0 && targetValue !== undefined:
509
+ // 空数组不覆盖已有值
510
+ break;
511
+ case (sourceValue instanceof Map && sourceValue.size === 0 && targetValue !== undefined):
512
+ case (sourceValue instanceof Set && sourceValue.size === 0 && targetValue !== undefined):
513
+ // 空 Map/Set 不覆盖已有值
514
+ break;
515
+ case sourceValue !== undefined:
516
+ object[key] = sourceValue;
517
+ break;
518
+ }
519
+ }
520
+ }
521
+
522
+ return object;
523
+ }
524
+
525
+ /**
526
+ * 判断值是否为普通对象 (Plain Object)
527
+ * Check whether a value is a plain object.
528
+ * @param {*} value - 要检查的值
529
+ * @param {*} value - Value to check.
530
+ * @returns {boolean} 如果是普通对象返回 true
531
+ * @returns {boolean} Returns true when value is a plain object.
532
+ * @see {@link https://lodash.com/docs/#isPlainObject lodash.isPlainObject}
533
+ * @see {@link https://www.lodashjs.com/docs/lodash.isPlainObject lodash.isPlainObject (中文)}
534
+ */
535
+ static #isPlainObject(value) {
536
+ if (value === null || typeof value !== "object") return false;
537
+ const proto = Object.getPrototypeOf(value);
538
+ return proto === null || proto === Object.prototype;
539
+ }
540
+
541
+ /**
542
+ * 删除对象指定路径并返回对象。
543
+ * Omit paths from object and return the same object.
544
+ *
545
+ * @param {object} [object={}] 目标对象 / Target object.
546
+ * @param {string|string[]} [paths=[]] 要删除的路径 / Paths to remove.
547
+ * @returns {object}
548
+ * @see {@link https://lodash.com/docs/#omit lodash.omit}
549
+ * @see {@link https://www.lodashjs.com/docs/lodash.omit lodash.omit (中文)}
550
+ */
551
+ static omit(object = {}, paths = []) {
552
+ if (!Array.isArray(paths)) paths = [paths.toString()];
553
+ paths.forEach(path => Lodash.unset(object, path));
554
+ return object;
555
+ }
556
+
557
+ /**
558
+ * 仅保留对象指定键(第一层)。
559
+ * Pick selected keys from object (top level only).
560
+ *
561
+ * @param {object} [object={}] 目标对象 / Target object.
562
+ * @param {string|string[]} [paths=[]] 需要保留的键 / Keys to keep.
563
+ * @returns {object}
564
+ * @see {@link https://lodash.com/docs/#pick lodash.pick}
565
+ * @see {@link https://www.lodashjs.com/docs/lodash.pick lodash.pick (中文)}
566
+ */
567
+ static pick(object = {}, paths = []) {
568
+ if (!Array.isArray(paths)) paths = [paths.toString()];
569
+ const filteredEntries = Object.entries(object).filter(([key, value]) => paths.includes(key));
570
+ return Object.fromEntries(filteredEntries);
571
+ }
572
+
573
+ /**
574
+ * 按路径写入对象值。
575
+ * Set object value by path.
576
+ *
577
+ * @param {object} object 目标对象 / Target object.
578
+ * @param {string|string[]} path 路径 / Path.
579
+ * @param {*} value 写入值 / Value.
580
+ * @returns {object}
581
+ * @see {@link https://lodash.com/docs/#set lodash.set}
582
+ * @see {@link https://www.lodashjs.com/docs/lodash.set lodash.set (中文)}
583
+ */
584
+ static set(object, path, value) {
585
+ if (!Array.isArray(path)) path = Lodash.toPath(path);
586
+ path.slice(0, -1).reduce((previousValue, currentValue, currentIndex) => (Object(previousValue[currentValue]) === previousValue[currentValue] ? previousValue[currentValue] : (previousValue[currentValue] = /^\d+$/.test(path[currentIndex + 1]) ? [] : {})), object)[path[path.length - 1]] = value;
587
+ return object;
588
+ }
589
+
590
+ /**
591
+ * 将点路径或数组下标路径转换为数组。
592
+ * Convert dot/array-index path string into path segments.
593
+ *
594
+ * @param {string} value 路径字符串 / Path string.
595
+ * @returns {string[]}
596
+ * @see {@link https://lodash.com/docs/#toPath lodash.toPath}
597
+ * @see {@link https://www.lodashjs.com/docs/lodash.toPath lodash.toPath (中文)}
598
+ */
599
+ static toPath(value) {
600
+ return value
601
+ .replace(/\[(\d+)\]/g, ".$1")
602
+ .split(".")
603
+ .filter(Boolean);
604
+ }
605
+
606
+ /**
607
+ * HTML 实体反转义。
608
+ * Unescape HTML entities.
609
+ *
610
+ * @param {string} string 输入文本 / Input text.
611
+ * @returns {string}
612
+ * @see {@link https://lodash.com/docs/#unescape lodash.unescape}
613
+ * @see {@link https://www.lodashjs.com/docs/lodash.unescape lodash.unescape (中文)}
614
+ */
615
+ static unescape(string) {
616
+ const map = {
617
+ "&amp;": "&",
618
+ "&lt;": "<",
619
+ "&gt;": ">",
620
+ "&quot;": '"',
621
+ "&#39;": "'",
622
+ };
623
+ return string.replace(/&amp;|&lt;|&gt;|&quot;|&#39;/g, m => map[m]);
624
+ }
625
+
626
+ /**
627
+ * 删除对象路径对应的值。
628
+ * Remove value by object path.
629
+ *
630
+ * @param {object} [object={}] 目标对象 / Target object.
631
+ * @param {string|string[]} [path=""] 路径 / Path.
632
+ * @returns {boolean}
633
+ * @see {@link https://lodash.com/docs/#unset lodash.unset}
634
+ * @see {@link https://www.lodashjs.com/docs/lodash.unset lodash.unset (中文)}
635
+ */
636
+ static unset(object = {}, path = "") {
637
+ if (!Array.isArray(path)) path = Lodash.toPath(path);
638
+ const result = path.reduce((previousValue, currentValue, currentIndex) => {
639
+ if (currentIndex === path.length - 1) {
640
+ delete previousValue[currentValue];
641
+ return true;
642
+ }
643
+ return Object(previousValue)[currentValue];
644
+ }, object);
645
+ return result;
646
+ }
647
+ }
648
+
649
+ /**
650
+ * 当前运行平台名称(脚本平台优先,模块系统次之)。
651
+ * Current runtime platform name (script platform first, module system second).
652
+ *
653
+ * 识别顺序:
654
+ * Detection order:
655
+ * 1) `$task` -> Quantumult X
656
+ * 2) `$loon` -> Loon
657
+ * 3) `$rocket` -> Shadowrocket
658
+ * 4) `Egern` -> Egern
659
+ * 5) `$environment["surge-version"]` -> Surge
660
+ * 6) `$environment["stash-version"]` -> Stash
661
+ * 7) `Cloudflare` -> Worker
662
+ * 8) `process.versions.node` -> Node.js
663
+ * 9) 默认回落 -> undefined
664
+ * default fallback -> undefined
665
+ *
666
+ * 说明:
667
+ * Notes:
668
+ * - 使用 `'key' in globalThis`,避免 `Object.keys` 对不可枚举全局变量漏检。
669
+ * - Use `'key' in globalThis` to avoid missing non-enumerable globals with `Object.keys`.
670
+ *
671
+ * @type {("Quantumult X" | "Loon" | "Shadowrocket" | "Egern" | "Surge" | "Stash" | "Worker" | "Node.js" | undefined)}
672
+ */
673
+ const $app = (() => {
674
+ const has = key => key in globalThis;
675
+ switch (true) {
676
+ case has("$task"):
677
+ return "Quantumult X";
678
+ case has("$loon"):
679
+ return "Loon";
680
+ case has("$rocket"):
681
+ return "Shadowrocket";
682
+ case has("Egern"):
683
+ return "Egern";
684
+ case Boolean(globalThis.$environment?.["surge-version"]):
685
+ return "Surge";
686
+ case Boolean(globalThis.$environment?.["stash-version"]):
687
+ return "Stash";
688
+ case has("Cloudflare"):
689
+ //case has("ServiceWorkerGlobalScope") && has("self") && has("caches") && has("scheduler"):
690
+ return "Worker";
691
+ case Boolean(globalThis.process?.versions?.node):
692
+ return "Node.js";
693
+ default:
694
+ return undefined;
695
+ }
696
+ })();
697
+
698
+ /**
699
+ * 跨平台持久化存储适配器。
700
+ * Cross-platform persistent storage adapter.
701
+ *
702
+ * 设计目标:
703
+ * Design goal:
704
+ * - 仿照 Web Storage (`Storage`) 接口设计
705
+ * - Modeled after Web Storage (`Storage`) interface
706
+ * - 统一 VPN App 脚本环境中的持久化读写接口
707
+ * - Unify persistence APIs across VPN app script environments
708
+ *
709
+ * 支持后端:
710
+ * Supported backends:
711
+ * - Surge/Loon/Stash/Egern/Shadowrocket: `$persistentStore`
712
+ * - Quantumult X: `$prefs`
713
+ * - Worker: 内存缓存(非持久化)
714
+ * - Worker: in-memory cache (non-persistent)
715
+ * - Node.js: 由 Node.js ESM 入口注入持久化后端
716
+ * - Node.js: persistent backend injected by the Node.js ESM entry
717
+ *
718
+ * 支持路径键:
719
+ * Supports path key:
720
+ * - `@root.path.to.value`
721
+ *
722
+ * 与 Web Storage 的已知差异:
723
+ * Known differences from Web Storage:
724
+ * - 支持 `@key.path` 深路径读写(Web Storage 原生不支持)
725
+ * - Supports `@key.path` deep-path access (not native in Web Storage)
726
+ * - `removeItem/clear` 并非所有平台都可用
727
+ * - `removeItem/clear` are not available on every platform
728
+ * - 读取时会尝试 `JSON.parse`,写入对象会 `JSON.stringify`
729
+ * - Reads try `JSON.parse`, writes stringify objects
730
+ *
731
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/Storage
732
+ * @link https://developer.mozilla.org/zh-CN/docs/Web/API/Storage
733
+ */
734
+ class Storage {
735
+ /**
736
+ * Worker / Node.js 环境下的内存数据缓存。
737
+ * In-memory data cache for Worker / Node.js runtime.
738
+ *
739
+ * @type {Record<string, any>|null}
740
+ */
741
+ static data = null;
742
+
743
+ /**
744
+ * Node.js 持久化文件名。
745
+ * Data file name used in Node.js.
746
+ *
747
+ * @type {string}
748
+ */
749
+ static dataFile = "box.dat";
750
+
751
+ /**
752
+ * Node.js ESM 入口注入的存储后端。
753
+ * Storage backend injected by the Node.js ESM entry.
754
+ *
755
+ * @type {{load: (dataFile: string) => Record<string, any>, write: (dataFile: string, data: Record<string, any>) => void}|null}
756
+ */
757
+ static nodeBackend = null;
758
+
759
+ /**
760
+ * `@key.path` 解析正则。
761
+ * Regex for `@key.path` parsing.
762
+ *
763
+ * @type {RegExp}
764
+ */
765
+ static #nameRegex = /^@(?<key>[^.]+)(?:\.(?<path>.*))?$/;
766
+
767
+ /**
768
+ * 读取存储值。
769
+ * Read value from persistent storage.
770
+ *
771
+ * @param {string} keyName 键名或路径键 / Key or path key.
772
+ * @param {*} [defaultValue=null] 默认值 / Default value when key is missing.
773
+ * @returns {*}
774
+ */
775
+ static getItem(keyName, defaultValue = null) {
776
+ let keyValue = defaultValue;
777
+ // 如果以 @
778
+ switch (keyName.startsWith("@")) {
779
+ case true: {
780
+ const { key, path } = keyName.match(Storage.#nameRegex)?.groups;
781
+ keyName = key;
782
+ let value = Storage.getItem(keyName, {});
783
+ if (typeof value !== "object") value = {};
784
+ keyValue = Lodash.get(value, path);
785
+ try {
786
+ keyValue = JSON.parse(keyValue);
787
+ } catch {}
788
+ break;
789
+ }
790
+ default:
791
+ switch ($app) {
792
+ case "Surge":
793
+ case "Loon":
794
+ case "Stash":
795
+ case "Egern":
796
+ case "Shadowrocket":
797
+ keyValue = $persistentStore.read(keyName);
798
+ break;
799
+ case "Quantumult X":
800
+ keyValue = $prefs.valueForKey(keyName);
801
+ break;
802
+ case "Worker":
803
+ Storage.data = Storage.data ?? {};
804
+ keyValue = Storage.data[keyName];
805
+ break;
806
+ case "Node.js":
807
+ Storage.data = Storage.nodeBackend.load(Storage.dataFile);
808
+ keyValue = Storage.data?.[keyName];
809
+ break;
810
+ default:
811
+ keyValue = Storage.data?.[keyName] || null;
812
+ break;
813
+ }
814
+ try {
815
+ keyValue = JSON.parse(keyValue);
816
+ } catch {
817
+ // do nothing
818
+ }
819
+ break;
820
+ }
821
+ return keyValue ?? defaultValue;
822
+ }
823
+
824
+ /**
825
+ * 写入存储值。
826
+ * Write value into persistent storage.
827
+ *
828
+ * @param {string} keyName 键名或路径键 / Key or path key.
829
+ * @param {*} keyValue 写入值 / Value to store.
830
+ * @returns {boolean}
831
+ */
832
+ static setItem(keyName = new String(), keyValue = new String()) {
833
+ let result = false;
834
+ switch (typeof keyValue) {
835
+ case "object":
836
+ keyValue = JSON.stringify(keyValue);
837
+ break;
838
+ default:
839
+ keyValue = String(keyValue);
840
+ break;
841
+ }
842
+ switch (keyName.startsWith("@")) {
843
+ case true: {
844
+ const { key, path } = keyName.match(Storage.#nameRegex)?.groups;
845
+ keyName = key;
846
+ let value = Storage.getItem(keyName, {});
847
+ if (typeof value !== "object") value = {};
848
+ Lodash.set(value, path, keyValue);
849
+ result = Storage.setItem(keyName, value);
850
+ break;
851
+ }
852
+ default:
853
+ switch ($app) {
854
+ case "Surge":
855
+ case "Loon":
856
+ case "Stash":
857
+ case "Egern":
858
+ case "Shadowrocket":
859
+ result = $persistentStore.write(keyValue, keyName);
860
+ break;
861
+ case "Quantumult X":
862
+ result = $prefs.setValueForKey(keyValue, keyName);
863
+ break;
864
+ case "Worker":
865
+ Storage.data = Storage.data ?? {};
866
+ Storage.data[keyName] = keyValue;
867
+ result = true;
868
+ break;
869
+ case "Node.js":
870
+ Storage.data = Storage.nodeBackend.load(Storage.dataFile);
871
+ Storage.data[keyName] = keyValue;
872
+ Storage.nodeBackend.write(Storage.dataFile, Storage.data);
873
+ result = true;
874
+ break;
875
+ default:
876
+ result = Storage.data?.[keyName] || null;
877
+ break;
878
+ }
879
+ break;
880
+ }
881
+ return result;
882
+ }
883
+
884
+ /**
885
+ * 删除存储值。
886
+ * Remove value from persistent storage.
887
+ *
888
+ * 平台说明:
889
+ * Platform notes:
890
+ * - Quantumult X: `$prefs.removeValueForKey`
891
+ * - Surge: 通过 `$persistentStore.write(null, keyName)` 删除
892
+ * - 其余平台当前返回 `false`
893
+ *
894
+ * @param {string} keyName 键名或路径键 / Key or path key.
895
+ * @returns {boolean}
896
+ */
897
+ static removeItem(keyName) {
898
+ let result = false;
899
+ switch (keyName.startsWith("@")) {
900
+ case true: {
901
+ const { key, path } = keyName.match(Storage.#nameRegex)?.groups;
902
+ keyName = key;
903
+ let value = Storage.getItem(keyName);
904
+ if (typeof value !== "object") value = {};
905
+ Lodash.unset(value, path);
906
+ result = Storage.setItem(keyName, value);
907
+ break;
908
+ }
909
+ default:
910
+ switch ($app) {
911
+ case "Surge":
912
+ result = $persistentStore.write(null, keyName);
913
+ break;
914
+ case "Loon":
915
+ case "Stash":
916
+ case "Egern":
917
+ case "Shadowrocket":
918
+ result = false;
919
+ break;
920
+ case "Quantumult X":
921
+ result = $prefs.removeValueForKey(keyName);
922
+ break;
923
+ case "Worker":
924
+ Storage.data = Storage.data ?? {};
925
+ delete Storage.data[keyName];
926
+ result = true;
927
+ break;
928
+ case "Node.js":
929
+ // result = false;
930
+ Storage.data = Storage.nodeBackend.load(Storage.dataFile);
931
+ delete Storage.data[keyName];
932
+ Storage.nodeBackend.write(Storage.dataFile, Storage.data);
933
+ result = true;
934
+ break;
935
+ default:
936
+ result = false;
937
+ break;
938
+ }
939
+ break;
940
+ }
941
+ return result;
942
+ }
943
+
944
+ /**
945
+ * 清空存储。
946
+ * Clear storage.
947
+ *
948
+ * @returns {boolean}
949
+ */
950
+ static clear() {
951
+ let result = false;
952
+ switch ($app) {
953
+ case "Surge":
954
+ case "Loon":
955
+ case "Stash":
956
+ case "Egern":
957
+ case "Shadowrocket":
958
+ result = false;
959
+ break;
960
+ case "Quantumult X":
961
+ result = $prefs.removeAllValues();
962
+ break;
963
+ case "Worker":
964
+ Storage.data = {};
965
+ result = true;
966
+ break;
967
+ case "Node.js":
968
+ // result = false;
969
+ Storage.data = Storage.nodeBackend.load(Storage.dataFile);
970
+ Storage.data = {};
971
+ Storage.nodeBackend.write(Storage.dataFile, Storage.data);
972
+ result = true;
973
+ break;
974
+ default:
975
+ result = false;
976
+ break;
977
+ }
978
+ return result;
979
+ }
980
+ }
981
+
982
+ /**
983
+ * 校验原始路径片段,不进行 URL 编码转换。
984
+ * Validate raw path segments without URL encoding conversion.
985
+ * @param {string[]} parts 原始路径片段 / Raw path segments.
986
+ * @returns {string[]} 同一数组,不复制或修改 / The same array without copying or mutation.
987
+ * @throws {TypeError} 空片段、非法字符或原型属性名 / Empty segments, invalid characters or prototype property names.
988
+ */
989
+ function validatePathParts(parts) {
990
+ if (!parts.every(part => typeof part === "string" && /^[a-zA-Z0-9_-]+$/.test(part) && !["__proto__", "prototype", "constructor"].includes(part))) throw new TypeError("Invalid key path");
991
+ return parts;
992
+ }
993
+
994
+ /**
995
+ * 无配置绑定的本地存储桥接;form 字段名就是完整 @root.path。
996
+ * Unbound local storage bridge; the form field name is the complete @root.path.
997
+ */
998
+ class Store {
999
+ /**
1000
+ * POST /api/get、set、delete;不下载配置、不解析控件、不鉴权。
1001
+ * POST /api/get, set or delete without config downloads, control parsing or authentication.
1002
+ * @param {import("./index.js").SettingsRequest} request 代理请求 / Proxy request.
1003
+ * @param {URL} [url] 已解析地址 / Parsed URL.
1004
+ * @returns {Promise<import("./index.js").SettingsResponse | undefined>} 操作结果 / Operation result.
1005
+ */
1006
+ async handle(request, url = new URL(request.url)) {
1007
+ if (!url.pathname.startsWith("/api/")) return;
1008
+ const reply = (status, data) => response(request, status, data);
1009
+ const action = url.pathname.slice(5);
1010
+ if (!["get", "set", "delete"].includes(action)) return reply(404, { error: "Unknown action" });
1011
+ if (request.method !== "POST") return reply(405, { error: "Use POST with a form body" });
1012
+ const headers = Object.fromEntries(Object.entries(request.headers ?? {}).map(([key, value]) => [key.toLowerCase(), value]));
1013
+ if (headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") return reply(415, { error: "Expected application/x-www-form-urlencoded" });
1014
+ if (typeof request.body !== "string" || request.body.length > 65536) return reply(400, { error: "Expected a form body up to 65536 characters" });
1015
+ let parts, value;
1016
+ try {
1017
+ const fields = request.body.split("&");
1018
+ if (fields.length !== 1) throw new TypeError("Send exactly one storage key");
1019
+ const separator = fields[0].indexOf("=");
1020
+ if (separator < 0) throw new TypeError("Expected @root.path=value");
1021
+ const key = decodeURIComponent(fields[0].slice(0, separator).replace(/\+/g, " "));
1022
+ value = decodeURIComponent(fields[0].slice(separator + 1).replace(/\+/g, " "));
1023
+ if (!key.startsWith("@")) throw new TypeError("Storage keys must start with @");
1024
+ parts = validatePathParts(key.slice(1).split("."));
1025
+ if (parts.length < 2) throw new TypeError("Specify a storage root and child path");
1026
+ } catch (error) {
1027
+ return reply(400, { error: error.message });
1028
+ }
1029
+ if (action === "set") {
1030
+ try {
1031
+ value = JSON.parse(value);
1032
+ } catch (error) {
1033
+ if (!(error instanceof SyntaxError)) throw error;
1034
+ }
1035
+ }
1036
+ const [storageKey, ...path] = parts;
1037
+ try {
1038
+ const root = Storage.getItem(storageKey, {});
1039
+ if (!isRecord(root)) throw new TypeError("Stored root must be an object");
1040
+ const parent = storageParent(root, path, action === "set");
1041
+ const key = path.at(-1);
1042
+ switch (action) {
1043
+ case "get": {
1044
+ const result = parent ? Lodash.get(parent, [key]) : undefined;
1045
+ return result === undefined ? reply(404, { error: "Stored path does not exist" }) : reply(200, result);
1046
+ }
1047
+ case "set":
1048
+ Lodash.set(parent, [key], value);
1049
+ break;
1050
+ case "delete":
1051
+ if (parent) Lodash.unset(parent, [key]);
1052
+ break;
1053
+ }
1054
+ if (!Storage.setItem(storageKey, root)) throw new Error("Storage write failed");
1055
+ return reply(200, action === "set" ? { saved: true } : { deleted: true });
1056
+ } catch (error) {
1057
+ return reply(500, { error: error.message });
1058
+ }
1059
+ }
1060
+ }
1061
+
1062
+ /**
1063
+ * 判断根节点是否为普通对象。
1064
+ * Determine whether a root node is a plain object.
1065
+ * @param {unknown} value 待检查值 / Value to inspect.
1066
+ * @returns {boolean} 是否为普通对象 / Whether this is a plain object.
1067
+ */
1068
+ function isRecord(value) {
1069
+ return value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype;
1070
+ }
1071
+
1072
+ /**
1073
+ * 遍历父路径,兼容旧存储中 JSON 字符串形式的中间节点。
1074
+ * Traverse parents, supporting legacy intermediate nodes serialized as JSON strings.
1075
+ * @param {Record<string, unknown>} root 存储根 / Storage root.
1076
+ * @param {string[]} parts 完整路径 / Complete path.
1077
+ * @param {boolean} create 是否创建缺失节点 / Whether to create missing parents.
1078
+ * @returns {object | undefined} 父节点,缺失且不创建时为 undefined / Parent, or undefined when absent and not creating.
1079
+ * @throws {TypeError} 无法继续遍历标量节点 / A scalar node cannot be traversed.
1080
+ */
1081
+ function storageParent(root, parts, create) {
1082
+ let parent = root;
1083
+ for (const part of parts.slice(0, -1)) {
1084
+ let next = Lodash.get(parent, [part]);
1085
+ switch (typeof next) {
1086
+ case "undefined":
1087
+ if (!create) return;
1088
+ next = {};
1089
+ break;
1090
+ case "string":
1091
+ next = JSON.parse(next);
1092
+ break;
1093
+ }
1094
+ if (!isRecord(next) && !Array.isArray(next)) throw new TypeError("Stored parent is not an object or array");
1095
+ Lodash.set(parent, [part], next);
1096
+ parent = next;
1097
+ }
1098
+ return parent;
1099
+ }
1100
+
1101
+ /**
1102
+ * 统一日志工具,兼容各脚本平台、Worker 与 Node.js。
1103
+ * Unified logger compatible with script platforms, Worker, and Node.js.
1104
+ *
1105
+ * logLevel 用法:
1106
+ * logLevel usage:
1107
+ * - 可读: `Console.logLevel` 返回 `OFF|ERROR|WARN|INFO|DEBUG|ALL`
1108
+ * - Read: `Console.logLevel` returns `OFF|ERROR|WARN|INFO|DEBUG|ALL`
1109
+ * - 可写: 数字 `0~5` 或字符串 `off/error/warn/info/debug/all`
1110
+ * - Write: number `0~5` or string `off/error/warn/info/debug/all`
1111
+ *
1112
+ * @example
1113
+ * Console.logLevel = "debug";
1114
+ * Console.debug("only shown when level >= DEBUG");
1115
+ * Console.logLevel = 2; // WARN
1116
+ */
1117
+ class Console {
1118
+ static #counts = new Map([]);
1119
+ static #groups = [];
1120
+ static #times = new Map([]);
1121
+
1122
+ /**
1123
+ * 清空控制台(当前为空实现)。
1124
+ * Clear console (currently a no-op).
1125
+ *
1126
+ * @returns {void}
1127
+ */
1128
+ static clear = () => {};
1129
+
1130
+ /**
1131
+ * 增加计数器并打印当前值。
1132
+ * Increment counter and print the current value.
1133
+ *
1134
+ * @param {string} [label="default"] 计数器名称 / Counter label.
1135
+ * @returns {void}
1136
+ */
1137
+ static count = (label = "default") => {
1138
+ switch (Console.#counts.has(label)) {
1139
+ case true:
1140
+ Console.#counts.set(label, Console.#counts.get(label) + 1);
1141
+ break;
1142
+ case false:
1143
+ Console.#counts.set(label, 0);
1144
+ break;
1145
+ }
1146
+ Console.log(`${label}: ${Console.#counts.get(label)}`);
1147
+ };
1148
+
1149
+ /**
1150
+ * 重置计数器。
1151
+ * Reset a counter.
1152
+ *
1153
+ * @param {string} [label="default"] 计数器名称 / Counter label.
1154
+ * @returns {void}
1155
+ */
1156
+ static countReset = (label = "default") => {
1157
+ switch (Console.#counts.has(label)) {
1158
+ case true:
1159
+ Console.#counts.set(label, 0);
1160
+ Console.log(`${label}: ${Console.#counts.get(label)}`);
1161
+ break;
1162
+ case false:
1163
+ Console.warn(`Counter "${label}" doesn’t exist`);
1164
+ break;
1165
+ }
1166
+ };
1167
+
1168
+ /**
1169
+ * 输出调试日志。
1170
+ * Print debug logs.
1171
+ *
1172
+ * @param {...any} msg 日志内容 / Log messages.
1173
+ * @returns {void}
1174
+ */
1175
+ static debug = (...msg) => {
1176
+ if (Console.#level < 4) return;
1177
+ msg = msg.map(m => `🅱️ ${m}`);
1178
+ Console.log(...msg);
1179
+ };
1180
+
1181
+ /**
1182
+ * 输出错误日志。
1183
+ * Print error logs.
1184
+ *
1185
+ * @param {...any} msg 日志内容 / Log messages.
1186
+ * @returns {void}
1187
+ */
1188
+ static error(...msg) {
1189
+ if (Console.#level < 1) return;
1190
+ switch ($app) {
1191
+ case "Surge":
1192
+ case "Loon":
1193
+ case "Stash":
1194
+ case "Egern":
1195
+ case "Shadowrocket":
1196
+ case "Quantumult X":
1197
+ default:
1198
+ msg = msg.map(m => `❌ ${m}`);
1199
+ break;
1200
+ case "Worker":
1201
+ case "Node.js":
1202
+ msg = msg.map(m => `❌ ${m?.stack ?? m}`);
1203
+ break;
1204
+ }
1205
+ Console.log(...msg);
1206
+ }
1207
+
1208
+ /**
1209
+ * `error` 的别名。
1210
+ * Alias of `error`.
1211
+ *
1212
+ * @param {...any} msg 日志内容 / Log messages.
1213
+ * @returns {void}
1214
+ */
1215
+ static exception = (...msg) => Console.error(...msg);
1216
+
1217
+ /**
1218
+ * 进入日志分组。
1219
+ * Enter a log group.
1220
+ *
1221
+ * @param {string} label 分组名 / Group label.
1222
+ * @returns {number}
1223
+ */
1224
+ static group = label => Console.#groups.unshift(label);
1225
+
1226
+ /**
1227
+ * 退出日志分组。
1228
+ * Exit the latest log group.
1229
+ *
1230
+ * @returns {*}
1231
+ */
1232
+ static groupEnd = () => Console.#groups.shift();
1233
+
1234
+ /**
1235
+ * 输出信息日志。
1236
+ * Print info logs.
1237
+ *
1238
+ * @param {...any} msg 日志内容 / Log messages.
1239
+ * @returns {void}
1240
+ */
1241
+ static info(...msg) {
1242
+ if (Console.#level < 3) return;
1243
+ msg = msg.map(m => `ℹ️ ${m}`);
1244
+ Console.log(...msg);
1245
+ }
1246
+
1247
+ static #level = 3;
1248
+
1249
+ /**
1250
+ * 获取日志级别文本。
1251
+ * Get current log level text.
1252
+ *
1253
+ * @returns {"OFF"|"ERROR"|"WARN"|"INFO"|"DEBUG"|"ALL"}
1254
+ */
1255
+ static get logLevel() {
1256
+ switch (Console.#level) {
1257
+ case 0:
1258
+ return "OFF";
1259
+ case 1:
1260
+ return "ERROR";
1261
+ case 2:
1262
+ return "WARN";
1263
+ case 3:
1264
+ default:
1265
+ return "INFO";
1266
+ case 4:
1267
+ return "DEBUG";
1268
+ case 5:
1269
+ return "ALL";
1270
+ }
1271
+ }
1272
+
1273
+ /**
1274
+ * 设置日志级别。
1275
+ * Set current log level.
1276
+ *
1277
+ * @param {number|string} level 级别值 / Level value.
1278
+ */
1279
+ static set logLevel(level) {
1280
+ switch (typeof level) {
1281
+ case "string":
1282
+ level = level.toLowerCase();
1283
+ break;
1284
+ case "number":
1285
+ break;
1286
+ case "undefined":
1287
+ default:
1288
+ level = "warn";
1289
+ break;
1290
+ }
1291
+ switch (level) {
1292
+ case 0:
1293
+ case "off":
1294
+ Console.#level = 0;
1295
+ break;
1296
+ case 1:
1297
+ case "error":
1298
+ Console.#level = 1;
1299
+ break;
1300
+ case 2:
1301
+ case "warn":
1302
+ case "warning":
1303
+ default:
1304
+ Console.#level = 2;
1305
+ break;
1306
+ case 3:
1307
+ case "info":
1308
+ Console.#level = 3;
1309
+ break;
1310
+ case 4:
1311
+ case "debug":
1312
+ Console.#level = 4;
1313
+ break;
1314
+ case 5:
1315
+ case "all":
1316
+ Console.#level = 5;
1317
+ break;
1318
+ }
1319
+ }
1320
+
1321
+ /**
1322
+ * 输出通用日志。
1323
+ * Print generic logs.
1324
+ *
1325
+ * 说明:
1326
+ * Notes:
1327
+ * - 多行字符串参数会按换行拆分为多个独立日志项。
1328
+ * - Multi-line string arguments are split into multiple log entries by line breaks.
1329
+ *
1330
+ * @param {...any} msg 日志内容 / Log messages.
1331
+ * @returns {void}
1332
+ */
1333
+ static log = (...msg) => {
1334
+ if (Console.#level === 0) return;
1335
+ msg = msg.flatMap(log => {
1336
+ switch (typeof log) {
1337
+ case "object":
1338
+ return [JSON.stringify(log)];
1339
+ case "bigint":
1340
+ case "number":
1341
+ case "boolean":
1342
+ return [log.toString()];
1343
+ case "string":
1344
+ return log.split(/\r?\n/u);
1345
+ case "undefined":
1346
+ default:
1347
+ return [log];
1348
+ }
1349
+ });
1350
+ Console.#groups.forEach(group => {
1351
+ msg = msg.map(log => ` ${log}`);
1352
+ msg.unshift(`▼ ${group}:`);
1353
+ });
1354
+ msg = ["", ...msg];
1355
+ console.log(msg.join("\n"));
1356
+ };
1357
+
1358
+ /**
1359
+ * 开始计时。
1360
+ * Start timer.
1361
+ *
1362
+ * @param {string} [label="default"] 计时器名称 / Timer label.
1363
+ * @returns {Map<string, number>}
1364
+ */
1365
+ static time = (label = "default") => Console.#times.set(label, Date.now());
1366
+
1367
+ /**
1368
+ * 结束计时并移除计时器。
1369
+ * End timer and remove it.
1370
+ *
1371
+ * @param {string} [label="default"] 计时器名称 / Timer label.
1372
+ * @returns {boolean}
1373
+ */
1374
+ static timeEnd = (label = "default") => Console.#times.delete(label);
1375
+
1376
+ /**
1377
+ * 输出当前计时器耗时。
1378
+ * Print elapsed time for a timer.
1379
+ *
1380
+ * @param {string} [label="default"] 计时器名称 / Timer label.
1381
+ * @returns {void}
1382
+ */
1383
+ static timeLog = (label = "default") => {
1384
+ const time = Console.#times.get(label);
1385
+ if (time) Console.log(`${label}: ${Date.now() - time}ms`);
1386
+ else Console.warn(`Timer "${label}" doesn’t exist`);
1387
+ };
1388
+
1389
+ /**
1390
+ * 输出警告日志。
1391
+ * Print warning logs.
1392
+ *
1393
+ * @param {...any} msg 日志内容 / Log messages.
1394
+ * @returns {void}
1395
+ */
1396
+ static warn(...msg) {
1397
+ if (Console.#level < 2) return;
1398
+ msg = msg.map(m => `⚠️ ${m}`);
1399
+ Console.log(...msg);
1400
+ }
1401
+ }
1402
+
1403
+ /**
1404
+ * HTTP 状态码文本映射表。
1405
+ * HTTP status code to status text map.
1406
+ *
1407
+ * 主要用途:
1408
+ * Primary usage:
1409
+ * - 为 Quantumult X 的 `$done` 状态行拼接提供状态文本
1410
+ * - Provide status text for Quantumult X `$done` status-line composition
1411
+ * - QX 在部分场景要求 `status` 为完整状态行(如 `HTTP/1.1 200 OK`)
1412
+ * - QX may require full status line (e.g. `HTTP/1.1 200 OK`) in some cases
1413
+ *
1414
+ * 参考:
1415
+ * Reference:
1416
+ * - https://github.com/crossutility/Quantumult-X/raw/refs/heads/master/sample-rewrite-response-header.js
1417
+ *
1418
+ * @type {Record<number, string>}
1419
+ */
1420
+ const StatusTexts = {
1421
+ 100: "Continue",
1422
+ 101: "Switching Protocols",
1423
+ 102: "Processing",
1424
+ 103: "Early Hints",
1425
+ 200: "OK",
1426
+ 201: "Created",
1427
+ 202: "Accepted",
1428
+ 203: "Non-Authoritative Information",
1429
+ 204: "No Content",
1430
+ 205: "Reset Content",
1431
+ 206: "Partial Content",
1432
+ 207: "Multi-Status",
1433
+ 208: "Already Reported",
1434
+ 226: "IM Used",
1435
+ 300: "Multiple Choices",
1436
+ 301: "Moved Permanently",
1437
+ 302: "Found",
1438
+ 304: "Not Modified",
1439
+ 307: "Temporary Redirect",
1440
+ 308: "Permanent Redirect",
1441
+ 400: "Bad Request",
1442
+ 401: "Unauthorized",
1443
+ 402: "Payment Required",
1444
+ 403: "Forbidden",
1445
+ 404: "Not Found",
1446
+ 405: "Method Not Allowed",
1447
+ 406: "Not Acceptable",
1448
+ 407: "Proxy Authentication Required",
1449
+ 408: "Request Timeout",
1450
+ 409: "Conflict",
1451
+ 410: "Gone",
1452
+ 411: "Length Required",
1453
+ 412: "Precondition Failed",
1454
+ 413: "Content Too Large",
1455
+ 414: "URI Too Long",
1456
+ 415: "Unsupported Media Type",
1457
+ 416: "Range Not Satisfiable",
1458
+ 417: "Expectation Failed",
1459
+ 418: "I'm a teapot",
1460
+ 421: "Misdirected Request",
1461
+ 422: "Unprocessable Entity",
1462
+ 423: "Locked",
1463
+ 424: "Failed Dependency",
1464
+ 425: "Too Early",
1465
+ 426: "Upgrade Required",
1466
+ 428: "Precondition Required",
1467
+ 429: "Too Many Requests",
1468
+ 431: "Request Header Fields Too Large",
1469
+ 451: "Unavailable For Legal Reasons",
1470
+ 500: "Internal Server Error",
1471
+ 501: "Not Implemented",
1472
+ 502: "Bad Gateway",
1473
+ 503: "Service Unavailable",
1474
+ 504: "Gateway Timeout",
1475
+ 505: "HTTP Version Not Supported",
1476
+ 506: "Variant Also Negotiates",
1477
+ 507: "Insufficient Storage",
1478
+ 508: "Loop Detected",
1479
+ 510: "Not Extended",
1480
+ 511: "Network Authentication Required",
1481
+ };
1482
+
1483
+ /**
1484
+ * `done` 的统一入参结构。
1485
+ * Unified `done` input payload.
1486
+ *
1487
+ * @typedef {object} DonePayload
1488
+ * @property {number|string} [status] 响应状态码或状态行 / Response status code or status line.
1489
+ * @property {string} [url] 响应 URL / Response URL.
1490
+ * @property {Record<string, any>} [headers] 响应头 / Response headers.
1491
+ * @property {string|ArrayBuffer|ArrayBufferView} [body] 响应体 / Response body.
1492
+ * @property {ArrayBuffer} [bodyBytes] 二进制响应体 / Binary response body.
1493
+ * @property {string} [policy] 指定策略名 / Preferred policy name.
1494
+ */
1495
+
1496
+ /**
1497
+ * 结束脚本执行并按平台转换参数。
1498
+ * Complete script execution with platform-specific parameter mapping.
1499
+ *
1500
+ * 说明:
1501
+ * Notes:
1502
+ * - 这是调用入口,平台原生 `$done` 差异在内部处理
1503
+ * - This is the call entry and native `$done` differences are handled internally
1504
+ * - Worker 不调用 `$done` 或退出进程,仅记录日志
1505
+ * - Worker neither calls `$done` nor exits the process; it only logs
1506
+ * - Node.js 不调用 `$done`,而是直接退出进程
1507
+ * - Node.js does not call `$done`; it exits the process directly
1508
+ * - 未识别平台仅记录结束日志,不会强制退出
1509
+ * - Unknown runtimes only log completion and do not force an exit
1510
+ *
1511
+ * @param {DonePayload} [object={}] 统一响应对象 / Unified response object.
1512
+ * @returns {void}
1513
+ */
1514
+ function done(object = {}) {
1515
+ switch ($app) {
1516
+ case "Surge":
1517
+ if (object.policy) Lodash.set(object, "headers.X-Surge-Policy", object.policy);
1518
+ Console.log("🚩 执行结束!", `🕛 ${new Date().getTime() / 1000 - $script.startTime} 秒`);
1519
+ $done(object);
1520
+ break;
1521
+ case "Loon":
1522
+ if (object.policy) object.node = object.policy;
1523
+ Console.log("🚩 执行结束!", `🕛 ${(new Date() - $script.startTime) / 1000} 秒`);
1524
+ $done(object);
1525
+ break;
1526
+ case "Stash":
1527
+ if (object.policy) Lodash.set(object, "headers.X-Stash-Selected-Proxy", encodeURI(object.policy));
1528
+ Console.log("🚩 执行结束!", `🕛 ${(new Date() - $script.startTime) / 1000} 秒`);
1529
+ $done(object);
1530
+ break;
1531
+ case "Egern":
1532
+ Console.log("🚩 执行结束!");
1533
+ $done(object);
1534
+ break;
1535
+ case "Shadowrocket":
1536
+ Console.log("🚩 执行结束!");
1537
+ $done(object);
1538
+ break;
1539
+ case "Quantumult X":
1540
+ if (object.policy) Lodash.set(object, "opts.policy", object.policy);
1541
+ object = Lodash.pick(object, ["status", "url", "headers", "body", "bodyBytes"]);
1542
+ switch (typeof object.status) {
1543
+ case "number":
1544
+ object.status = `HTTP/1.1 ${object.status} ${StatusTexts[object.status]}`;
1545
+ break;
1546
+ case "string":
1547
+ case "undefined":
1548
+ break;
1549
+ default:
1550
+ throw new TypeError(`${Function.name}: 参数类型错误, status 必须为数字或字符串`);
1551
+ }
1552
+ if (object.body instanceof ArrayBuffer) {
1553
+ object.bodyBytes = object.body;
1554
+ object.body = undefined;
1555
+ } else if (ArrayBuffer.isView(object.body)) {
1556
+ object.bodyBytes = object.body.buffer.slice(object.body.byteOffset, object.body.byteLength + object.body.byteOffset);
1557
+ object.body = undefined;
1558
+ } else if (object.body) object.bodyBytes = undefined;
1559
+ Console.log("🚩 执行结束!");
1560
+ $done(object);
1561
+ break;
1562
+ case "Worker":
1563
+ Console.log("🚩 执行结束!");
1564
+ break;
1565
+ case "Node.js":
1566
+ Console.log("🚩 执行结束!");
1567
+ process.exit(1);
1568
+ break;
1569
+ default:
1570
+ Console.log("🚩 执行结束!");
1571
+ break;
1572
+ }
1573
+ }
1574
+
1575
+ /**
1576
+ * 统一适配代理的完成格式;未接管的请求原样继续。
1577
+ * Adapt the host completion format and pass through unhandled requests.
1578
+ * @param {import("../index.js").SettingsResponse | undefined} result 通用响应 / Common response.
1579
+ * @returns {void} 响应已交给宿主 / Response delivered to the host.
1580
+ */
1581
+ function complete(result) {
1582
+ if (!result) {
1583
+ done({});
1584
+ return;
1585
+ }
1586
+ done($app === "Quantumult X" ? result : { response: result });
1587
+ }
1588
+
1589
+ /**
1590
+ * 通用代理入口:提供无鉴权 form 存储 API 及模块页面,不含业务配置。
1591
+ * Generic proxy entry serving unauthenticated form storage and module pages without business configuration.
1592
+ * @returns {Promise<void>} 已交给代理宿主的响应 / Response delivered to the proxy host.
1593
+ */
1594
+ async function run() {
1595
+ const request = globalThis.$request;
1596
+ let result;
1597
+ try {
1598
+ const url = new URL(request.url);
1599
+ switch (true) {
1600
+ case url.pathname.startsWith("/api/"):
1601
+ result = await new Store().handle(request, url);
1602
+ break;
1603
+ case /^\/settings\/[a-zA-Z0-9_-]+\/?$/.test(url.pathname): {
1604
+ const inputs = encodeURIComponent(JSON.stringify(pageInputs(url, request.headers)));
1605
+ result = response(request, 200, assets.page.body.replace("</head>", `<meta name="preference-panes-inputs" content="${inputs}"></head>`), "text/html");
1606
+ break;
1607
+ }
1608
+ default: {
1609
+ const asset = assets[url.pathname];
1610
+ if (asset) result = response(request, 200, asset.body, asset.type);
1611
+ }
1612
+ }
1613
+ if (result && !url.pathname.startsWith("/api/") && !["GET", "HEAD"].includes(request.method)) result = response(request, 405, { error: "Method not allowed" });
1614
+ } catch (error) {
1615
+ console.error(`PreferencePanes: ${error.message}`);
1616
+ result = response(request, 500, { error: error.message });
1617
+ }
1618
+ complete(result);
1619
+ }
1620
+ run();
1621
+
1622
+ })();