示例工程 11-main-process-services
11-main-process-services/app/main/index.ts
import { app, BrowserWindow } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { registerIpc } from "./ipc";
import { createServices } from "./services";
import { ServiceError, toPublicError } from "../shared/ipc";
app.setName("Service Workbench");
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(), `service-workbench-smoke-${process.pid}`)
: "";
if (smokeData) app.setPath("userData", smokeData);
let logFile = "";
let requestSeq = 0;
function writeLog(level: string, evt: string, msg?: string): void {
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(): 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 win = new BrowserWindow({
width: 1000,
height: 720,
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: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function evalRenderer<T>(win: BrowserWindow, code: string): Promise<T> {
let lastError: unknown = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return (await win.webContents.executeJavaScript(code)) as T;
} catch (error) {
lastError = error;
await delay(200);
}
}
throw lastError instanceof Error ? lastError : new Error(String(lastError));
}
async function waitForRenderer(win: BrowserWindow): Promise<void> {
for (let attempt = 0; attempt < 120; attempt += 1) {
if (win.isDestroyed()) return;
try {
const ready = await evalRenderer<boolean>(
win,
"typeof window.__smoke === 'function'",
);
if (ready) return;
} catch {
// 页面仍在加载。
}
await delay(100);
}
throw new Error("renderer did not become ready");
}
type SmokeResult = {
notes: number;
readBytes: number;
badId: string;
allowed: boolean;
blocked: string;
picked: string;
};
async function runSmoke(): Promise<void> {
try {
const win = createWindow();
await waitForRenderer(win);
await delay(700);
await waitForRenderer(win);
const result = await evalRenderer<SmokeResult>(win, "window.__smoke()");
process.stdout.write(
`${JSON.stringify({
evt: "smoke",
ok:
result.notes >= 2 &&
result.readBytes > 0 &&
result.badId === "BAD_ID" &&
result.allowed &&
result.blocked === "URL_NOT_ALLOWED" &&
result.picked === "welcome.md",
...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: BrowserWindow, tab: string): Promise<void> {
await evalRenderer(
win,
`window.__setTab && window.__setTab(${JSON.stringify(tab)})`,
);
}
async function capture(
win: BrowserWindow,
dir: string,
file: string,
): Promise<void> {
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);
writeLog("debug", "shot", file);
}
async function runShots(): Promise<void> {
try {
const dir = path.resolve(
process.cwd(),
"../../../docs/assets/images/11-main-process-services",
);
fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
const win = createWindow();
await waitForRenderer(win);
await delay(700);
await waitForRenderer(win);
await evalRenderer(win, "window.__smoke()");
await delay(350);
await setTab(win, "catalog");
await delay(250);
await capture(win, dir, "11-01-catalog.png");
await setTab(win, "notes");
await delay(250);
await capture(win, dir, "11-02-notes.png");
await setTab(win, "shell");
await delay(250);
await capture(win, dir, "11-03-shell-dialog.png");
app.quit();
} catch (error) {
writeLog("error", "shots-failed", String(error));
app.exit(1);
}
}
function runDiagnostics(): void {
try {
throw new ServiceError("BAD_ID", "非法的笔记 id", "id");
} catch (error) {
const value = error as 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`,
);
}
app.exit(0);
}
app.whenReady().then(() => {
if (isDiagnostics) {
runDiagnostics();
return;
}
const dir = path.join(app.getPath("userData"), "notes");
const services = createServices({ dir, dryRun: isSmoke || isShots });
registerIpc(services, {
nextRequestId: () => {
requestSeq += 1;
return `req-${requestSeq}-${Date.now().toString(36)}`;
},
log: (evt, msg) => writeLog("info", evt, msg),
});
logFile = path.join(app.getPath("logs"), "services.log");
try {
fsSync.mkdirSync(path.dirname(logFile), { recursive: true });
} catch {
// 目录不可写时退化为只写 stdout。
}
writeLog("info", "app-ready", `${app.getVersion()} dir=${dir}`);
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();
});