示例工程 26-svelte5-runes

26-svelte5-runes/app/main/index.ts

typescript · 8.1 KB

import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import {
  assertExportReq,
  CH,
  type Level,
  type Source,
  type StreamBatch,
  type StreamEvent,
  type StreamStats,
} from "../shared/ipc";

app.setName("Svelte Stream 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(), `svelte-stream-smoke-${process.pid}`)
  : "";
if (smokeData) app.setPath("userData", smokeData);

const SOURCES: Source[] = ["build", "network", "tools"];
const BATCH_SIZE = 4;
const INTERVAL_MS = 80;

let timer: ReturnType<typeof setInterval> | null = null;
let emitted = 0;
let sequence = 0;

function nextEvent(): StreamEvent {
  sequence += 1;
  const source = SOURCES[sequence % SOURCES.length] ?? "build";
  const level: Level =
    sequence % 29 === 0 ? "error" : sequence % 11 === 0 ? "warn" : "info";
  return {
    id: sequence,
    ts: Date.now(),
    source,
    level,
    text: `事件 #${sequence} · ${source} · 耗时 ${12 + (sequence % 40)}ms`,
  };
}

function emitBatch(): void {
  const events = Array.from({ length: BATCH_SIZE }, () => nextEvent());
  emitted += events.length;
  const batch: StreamBatch = { events, emitted };
  for (const win of BrowserWindow.getAllWindows()) {
    if (!win.isDestroyed()) win.webContents.send(CH.batch, batch);
  }
}

function stats(): StreamStats {
  return { emitted, running: timer !== null };
}

function startStream(): void {
  if (timer !== null) return;
  timer = setInterval(emitBatch, INTERVAL_MS);
}

function stopStream(): StreamStats {
  if (timer !== null) {
    clearInterval(timer);
    timer = null;
  }
  return stats();
}

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: 1100,
    height: 820,
    show: false,
    title: "Svelte 5 事件流面板",
    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 = {
  svelteVersion: string;
  pausedBuffered: number;
  receivedAtPause: number;
  receivedAfterResume: number;
  received: number;
  emitted: number;
  buildOnly: boolean;
  exportLines: number;
  exportBytes: number;
  visibleRows: number;
  runesVisible: boolean;
  snapshotIsPlain: boolean;
};

async function runSmoke(): Promise<void> {
  try {
    const win = createWindow();
    await waitForRenderer(win);
    await delay(500);
    await waitForRenderer(win);
    const result = await evalRenderer<SmokeResult>(win, "window.__smoke()");
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          result.pausedBuffered > 0 &&
          result.receivedAfterResume >=
            result.receivedAtPause + result.pausedBuffered &&
          result.received === result.emitted &&
          result.buildOnly &&
          result.exportLines === result.received &&
          result.exportBytes > 0 &&
          result.visibleRows > 0 &&
          result.svelteVersion.startsWith("5.") &&
          result.runesVisible &&
          result.snapshotIsPlain,
        ...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: 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);
}

async function runShots(): Promise<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/26-svelte5-runes",
    );
    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()");
    await delay(700);
    await capture(win, dir, "26-01-live.png");
    await evalRenderer(win, "window.__pause()");
    await delay(600);
    await capture(win, dir, "26-02-paused.png");
    await evalRenderer(win, `window.__setTab("runes")`);
    await delay(350);
    await capture(win, dir, "26-03-runes.png");
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

ipcMain.handle(CH.start, () => {
  try {
    startStream();
    return { started: true };
  } catch {
    throw new Error("STREAM_START_FAILED");
  }
});

ipcMain.handle(CH.stop, () => {
  try {
    return stopStream();
  } catch {
    throw new Error("STREAM_STOP_FAILED");
  }
});

ipcMain.handle(CH.stats, () => {
  try {
    return stats();
  } catch {
    throw new Error("STREAM_STATS_FAILED");
  }
});

ipcMain.handle(CH.export, (_event, raw: unknown) => {
  try {
    assertExportReq(raw);
    const dir = path.join(app.getPath("userData"), "exports");
    fsSync.mkdirSync(dir, { recursive: true });
    const file = path.join(dir, `stream-${Date.now()}.jsonl`);
    const body = raw.events
      .map((event) =>
        JSON.stringify({
          id: event.id,
          ts: event.ts,
          source: event.source,
          level: event.level,
          text: event.text,
        }),
      )
      .join("\n");
    const content = `${body}\n`;
    fsSync.writeFileSync(file, content, "utf8");
    return {
      file: path.basename(file),
      lines: raw.events.length,
      bytes: Buffer.byteLength(content, "utf8"),
    };
  } catch {
    throw new Error("STREAM_EXPORT_FAILED");
  }
});

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", () => {
  stopStream();
  if (smokeData) {
    try {
      fsSync.rmSync(smokeData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

app.on("window-all-closed", () => {
  if (!isSmoke && !isShots && process.platform !== "darwin") app.quit();
});