示例工程 28-project-approval-panel

28-project-approval-panel/app/.tsc/main/index.js

javascript · 8.6 KB

import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { assertDecideReq, assertRequestReq, CH, } from "../shared/ipc";
app.setName("Approval Panel");
const isSmoke = process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const smokeData = isSmoke
    ? path.join(os.tmpdir(), `approval-panel-smoke-${process.pid}`)
    : "";
if (smokeData)
    app.setPath("userData", smokeData);
let sequence = 0;
let pending = [];
let history = [];
let policies = [];
const timers = new Map();
function state() {
    return {
        pending: [...pending],
        history: [...history],
        policies: [...policies],
        now: Date.now(),
    };
}
function broadcast() {
    const snapshot = state();
    for (const win of BrowserWindow.getAllWindows()) {
        if (!win.isDestroyed())
            win.webContents.send(CH.changed, snapshot);
    }
}
function record(request, outcome, auto) {
    history = [
        {
            id: request.id,
            tool: request.tool,
            risk: request.risk,
            outcome,
            at: Date.now(),
            auto,
        },
        ...history,
    ].slice(0, 50);
}
function expire(id) {
    const request = pending.find((item) => item.id === id);
    if (!request)
        return;
    pending = pending.filter((item) => item.id !== id);
    timers.delete(id);
    record(request, "expired", false);
    broadcast();
}
function enqueue(input) {
    if (policies.includes(input.tool)) {
        record({
            id: `auto-${++sequence}`,
            tool: input.tool,
            risk: input.risk,
            detail: input.detail,
            createdAt: Date.now(),
            expiresAt: Date.now(),
        }, "allow", true);
        broadcast();
        return state();
    }
    const request = {
        id: `req-${++sequence}`,
        tool: input.tool,
        risk: input.risk,
        detail: input.detail,
        createdAt: Date.now(),
        expiresAt: Date.now() + input.ttlMs,
    };
    pending = [...pending, request].slice(-20);
    const timer = setTimeout(() => expire(request.id), input.ttlMs);
    timers.set(request.id, timer);
    broadcast();
    return state();
}
function decide(id, decision) {
    const request = pending.find((item) => item.id === id);
    if (!request)
        return state();
    const timer = timers.get(id);
    if (timer)
        clearTimeout(timer);
    timers.delete(id);
    pending = pending.filter((item) => item.id !== id);
    if (decision === "always") {
        policies = [...new Set([...policies, request.tool])];
    }
    record(request, decision, false);
    broadcast();
    return state();
}
function reset() {
    for (const timer of timers.values())
        clearTimeout(timer);
    timers.clear();
    pending = [];
    history = [];
    policies = [];
    broadcast();
    return state();
}
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: 820,
        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 < 160; 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.allowOutcome === "allow" &&
                result.alwaysPolicy &&
                result.autoApproved &&
                result.expiredSeen &&
                result.keyboardOutcome === "allow" &&
                result.viewsMatch &&
                result.finalHistory >= 4 &&
                result.reactVersion.startsWith("19.") &&
                result.vueVersion.startsWith("3.") &&
                result.svelteVersion.startsWith("5."),
            ...result,
        })}\n`);
        app.quit();
    }
    catch (error) {
        process.stdout.write(`${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`);
        app.exit(1);
    }
}
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/28-project-approval-panel");
        fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
        const win = createWindow();
        await waitForRenderer(win);
        await delay(500);
        await waitForRenderer(win);
        await evalRenderer(win, `window.__prepareShots("react")`);
        await delay(500);
        await capture(win, dir, "28-01-react.png");
        await evalRenderer(win, `window.__prepareShots("vue")`);
        await delay(500);
        await capture(win, dir, "28-02-vue.png");
        await evalRenderer(win, `window.__prepareShots("svelte")`);
        await delay(500);
        await capture(win, dir, "28-03-svelte.png");
        app.quit();
    }
    catch (error) {
        process.stdout.write(`${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`);
        app.exit(1);
    }
}
ipcMain.handle(CH.get, () => state());
ipcMain.handle(CH.decide, (_event, raw) => {
    try {
        assertDecideReq(raw);
        return decide(raw.id, raw.decision);
    }
    catch {
        throw new Error("APPROVAL_DECIDE_FAILED");
    }
});
ipcMain.handle(CH.request, (_event, raw) => {
    try {
        assertRequestReq(raw);
        return enqueue(raw);
    }
    catch {
        throw new Error("APPROVAL_REQUEST_FAILED");
    }
});
ipcMain.handle(CH.reset, () => reset());
const ticker = setInterval(() => {
    if (pending.length > 0)
        broadcast();
}, 250);
app.whenReady().then(() => {
    if (isSmoke) {
        void runSmoke();
    }
    else if (isShots) {
        void runShots();
    }
    else {
        createWindow();
    }
    app.on("activate", () => {
        if (BrowserWindow.getAllWindows().length === 0)
            createWindow();
    });
});
app.on("will-quit", () => {
    clearInterval(ticker);
    for (const timer of timers.values())
        clearTimeout(timer);
    timers.clear();
    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