import { app, BrowserWindow, ipcMain } from "electron"; import fsSync from "node:fs"; import os from "node:os"; import path from "node:path"; import { CH, type AssetRow, type Check, type EventRow, type PathRow, type Snapshot, } from "../shared/ipc"; app.setName("Paths Assets Lab"); const isSmoke = process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1"; const isShots = process.argv.includes("--shots"); const tempData = isSmoke || isShots ? path.join(os.tmpdir(), `paths50-${process.pid}`) : ""; if (tempData) app.setPath("userData", tempData); const appRoot = app.getAppPath(); const userData = app.getPath("userData"); const tempDir = app.getPath("temp"); const logsDir = app.getPath("logs"); const assetsDir = path.join(__dirname, "assets"); const assetFile = path.join(assetsDir, "notice.txt"); const extraName = "extra.txt"; let win: BrowserWindow | null = null; let events: EventRow[] = []; const flags = { userDataWritable: false, tempWritable: false, appRootWritable: false, extraResolved: false, }; fsSync.mkdirSync(logsDir, { recursive: true }); function log(kind: string, detail: string): void { events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40); broadcast(); } function broadcast(): void { if (win && !win.isDestroyed()) { win.webContents.send("paths:event", { at: Date.now() }); } } function canWrite(dir: string): boolean { const probe = path.join(dir, `.probe-${process.pid}`); try { fsSync.mkdirSync(dir, { recursive: true }); fsSync.writeFileSync(probe, "ok", "utf8"); const value = fsSync.readFileSync(probe, "utf8"); fsSync.rmSync(probe, { force: true }); return value === "ok"; } catch { try { fsSync.rmSync(probe, { force: true }); } catch { // 探针清理失败不影响结果。 } return false; } } function insideAsar(value: string): boolean { return value.includes(".asar/") || value.endsWith(".asar"); } function pathRow( id: string, label: string, value: string, kind: "dir" | "file", writableOverride?: boolean, ): PathRow { let exists = false; try { exists = fsSync.existsSync(value); } catch { exists = false; } let writable = writableOverride ?? false; if (writableOverride === undefined && kind === "dir" && exists) { writable = canWrite(value); } return { id, label, value, kind, exists, insideAsar: insideAsar(value), writable, }; } function resolveExtra(): { file: string; via: AssetRow["via"] } { const packaged = path.join(process.resourcesPath, "extra", extraName); if (fsSync.existsSync(packaged)) { return { file: packaged, via: "resourcesPath" }; } const dev = path.join(appRoot, "resources/extra", extraName); return { file: dev, via: "appPath" }; } function assetRow( id: string, label: string, file: string, via: AssetRow["via"], ): AssetRow { try { const buffer = fsSync.readFileSync(file); const preview = buffer .toString("utf8") .split(/\r?\n/) .filter(Boolean)[0] ?.slice(0, 60); return { id, label, resolved: file, via, exists: true, bytes: buffer.byteLength, preview: preview ?? "", insideAsar: insideAsar(file), }; } catch { return { id, label, resolved: file, via, exists: false, bytes: 0, preview: "", insideAsar: insideAsar(file), }; } } function inspectPaths(): PathRow[] { return [ pathRow("appPath", "app.getAppPath()", appRoot, "dir"), pathRow("dirname", "__dirname", __dirname, "dir"), pathRow("resources", "process.resourcesPath", process.resourcesPath, "dir"), pathRow("exec", "process.execPath", process.execPath, "file", false), pathRow("userData", "app.getPath('userData')", userData, "dir"), pathRow("temp", "app.getPath('temp')", tempDir, "dir"), pathRow("logs", "app.getPath('logs')", logsDir, "dir"), pathRow("assets", "assets/notice.txt", assetFile, "file", false), ]; } function inspectAssets(): AssetRow[] { const extra = resolveExtra(); flags.extraResolved = fsSync.existsSync(extra.file); return [ assetRow("bundled", "asar 内资源", assetFile, "appPath"), assetRow("extra", "extraResource", extra.file, extra.via), ]; } function checks(paths: PathRow[], assets: AssetRow[]): Check[] { const appPath = paths.find((row) => row.id === "appPath"); const user = paths.find((row) => row.id === "userData"); const temp = paths.find((row) => row.id === "temp"); const logs = paths.find((row) => row.id === "logs"); const bundled = assets.find((row) => row.id === "bundled"); const extra = assets.find((row) => row.id === "extra"); const packaged = app.isPackaged; const asar = insideAsar(appRoot); return [ { id: "app-path", label: "app.getAppPath() 可解析", pass: appPath?.exists === true, detail: appPath?.value ?? "", }, { id: "bundled", label: "asar 内资源可读", pass: bundled?.exists === true && bundled.bytes > 0 && bundled.preview.length > 0, detail: `${bundled?.bytes ?? 0} B`, }, { id: "user-data", label: "userData 可写(探针)", pass: user?.writable === true, detail: String(user?.writable ?? false), }, { id: "temp", label: "temp 可写(探针)", pass: temp?.writable === true, detail: String(temp?.writable ?? false), }, { id: "logs", label: "logs 目录存在且可写", pass: logs?.exists === true && logs.writable, detail: String(logs?.writable ?? false), }, { id: "extra", label: "extraResource 在 asar 外可读", pass: extra?.exists === true && !extra.insideAsar, detail: extra?.via ?? "", }, { id: "asar-flag", label: "asar 状态与打包态一致", pass: packaged === asar, detail: `packaged=${packaged} asar=${asar}`, }, { id: "readonly", label: "打包后应用目录只读", pass: packaged ? !flags.appRootWritable : true, detail: `writable=${flags.appRootWritable}`, }, { id: "bundled-asar", label: "打包后内资源位于 asar", pass: packaged ? bundled?.insideAsar === true : bundled?.insideAsar === false, detail: String(bundled?.insideAsar ?? false), }, { id: "containment", label: "资源路径落在 appPath/resourcesPath 内", pass: assets.every( (row) => row.resolved.startsWith(appRoot) || row.resolved.startsWith(process.resourcesPath), ), detail: `${assets.length} assets`, }, ]; } function snapshot(): Snapshot { const paths = inspectPaths(); const assets = inspectAssets(); const list = checks(paths, assets); const passed = list.filter((check) => check.pass).length; const asar = insideAsar(appRoot); return { platform: process.platform, electronVersion: process.versions.electron, nodeVersion: process.versions.node, isPackaged: app.isPackaged, asar, appPath: appRoot, resourcesPath: process.resourcesPath, paths, assets, checks: list, score: Math.round((passed / list.length) * 100), events: events.map((row) => ({ ...row })), }; } function resolvePreload(): string { const candidates = [ path.join(__dirname, "preload.cjs"), path.join(__dirname, "../preload/index.cjs"), path.join(__dirname, "preload.js"), ]; return ( candidates.find((candidate) => fsSync.existsSync(candidate)) ?? candidates[0] ?? "" ); } function createWindow(): BrowserWindow { const window = new BrowserWindow({ width: 1100, height: 860, show: false, title: "路径与资源实验室", backgroundColor: "#ffffff", webPreferences: { preload: resolvePreload(), contextIsolation: true, sandbox: true, nodeIntegration: false, webSecurity: true, allowRunningInsecureContent: false, experimentalFeatures: false, webviewTag: false, spellcheck: false, backgroundThrottling: true, }, }); const contents = window.webContents; contents.setWindowOpenHandler(() => ({ action: "deny" })); contents.on("will-navigate", (event, url) => { if ( !url.startsWith("file://") && !url.startsWith(MAIN_WINDOW_VITE_DEV_SERVER_URL ?? "") ) { event.preventDefault(); } }); contents.on("will-attach-webview", (event) => event.preventDefault()); window.once("ready-to-show", () => window.show()); contents.once("did-finish-load", () => { if (!window.isDestroyed() && !window.isVisible()) window.show(); log("ready", "路径与资源界面已加载"); }); if (MAIN_WINDOW_VITE_DEV_SERVER_URL) { void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL); } else { void window.loadFile( path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`), ); } win = window; return window; } function delay(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } async function evalRenderer( window: BrowserWindow, code: string, ): Promise { let lastCaught: unknown = null; for (let attempt = 0; attempt < 3; attempt += 1) { try { return (await window.webContents.executeJavaScript(code)) as T; } catch (caught) { lastCaught = caught; await delay(150); } } throw lastCaught instanceof Error ? lastCaught : new Error(String(lastCaught)); } async function waitForRenderer(window: BrowserWindow): Promise { for (let attempt = 0; attempt < 160; attempt += 1) { if (window.isDestroyed()) return; try { const ready = await evalRenderer( window, "typeof window.__demo === 'function'", ); if (ready) return; } catch { // 页面仍在加载。 } await delay(100); } throw new Error("renderer did not become ready"); } type DemoState = { score: number; checks: number; passed: number; isPackaged: boolean; asar: boolean; userWritable: boolean; tempWritable: boolean; appWritable: boolean; bundledBytes: number; extraBytes: number; extraVia: string; bundledInsideAsar: boolean; assets: number; }; async function runSmoke(window: BrowserWindow): Promise { try { await waitForRenderer(window); await delay(700); await waitForRenderer(window); const state = await evalRenderer(window, "window.__demo()"); process.stdout.write( `${JSON.stringify({ evt: "smoke", ok: state.score === 100 && state.checks === 10 && state.passed === 10 && state.userWritable && state.tempWritable && state.bundledBytes > 0 && state.extraBytes > 0 && state.extraVia.length > 0 && state.assets === 2 && (state.isPackaged ? state.asar && state.bundledInsideAsar && !state.appWritable : !state.asar && !state.bundledInsideAsar), ...state, })}\n`, ); app.quit(); } catch (caught) { process.stdout.write( `${JSON.stringify({ evt: "smoke", ok: false, message: String(caught) })}\n`, ); app.exit(1); } } async function capture( window: BrowserWindow, dir: string, file: string, ): Promise { const image = await window.webContents.capturePage(); if (image.isEmpty()) throw new Error(`empty capture: ${file}`); const png = image.toPNG(); fsSync.writeFileSync(path.join(dir, file), png); fsSync.writeFileSync(path.join(dir, "raw", file), png); } async function runShots(window: BrowserWindow): Promise { try { const dir = path.resolve( process.cwd(), "../../../docs/assets/images/50-paths-and-assets", ); fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true }); await waitForRenderer(window); await delay(700); await waitForRenderer(window); await evalRenderer(window, `window.__prepareShots("paths")`); await delay(250); await capture(window, dir, "50-01-paths.png"); await evalRenderer(window, `window.__prepareShots("layout")`); await delay(250); await capture(window, dir, "50-02-layout.png"); await evalRenderer(window, `window.__prepareShots("assets")`); await delay(250); await capture(window, dir, "50-03-assets.png"); app.quit(); } catch (caught) { process.stdout.write( `${JSON.stringify({ evt: "shots-error", message: String(caught) })}\n`, ); app.exit(1); } } ipcMain.handle(CH.snapshot, () => snapshot()); ipcMain.handle(CH.refresh, () => { log("refresh", "重新检查路径与资源"); return snapshot(); }); app.whenReady().then(() => { flags.userDataWritable = canWrite(userData); flags.tempWritable = canWrite(tempDir); flags.appRootWritable = canWrite(appRoot); log("paths", `appPath=${appRoot}`); const window = createWindow(); if (isSmoke) { void runSmoke(window); } else if (isShots) { void runShots(window); } app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } else { win?.show(); win?.focus(); } }); }); app.on("will-quit", () => { if (tempData) { try { fsSync.rmSync(tempData, { recursive: true, force: true }); } catch { // 清理失败不影响退出。 } } }); app.on("window-all-closed", () => { if (process.platform !== "darwin") app.quit(); });