(code: string)
| 2 | import type { UserConfig } from "@App/app/repo/scripts"; |
| 3 | |
| 4 | export function parseUserConfig(code: string): UserConfig | undefined { |
| 5 | const regex = /\/\*\s*==UserConfig==([\s\S]+?)\s*==\/UserConfig==\s*\*\//m; |
| 6 | const config = regex.exec(code); |
| 7 | if (!config) { |
| 8 | return undefined; |
| 9 | } |
| 10 | |
| 11 | const configs = config[1].trim().split(/[-]{3,}/); |
| 12 | const ret = Object.create(null) as UserConfig; |
| 13 | |
| 14 | const sortSet = new Set<string>(); |
| 15 | |
| 16 | for (const val of configs) { |
| 17 | const obj: UserConfig = parse(val); |
| 18 | if (!obj || typeof obj !== "object") { |
| 19 | continue; |
| 20 | } |
| 21 | // 验证是否符合分组规范:group -> config -> properties |
| 22 | for (const [groupKey, groupValue] of Object.entries(obj)) { |
| 23 | // Reject keys inherited from Object.prototype (e.g. __proto__, constructor, |
| 24 | // valueOf, toString) so untrusted userscript metadata can't pollute lookups. |
| 25 | if (Reflect.has(Object.prototype, groupKey)) { |
| 26 | throw new Error(`UserConfig key "${groupKey}" is not valid.`); |
| 27 | } |
| 28 | |
| 29 | if (!groupValue || typeof groupValue !== "object") { |
| 30 | // 如果分组值不是对象,说明不符合规范 |
| 31 | throw new Error(`UserConfig group "${groupKey}" is not a valid object.`); |
| 32 | } |
| 33 | |
| 34 | //@ts-ignore |
| 35 | ret[groupKey] = groupValue; |
| 36 | |
| 37 | if (groupKey === "#options") { |
| 38 | continue; |
| 39 | } |
| 40 | |
| 41 | sortSet.add(groupKey); |
| 42 | |
| 43 | Object.keys(ret[groupKey] || {}).forEach((subKey, subIndex) => { |
| 44 | const groupData = ret[groupKey] as { [key: string]: any }; |
| 45 | if (groupData[subKey] && typeof groupData[subKey] === "object") { |
| 46 | groupData[subKey].index = groupData[subKey].index || subIndex; // 确保index存在 |
| 47 | } |
| 48 | }); |
| 49 | } |
| 50 | } |
| 51 | ret["#options"] = { sort: Array.from(sortSet) }; |
| 52 | return ret; |
| 53 | } |
no test coverage detected