import { forwardAndroidApi } from "./android-api.mjs"; import { spawn } from "node:child_process"; import { fileURLToPath } from "node:url"; import path from "node:path"; const rootUrl = new URL("../", import.meta.url); const root = fileURLToPath(rootUrl); const projectId = [...rootUrl.pathname] .reduce( (hash, character) => Math.imul(hash ^ character.charCodeAt(0), 16777619) >>> 0, 2166136261, ) .toString(16); /** Reuse only this project's reachable Vite instance; never terminate an existing server. */ export async function ensureDevServer({ host = process.env.TAURI_DEV_HOST || "127.0.0.1", port = 5173, } = {}) { const hostname = host.includes(":") ? `[${host}]` : host; const address = `http://${hostname}:${port}`; async function inspect() { let response; try { response = await fetch(`${address}/__altitude_dev_server`, { signal: AbortSignal.timeout(2000), }); } catch (error) { if (error.cause?.code === "ECONNREFUSED") return false; throw new Error( `Could not check the development server at ${address}: ${error.message}`, ); } const info = await response.json().catch(() => null); if ( !response.ok || info?.app !== "altitude" || info?.projectId !== projectId ) { throw new Error( `Port ${port} at ${host} is occupied by another server. Stop that server before starting Altitude.`, ); } if (info.hmrHost && info.hmrHost !== host) { throw new Error( `The existing Altitude server uses hot reload at ${info.hmrHost}. Restart it for ${host}.`, ); } return true; } if (await inspect()) { console.log(`Reusing Altitude development server at ${address}`); return; } const child = spawn( process.execPath, [ path.join(root, "node_modules/vite/bin/vite.js"), "--host", host, "--port", String(port), ], { cwd: root, env: { ...process.env, ...(host !== "127.0.0.1" ? { TAURI_DEV_HOST: host } : {}), }, stdio: "inherit", }, ); let stopping = false; const stop = (signal) => { stopping = true; child.kill(signal); }; const interrupt = () => stop("SIGINT"); const terminate = () => stop("SIGTERM"); process.once("SIGINT", interrupt); process.once("SIGTERM", terminate); try { await new Promise((resolve, reject) => { child.once("error", reject); child.once("exit", (code, signal) => { if ( stopping || code === 0 || signal === "SIGINT" || signal === "SIGTERM" ) resolve(); else reject(new Error(`Vite exited with code ${code ?? signal}.`)); }); }); } finally { process.removeListener("SIGINT", interrupt); process.removeListener("SIGTERM", terminate); } } if ( process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) ) { Promise.resolve() .then(() => { forwardAndroidApi(); return ensureDevServer(); }) .catch((error) => { console.error(error.message); process.exitCode = 1; }); }