Files
bunext/dist/commands/start/index.js
T
2026-10-02 07:04:22 +01:00

68 lines
2.2 KiB
JavaScript

import { Command } from "commander";
import path from "path";
import writeErrorFile from "../../functions/write-error-file";
import grabDirNames from "../../utils/grab-dir-names";
import { existsSync, rmSync } from "fs";
const { BUNX_BUNDLER_ERROR_EXIT_FILE } = grabDirNames();
let retries = 0;
let timeout;
const MAX_RETRIES = 5;
export default function () {
return new Command("start")
.description("Start production server")
.action(async () => {
// A stale error file from a previous session makes the bundler
// run in "silent" mode and pages fail with misleading messages.
rmSync(BUNX_BUNDLER_ERROR_EXIT_FILE, { force: true });
await start();
});
}
async function start() {
clearTimeout(timeout);
if (retries >= MAX_RETRIES) {
console.error(`Production server crashed ${MAX_RETRIES} times. Exiting.`);
process.exit(1);
}
const prod_spawn_file = path.resolve(__dirname, "prod-spawn.ts");
const prod_spawn_js_file = path.resolve(__dirname, "prod-spawn.js");
const final_spawn_file = existsSync(prod_spawn_js_file)
? prod_spawn_js_file
: prod_spawn_file;
const spawn_options = {
cmd: ["bun", final_spawn_file],
stdio: ["inherit", "inherit", "inherit"],
onExit(subprocess, exitCode, signalCode, error) {
writeErrorFile({ exitCode, error });
},
env: {
...process.env,
NODE_ENV: "production",
},
};
let dev_process;
try {
dev_process = Bun.spawn(spawn_options);
}
catch (error) {
console.error(`Failed to start production process:`, error);
retries++;
timeout = setTimeout(() => {
retries = 0;
}, 10000);
return await start();
}
const exited = await dev_process.exited;
// Restart on any numeric exit (0 included). A null exit means the child
// was killed by a signal, which we must not restart.
if (exited != null) {
retries++;
timeout = setTimeout(() => {
retries = 0;
}, 10000);
return await start();
}
timeout = setTimeout(() => {
retries = 0;
}, 10000);
}