示例工程 55-installers-and-channels

55-installers-and-channels/app/main/index.ts

typescript · 10 KB

import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { CH, type Check, type EventRow, type Snapshot } from "../shared/ipc";
import {
  CHANNELS,
  INSTALLERS,
  checksumName,
  recommend,
  releasePath,
  type Requirement,
} from "../shared/channels";

app.setName("Channels 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(), `chan55-${process.pid}`) : "";
if (tempData) app.setPath("userData", tempData);

let win: BrowserWindow | null = null;
let events: EventRow[] = [];

const scenarios: Array<{ id: string; label: string; req: Requirement }> = [
  {
    id: "personal",
    label: "个人 · 自动更新",
    req: { store: false, enterprise: false, autoUpdate: true, linux: false },
  },
  {
    id: "enterprise",
    label: "企业 · 安装器",
    req: { store: false, enterprise: true, autoUpdate: false, linux: false },
  },
  {
    id: "store-mac",
    label: "商店 · macOS",
    req: { store: true, enterprise: false, autoUpdate: false, linux: false },
  },
  {
    id: "store-linux",
    label: "商店 · Linux",
    req: { store: true, enterprise: false, autoUpdate: true, linux: 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("chan:event", { at: Date.now() });
  }
}

function checks(): Check[] {
  const storeIds = ["mas", "msstore", "flathub", "snap"];
  const storeChannels = CHANNELS.filter((row) => storeIds.includes(row.id));
  const direct = CHANNELS.filter((row) =>
    ["direct", "github"].includes(row.id),
  );
  const personal = recommend(scenarios[0]!.req);
  const enterprise = recommend(scenarios[1]!.req);
  const storeMac = recommend(scenarios[2]!.req);
  const storeLinux = recommend(scenarios[3]!.req);
  return [
    {
      id: "channels",
      label: "渠道矩阵 8 项",
      pass: CHANNELS.length === 8,
      detail: String(CHANNELS.length),
    },
    {
      id: "installers",
      label: "安装器行为 9 项",
      pass: INSTALLERS.length === 9,
      detail: String(INSTALLERS.length),
    },
    {
      id: "store",
      label: "商店渠道关闭应用内自更新",
      pass: storeChannels.every((row) => !row.inAppUpdate),
      detail: storeIds.join(","),
    },
    {
      id: "direct",
      label: "直下/Releases 支持应用内更新",
      pass: direct.every((row) => row.inAppUpdate),
      detail: direct.map((row) => row.id).join(","),
    },
    {
      id: "personal",
      label: "个人场景选直下",
      pass: personal.channel === "direct" && personal.artifact.includes("dmg"),
      detail: personal.artifact,
    },
    {
      id: "enterprise",
      label: "企业场景选安装器",
      pass:
        enterprise.channel === "direct" &&
        /msi|pkg|deb/.test(enterprise.artifact),
      detail: enterprise.artifact,
    },
    {
      id: "store-mac",
      label: "macOS 商店选 MAS",
      pass: storeMac.channel === "mas",
      detail: storeMac.channel,
    },
    {
      id: "store-linux",
      label: "Linux 商店选 Flathub",
      pass: storeLinux.channel === "flathub",
      detail: storeLinux.channel,
    },
    {
      id: "layout",
      label: "发布物路径与校验和命名一致",
      pass:
        releasePath("macos", "arm64", "App.dmg") ===
          "releases/macos/arm64/App.dmg" &&
        checksumName("App.dmg") === "App.dmg.sha256",
      detail: releasePath("macos", "arm64", "App.dmg"),
    },
    {
      id: "residue",
      label: "每个安装器都记录卸载与残留",
      pass: INSTALLERS.every(
        (row) => row.uninstall.length > 0 && row.residue.length > 0,
      ),
      detail: `${INSTALLERS.length} rows`,
    },
  ];
}

function snapshot(): Snapshot {
  const list = checks();
  const passed = list.filter((check) => check.pass).length;
  return {
    platform: process.platform,
    electronVersion: process.versions.electron,
    nodeVersion: process.versions.node,
    channels: CHANNELS.map((row) => ({ ...row })),
    installers: INSTALLERS.map((row) => ({ ...row })),
    decisions: scenarios.map((scenario) => ({
      id: scenario.id,
      label: scenario.label,
      result: recommend(scenario.req),
    })),
    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://")) 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<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function evalRenderer<T>(
  window: BrowserWindow,
  code: string,
): Promise<T> {
  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<void> {
  for (let attempt = 0; attempt < 160; attempt += 1) {
    if (window.isDestroyed()) return;
    try {
      const ready = await evalRenderer<boolean>(
        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;
  channels: number;
  installers: number;
  storeOff: boolean;
  directOn: boolean;
  enterpriseArtifact: string;
  personalChannel: string;
  storeMac: string;
  storeLinux: string;
  decisions: number;
};

async function runSmoke(window: BrowserWindow): Promise<void> {
  try {
    await waitForRenderer(window);
    await delay(600);
    await waitForRenderer(window);
    const state = await evalRenderer<DemoState>(window, "window.__demo()");
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          state.score === 100 &&
          state.checks === 10 &&
          state.passed === 10 &&
          state.channels === 8 &&
          state.installers === 9 &&
          state.storeOff &&
          state.directOn &&
          /msi|pkg|deb/.test(state.enterpriseArtifact) &&
          state.personalChannel === "direct" &&
          state.storeMac === "mas" &&
          state.storeLinux === "flathub" &&
          state.decisions === 4,
        ...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<void> {
  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<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/55-installers-and-channels",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(window);
    await delay(600);
    await waitForRenderer(window);
    await evalRenderer(window, `window.__prepareShots("channels")`);
    await delay(250);
    await capture(window, dir, "55-01-channels.png");
    await evalRenderer(window, `window.__prepareShots("installers")`);
    await delay(250);
    await capture(window, dir, "55-02-installers.png");
    await evalRenderer(window, `window.__prepareShots("decisions")`);
    await delay(250);
    await capture(window, dir, "55-03-decisions.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(() => {
  log("load", `${CHANNELS.length} 渠道 / ${INSTALLERS.length} 安装器`);
  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();
});