Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

6.2 KB
Raw Blame
// Real macOS WebView coverage for URL restoration and persistent login data.
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import { once } from "node:events";

if (process.platform !== "darwin") {
  throw new Error("This native URL restoration fixture requires macOS.");
}
const repo = process.cwd();
const root = await fs.mkdtemp(path.join(os.tmpdir(), "pake-last-url-"));
const identifier = `com.pake.last-url-probe-${process.pid}`;
const dataDir = path.join(
  os.homedir(),
  "Library/Application Support",
  identifier,
);
const lastUrl = path.join(dataDir, "last-url.txt");
const reports = [];
let phase = "seed";
let app;
const server = http.createServer(async (request, response) => {
  if (request.url === "/report") {
    let body = "";
    for await (const chunk of request) body += chunk;
    reports.push(JSON.parse(body));
    response.end("ok");
    return;
  }
  response.setHeader("Content-Type", "text/html");
  response.end(`<!doctype html><title>Pake URL restoration probe</title><script>
    (async () => {
      const phase = ${JSON.stringify(phase)};
      if (phase === "seed" && location.pathname === "/") {
        localStorage.setItem("session", "retained");
        document.cookie = "session=retained; Max-Age=3600; Path=/";
        location.href = "/task";
        return;
      }
      if (phase === "disabled" && location.pathname === "/") {
        await fetch("/report", {method:"POST", body:JSON.stringify({
          phase, path:location.pathname, storage:localStorage.getItem("session"),
          cookie:document.cookie
        })});
        location.href = "/other";
        return;
      }
      await fetch("/report", {method:"POST", body:JSON.stringify({
        phase, path:location.pathname, storage:localStorage.getItem("session"),
        cookie:document.cookie
      })});
      await new Promise(resolve => setTimeout(resolve, 300));
      await window.__PAKE_NATIVE__.core.invoke("plugin:window|close", {label:"pake"});
    })();
  </script>`);
});
server.listen(0, "127.0.0.1");
await once(server, "listening");
const origin = `http://127.0.0.1:${server.address().port}`;

try {
  const fixture = path.join(root, "fixture");
  await fs.mkdir(fixture);
  await fs.cp(path.join(repo, "src-tauri"), path.join(fixture, "src-tauri"), {
    recursive: true,
    filter: (file) => {
      const relative = path.relative(path.join(repo, "src-tauri"), file);
      return (
        !["target", ".pake", "gen", ".cargo"].includes(
          relative.split(path.sep)[0],
        ) && !relative.startsWith(path.join("permissions", "autogenerated"))
      );
    },
  });
  await fs.copyFile(
    path.join(repo, "rust-toolchain.toml"),
    path.join(fixture, "rust-toolchain.toml"),
  );
  await fs.mkdir(path.join(fixture, "dist"));
  await fs.writeFile(path.join(fixture, "dist/index.html"), "URL fixture");
  const log = await fs.open(path.join(root, "build.log"), "w");
  console.log("Building native URL restoration fixture...");
  const compiler = spawn(
    "cargo",
    ["build", "--locked", "--features", "runtime-template"],
    {
      cwd: path.join(fixture, "src-tauri"),
      env: {
        ...process.env,
        CARGO_TARGET_DIR: path.join(repo, "src-tauri/target"),
      },
      stdio: ["ignore", log.fd, log.fd],
    },
  );
  const [code] = await once(compiler, "exit");
  await log.close();
  if (code !== 0) {
    console.error(await fs.readFile(path.join(root, "build.log"), "utf8"));
    throw new Error(`Native fixture build failed with exit code ${code}`);
  }

  const contents = path.join(root, "Probe.app/Contents");
  const executable = path.join(contents, "MacOS/pake");
  const runtime = path.join(contents, "Resources/pake-runtime");
  await fs.mkdir(path.dirname(executable), { recursive: true });
  await fs.mkdir(runtime, { recursive: true });
  await fs.copyFile(path.join(repo, "src-tauri/target/debug/pake"), executable);
  await fs.chmod(executable, 0o755);
  await fs.writeFile(
    path.join(runtime, "app.json"),
    JSON.stringify({ identifier, productName: "PakeUrlProbe" }),
  );
  const config = JSON.parse(
    await fs.readFile(path.join(repo, "src-tauri/pake.json")),
  );
  config.windows[0].url = origin + "/";
  config.windows[0].hide_on_close = false;
  config.system_tray.macos = false;
  const run = async (nextPhase, enabled) => {
    phase = nextPhase;
    if (enabled === undefined) delete config.windows[0].restore_last_url;
    else config.windows[0].restore_last_url = enabled;
    await fs.writeFile(path.join(runtime, "pake.json"), JSON.stringify(config));
    app = spawn(executable, [], { stdio: "ignore" });
    const timer = setTimeout(() => app.kill("SIGKILL"), 45_000);
    const [exitCode] = await once(app, "exit");
    clearTimeout(timer);
    assert.equal(exitCode, 0, `native app failed during ${phase}`);
  };

  await run("seed", undefined);
  assert.equal(await fs.readFile(lastUrl, "utf8"), origin + "/task");
  await run("restored", true);
  assert.equal(reports.find((r) => r.phase === "restored")?.path, "/task");
  const saved = await fs.readFile(lastUrl, "utf8");
  await run("disabled", false);
  await run("disabled-relaunch", false);
  assert.equal(
    await fs.readFile(lastUrl, "utf8"),
    saved,
    "opt-out must not save a new URL",
  );
  assert.deepEqual(
    reports.filter((r) => r.phase === "disabled").map((r) => r.path),
    ["/", "/other"],
  );
  assert.equal(reports.find((r) => r.phase === "disabled-relaunch")?.path, "/");
  for (const report of reports) {
    assert.equal(report.storage, "retained", `${report.phase}: local storage`);
    assert.match(
      report.cookie,
      /(?:^|; )session=retained(?:;|$)/,
      `${report.phase}: cookie`,
    );
  }
  console.log(
    "Native URL restoration passed: legacy/default restore, opt-out launch and save, persistent cookies and local storage.",
  );
} finally {
  if (app && app.exitCode === null && app.signalCode === null) {
    const exited = once(app, "exit");
    app.kill("SIGKILL");
    await exited;
  }
  server.close();
  await fs.rm(dataDir, { recursive: true, force: true });
  console.log(`Native fixture and build log: ${root}`);
}