import * as fs from "fs"; import sqlite3 from "sqlite3"; import { DB_FILE, LEGACY_DB_FILE, MOCK_DIR, DATA_DIR } from "./constants"; import { state } from "./state"; import { normalizeStatusCode } from "./utils"; import type { ApiListItem, AppConfig, MockFileRow, MockGroupRow, RouteApiNameMap, RouteConfig, RouteEnabledMap, RouteRow, RouteStatusConfig, IpRule, IpRuleRow, IpRuleConfig, } from "./types"; export function dbRun(sql: string, params: unknown[] = []): Promise { return new Promise((resolve, reject) => { state.db.run(sql, params, (error) => { if (error) { reject(error); return; } resolve(); }); }); } export function dbAll( sql: string, params: unknown[] = [], ): Promise { return new Promise((resolve, reject) => { state.db.all(sql, params, (error, rows) => { if (error) { reject(error); return; } resolve((rows as T[]) || []); }); }); } export function openDatabase(): Promise { return new Promise((resolve, reject) => { state.db = new sqlite3.Database(DB_FILE, (error) => { if (error) { reject(error); return; } resolve(); }); }); } async function tableExists(name: string): Promise { const rows = await dbAll<{ cnt: number }>( "SELECT COUNT(*) AS cnt FROM sqlite_master WHERE type='table' AND name=?", [name], ); return (rows[0]?.cnt ?? 0) > 0; } export async function initDatabase(): Promise { fs.mkdirSync(MOCK_DIR, { recursive: true }); fs.mkdirSync(DATA_DIR, { recursive: true }); if (!fs.existsSync(DB_FILE) && fs.existsSync(LEGACY_DB_FILE)) { fs.copyFileSync(LEGACY_DB_FILE, DB_FILE); console.log( `[DB] 已从旧路径迁移数据库: ${LEGACY_DB_FILE} -> ${DB_FILE}`, ); } await openDatabase(); await dbRun(` CREATE TABLE IF NOT EXISTS route_mappings ( route_key TEXT PRIMARY KEY, file_path TEXT NOT NULL, status_code INTEGER NOT NULL DEFAULT 200 ) `); await dbRun( "ALTER TABLE route_mappings ADD COLUMN status_code INTEGER NOT NULL DEFAULT 200", ).catch(() => { // ignore when column already exists }); await dbRun( "ALTER TABLE route_mappings ADD COLUMN enabled INTEGER NOT NULL DEFAULT 1", ).catch(() => { // ignore when column already exists }); await dbRun( "ALTER TABLE route_mappings ADD COLUMN api_name TEXT NOT NULL DEFAULT ''", ).catch(() => { // ignore when column already exists }); // 迁移:将 # 前缀路由转为 enabled=0 并去掉前缀 const hashRoutes = await dbAll( "SELECT route_key, file_path, status_code FROM route_mappings WHERE route_key LIKE '#%'", ); for (const row of hashRoutes) { const cleanKey = row.route_key.replace(/^#+/, ""); await dbRun("DELETE FROM route_mappings WHERE route_key = ?", [row.route_key]); await dbRun( "INSERT OR IGNORE INTO route_mappings(route_key, file_path, status_code, enabled) VALUES(?, ?, ?, 0)", [cleanKey, row.file_path, row.status_code], ); } await dbRun(` CREATE TABLE IF NOT EXISTS api_list ( route TEXT PRIMARY KEY, name TEXT NOT NULL ) `); await dbRun(` CREATE TABLE IF NOT EXISTS mock_groups ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE ) `); await dbRun(` CREATE TABLE IF NOT EXISTS mock_files ( file_path TEXT PRIMARY KEY, alias TEXT NOT NULL DEFAULT '' ) `); await dbRun( "ALTER TABLE mock_files ADD COLUMN alias TEXT NOT NULL DEFAULT ''", ).catch(() => { // ignore when column already exists }); await dbRun( "ALTER TABLE mock_files ADD COLUMN group_id INTEGER", ).catch(() => { // ignore when column already exists }); await dbRun(` CREATE TABLE IF NOT EXISTS server_config ( key TEXT PRIMARY KEY, value TEXT NOT NULL ) `); const hadIpRules = await tableExists("ip_rules"); await dbRun(` CREATE TABLE IF NOT EXISTS ip_rules ( ip TEXT PRIMARY KEY, blocked INTEGER NOT NULL DEFAULT 0, remark TEXT NOT NULL DEFAULT '', use_custom_config INTEGER NOT NULL DEFAULT 0, mock_enabled INTEGER, default_content_type TEXT, target_host TEXT, target_port INTEGER, target_https INTEGER ) `); if (!hadIpRules) { console.log("[DB] 数据库已自动升级: 新增 IP 管理(ip_rules)表"); } // 清理不该出现在 mock 列表中的系统数据 await dbRun( "DELETE FROM mock_files WHERE file_path = ? OR file_path LIKE ?", ["mock/api-list.json", "%.sqlite3"], ); } export async function saveRoutesToDb( routes: RouteConfig, routeStatuses: RouteStatusConfig = {}, routeEnabledMap: RouteEnabledMap = {}, routeApiNameMap: RouteApiNameMap = {}, ): Promise { await dbRun("DELETE FROM route_mappings"); for (const [routeKey, filePath] of Object.entries(routes)) { const statusCode = normalizeStatusCode(routeStatuses[routeKey], 200); const enabled = routeEnabledMap[routeKey] !== false ? 1 : 0; const apiName = routeApiNameMap[routeKey] || ""; await dbRun( "INSERT INTO route_mappings(route_key, file_path, status_code, enabled, api_name) VALUES(?, ?, ?, ?, ?)", [routeKey, filePath, statusCode, enabled, apiName], ); await dbRun("INSERT OR IGNORE INTO mock_files(file_path) VALUES(?)", [ filePath, ]); } } export async function loadRoutesFromDb(): Promise<{ routes: RouteConfig; routeStatuses: RouteStatusConfig; routeEnabledMap: RouteEnabledMap; routeApiNameMap: RouteApiNameMap; }> { const rows = await dbAll( "SELECT route_key, file_path, status_code, enabled, api_name FROM route_mappings ORDER BY route_key ASC", ); const routes: RouteConfig = {}; const routeStatuses: RouteStatusConfig = {}; const routeEnabledMap: RouteEnabledMap = {}; const routeApiNameMap: RouteApiNameMap = {}; for (const row of rows) { routes[row.route_key] = row.file_path; routeStatuses[row.route_key] = normalizeStatusCode(row.status_code, 200); routeEnabledMap[row.route_key] = row.enabled !== 0; if (row.api_name) { routeApiNameMap[row.route_key] = row.api_name; } } return { routes, routeStatuses, routeEnabledMap, routeApiNameMap }; } export async function upsertApiListToDb(list: ApiListItem[]): Promise { await dbRun("DELETE FROM api_list"); for (const item of list) { await dbRun("INSERT INTO api_list(route, name) VALUES(?, ?)", [ item.route, item.name, ]); } } export async function loadApiListFromDb(): Promise { const rows = await dbAll<{ route: string; name: string }>( "SELECT route, name FROM api_list ORDER BY route ASC", ); return rows.map((row) => ({ route: row.route, name: row.name })); } export async function insertApiItemToDb(item: ApiListItem): Promise { await dbRun("INSERT INTO api_list(route, name) VALUES(?, ?)", [ item.route, item.name, ]); } export async function updateApiItemInDb( oldRoute: string, item: ApiListItem, ): Promise { await dbRun("UPDATE api_list SET route = ?, name = ? WHERE route = ?", [ item.route, item.name, oldRoute, ]); } export async function deleteApiItemFromDb(route: string): Promise { await dbRun("DELETE FROM api_list WHERE route = ?", [route]); } export async function upsertMockFilePathToDb( filePath: string, alias?: string, groupId?: number | null, ): Promise { if (typeof alias === "string") { if (typeof groupId !== "undefined") { await dbRun( "INSERT INTO mock_files(file_path, alias, group_id) VALUES(?, ?, ?) ON CONFLICT(file_path) DO UPDATE SET alias = excluded.alias, group_id = excluded.group_id", [filePath, alias, groupId ?? null], ); return; } await dbRun( "INSERT INTO mock_files(file_path, alias) VALUES(?, ?) ON CONFLICT(file_path) DO UPDATE SET alias = excluded.alias", [filePath, alias], ); return; } await dbRun("INSERT OR IGNORE INTO mock_files(file_path, alias) VALUES(?, '')", [ filePath, ]); } export async function removeMockFilePathFromDb(filePath: string): Promise { await dbRun("DELETE FROM mock_files WHERE file_path = ?", [filePath]); } export async function loadMockFilePathsFromDb(): Promise { const rows = await dbAll( "SELECT file_path, alias, group_id FROM mock_files ORDER BY file_path ASC", ); return rows.map((row) => ({ file_path: row.file_path, alias: String(row.alias || ""), group_id: row.group_id ?? null, })); } // ── mock_groups CRUD ── export async function loadMockGroups(): Promise { const rows = await dbAll( "SELECT id, name FROM mock_groups ORDER BY id ASC", ); return rows.map((row) => ({ id: row.id, name: row.name })); } export async function insertMockGroup(name: string): Promise { await dbRun("INSERT INTO mock_groups(name) VALUES(?)", [name]); const row = await dbAll<{ id: number }>( "SELECT id FROM mock_groups WHERE name = ?", [name], ); return row[0]?.id ?? 0; } export async function updateMockGroup( id: number, name: string, ): Promise { await dbRun("UPDATE mock_groups SET name = ? WHERE id = ?", [name, id]); } export async function deleteMockGroup(id: number): Promise { await dbRun("DELETE FROM mock_groups WHERE id = ?", [id]); } export async function countMockFilesByGroup( groupId: number, ): Promise { const rows = await dbAll<{ cnt: number }>( "SELECT COUNT(*) AS cnt FROM mock_files WHERE group_id = ?", [groupId], ); return rows[0]?.cnt ?? 0; } export async function updateMockFilesGroupId( oldGroupId: number, newGroupId: number | null, ): Promise { await dbRun("UPDATE mock_files SET group_id = ? WHERE group_id = ?", [ newGroupId, oldGroupId, ]); } export async function deleteMockFilesByGroup( groupId: number, ): Promise { const rows = await dbAll( "SELECT file_path FROM mock_files WHERE group_id = ?", [groupId], ); await dbRun("DELETE FROM mock_files WHERE group_id = ?", [groupId]); return rows.map((row) => ({ file_path: row.file_path, alias: "", group_id: null })); } const DEFAULT_SERVER_CONFIG: AppConfig = { cacheConfig: true, reloadOnChange: true, defaultContentType: "application/json", proxyPort: 8879, targetHost: "localhost", targetPort: 80, targetHttps: false, }; export async function loadServerConfig(): Promise { const rows = await dbAll<{ key: string; value: string }>( "SELECT key, value FROM server_config", ); if (rows.length === 0) { return { ...DEFAULT_SERVER_CONFIG }; } const map = new Map(rows.map((r) => [r.key, r.value])); return { mockEnabled: map.has("mockEnabled") ? map.get("mockEnabled") === "true" : undefined, cacheConfig: map.get("cacheConfig") !== "false", reloadOnChange: map.get("reloadOnChange") !== "false", defaultContentType: map.get("defaultContentType") || DEFAULT_SERVER_CONFIG.defaultContentType, proxyPort: Number(map.get("proxyPort")) || DEFAULT_SERVER_CONFIG.proxyPort, targetHost: map.get("targetHost") || DEFAULT_SERVER_CONFIG.targetHost, targetPort: Number(map.get("targetPort")) || DEFAULT_SERVER_CONFIG.targetPort, targetHttps: map.get("targetHttps") === "true", }; } export async function saveServerConfig(config: AppConfig): Promise { const entries: [string, string][] = [ ["mockEnabled", String(config.mockEnabled !== false)], ["cacheConfig", String(config.cacheConfig)], ["reloadOnChange", String(config.reloadOnChange)], ["defaultContentType", config.defaultContentType], ["proxyPort", String(config.proxyPort)], ["targetHost", config.targetHost], ["targetPort", String(config.targetPort ?? "")], ["targetHttps", String(config.targetHttps !== false)], ]; await dbRun("DELETE FROM server_config"); for (const [key, value] of entries) { await dbRun("INSERT INTO server_config(key, value) VALUES(?, ?)", [ key, value, ]); } } function rowToIpRule(row: IpRuleRow): IpRule { const config: IpRuleConfig = {}; if (row.mock_enabled != null) { config.mockEnabled = row.mock_enabled !== 0; } if (row.default_content_type) { config.defaultContentType = row.default_content_type; } if (row.target_host) { config.targetHost = row.target_host; } if (row.target_port != null) { config.targetPort = row.target_port; } if (row.target_https != null) { config.targetHttps = row.target_https !== 0; } return { ip: row.ip, blocked: row.blocked !== 0, remark: row.remark || "", useCustomConfig: row.use_custom_config !== 0, config, }; } export async function loadIpRulesFromDb(): Promise { const rows = await dbAll( "SELECT ip, blocked, remark, use_custom_config, mock_enabled, default_content_type, target_host, target_port, target_https FROM ip_rules ORDER BY ip ASC", ); return rows.map(rowToIpRule); } export async function upsertIpRuleToDb(rule: IpRule): Promise { const mockEnabled = rule.config.mockEnabled !== undefined ? rule.config.mockEnabled ? 1 : 0 : null; const targetHttps = rule.config.targetHttps !== undefined ? rule.config.targetHttps ? 1 : 0 : null; await dbRun( `INSERT INTO ip_rules( ip, blocked, remark, use_custom_config, mock_enabled, default_content_type, target_host, target_port, target_https ) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(ip) DO UPDATE SET blocked = excluded.blocked, remark = excluded.remark, use_custom_config = excluded.use_custom_config, mock_enabled = excluded.mock_enabled, default_content_type = excluded.default_content_type, target_host = excluded.target_host, target_port = excluded.target_port, target_https = excluded.target_https`, [ rule.ip, rule.blocked ? 1 : 0, rule.remark || "", rule.useCustomConfig ? 1 : 0, mockEnabled, rule.config.defaultContentType || null, rule.config.targetHost || null, rule.config.targetPort ?? null, targetHttps, ], ); } export async function deleteIpRuleFromDb(ip: string): Promise { await dbRun("DELETE FROM ip_rules WHERE ip = ?", [ip]); } export async function saveAllIpRulesToDb(rules: IpRule[]): Promise { await dbRun("DELETE FROM ip_rules"); for (const rule of rules) { await upsertIpRuleToDb(rule); } }