示例工程 13-project-file-explorer
13-project-file-explorer/app/.tsc/main/index.js
import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { CH, parsePathReq, parseSaveReq, toPublicError, } from "../shared/ipc";
import { createWorkspaceService } from "./services/workspace-service";
app.setName("File Explorer");
const isSmoke = process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const isDiagnostics = process.argv.includes("--diagnostics");
const smokeData = isSmoke
? path.join(os.tmpdir(), `file-explorer-smoke-${process.pid}`)
: "";
if (smokeData)
app.setPath("userData", smokeData);
let logFile = "";
let requestSeq = 0;
function writeLog(level, evt, msg) {
const line = JSON.stringify({
at: Date.now(),
level,
evt,
...(msg ? { msg } : {}),
});
process.stdout.write(`${line}\n`);
if (!logFile)
return;
try {
fsSync.appendFileSync(logFile, `${line}\n`);
}
catch {
// 日志失败不影响文件浏览。
}
}
function resolvePreload() {
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() {
const win = new BrowserWindow({
width: 1100,
height: 760,
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,
},
});
win.once("ready-to-show", () => {
if (!win.isDestroyed())
win.show();
});
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
void win.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
}
else {
void win.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));
}
return win;
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function evalRenderer(win, code) {
let lastError = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return (await win.webContents.executeJavaScript(code));
}
catch (error) {
lastError = error;
await delay(200);
}
}
throw lastError instanceof Error ? lastError : new Error(String(lastError));
}
async function waitForRenderer(win) {
for (let attempt = 0; attempt < 120; attempt += 1) {
if (win.isDestroyed())
return;
try {
const ready = await evalRenderer(win, "typeof window.__smoke === 'function'");
if (ready)
return;
}
catch {
// 页面仍在加载。
}
await delay(100);
}
throw new Error("renderer did not become ready");
}
async function runSmoke() {
try {
const win = createWindow();
await waitForRenderer(win);
await delay(500);
await waitForRenderer(win);
const result = await evalRenderer(win, "window.__smoke()");
process.stdout.write(`${JSON.stringify({
evt: "smoke",
ok: result.entries >= 6 &&
result.readBytes > 0 &&
result.saved &&
result.traversal === "PATH_OUTSIDE_WORKSPACE" &&
result.absolute === "PATH_OUTSIDE_WORKSPACE" &&
result.symlink === "PATH_OUTSIDE_WORKSPACE",
...result,
})}\n`);
app.quit();
}
catch (error) {
process.stdout.write(`${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`);
app.exit(1);
}
}
async function setTab(win, tab) {
await evalRenderer(win, `window.__setTab && window.__setTab(${JSON.stringify(tab)})`);
}
async function capture(win, dir, file) {
const image = await win.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() {
try {
const dir = path.resolve(process.cwd(), "../../../docs/assets/images/13-project-file-explorer");
fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
const win = createWindow();
await waitForRenderer(win);
await delay(500);
await waitForRenderer(win);
await evalRenderer(win, "window.__smoke()");
await delay(300);
await setTab(win, "browser");
await delay(250);
await capture(win, dir, "13-01-tree.png");
await evalRenderer(win, "window.__demoSave()");
await delay(250);
await capture(win, dir, "13-02-save.png");
await setTab(win, "security");
await delay(250);
await capture(win, dir, "13-03-blocked.png");
app.quit();
}
catch (error) {
process.stdout.write(`${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`);
app.exit(1);
}
}
function requestId() {
requestSeq += 1;
return `req-${requestSeq}-${Date.now().toString(36)}`;
}
const root = path.join(app.getPath("userData"), "workspace");
const workspace = createWorkspaceService({ root });
function handle(channel, run) {
ipcMain.handle(channel, async (_event, raw) => {
const id = requestId();
try {
const value = await run(raw);
writeLog("info", "ipc-ok", `${channel} ${id}`);
return { ok: true, value, requestId: id };
}
catch (error) {
writeLog("warn", "ipc-error", `${channel} ${id}`);
return { ok: false, error: toPublicError(error, id) };
}
});
}
handle(CH.tree, () => workspace.tree());
handle(CH.read, (raw) => {
const req = parsePathReq(raw);
return workspace.read(req.path);
});
handle(CH.save, (raw) => {
const req = parseSaveReq(raw);
return workspace.save(req.path, req.content);
});
handle(CH.reset, async () => {
await workspace.reset();
return null;
});
async function runDiagnostics() {
const dir = path.join(os.tmpdir(), `explorer-diag-${process.pid}`);
const service = createWorkspaceService({ root: dir });
await service.ensure();
try {
await service.read("escape-link.md");
}
catch (error) {
const value = error;
process.stdout.write(`${JSON.stringify({
evt: "diagnostics",
name: value.name,
message: value.message,
stack: String(value.stack ?? "")
.split("\n")
.slice(0, 3),
public: toPublicError(error, "req-diag-1"),
})}\n`);
}
fsSync.rmSync(dir, { recursive: true, force: true });
app.exit(0);
}
app.whenReady().then(async () => {
if (isDiagnostics) {
await runDiagnostics();
return;
}
logFile = path.join(app.getPath("logs"), "explorer.log");
try {
fsSync.mkdirSync(path.dirname(logFile), { recursive: true });
}
catch {
// 目录不可写时退化为只写 stdout。
}
await workspace.ensure();
writeLog("info", "app-ready", `${app.getVersion()} root=${root}`);
if (isSmoke) {
void runSmoke();
}
else if (isShots) {
void runShots();
}
else {
createWindow();
}
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0)
createWindow();
});
});
app.on("will-quit", () => {
if (smokeData) {
try {
fsSync.rmSync(smokeData, { recursive: true, force: true });
}
catch {
// 清理失败不影响退出。
}
}
});
app.on("window-all-closed", () => {
if (!isSmoke && !isShots && process.platform !== "darwin")
app.quit();
});
//# sourceMappingURL=index.js.map