import { execa } from "execa"; import { watch } from "chokidar"; import { buildDev } from "./code-gen/esbuild"; import type { BuildContext } from "esbuild"; import { findUpSync } from "find-up"; import { getResocketDir } from "./code-gen/getAssets"; import { getWorkerFilePath } from "./utils"; import { getResocketConfig } from "./config"; export interface DevCliOverrides { config?: string; configOverrides: { port?: number; }; } export const resocketDev = async (overrides: DevCliOverrides) => { const workerdir = getResocketDir(); const config = getResocketConfig(overrides); const workerFilePath = getWorkerFilePath(overrides.config, config); let ctx: BuildContext; //build will build and watch both ctx = await buildDev(workerFilePath, { ...config, ...overrides.configOverrides, }); //run shell const childProcess = execa( `wrangler dev ${workerdir}/gen/worker.js -c ${workerdir}/gen/wrangler.toml`, { stdio: "inherit" } ); const envFilesToWatch = []; const envFilePath = findUpSync(".env"); const envLocalFilePath = findUpSync(".env.local"); if (envFilePath) envFilesToWatch.push(envFilePath); if (envLocalFilePath) envFilesToWatch.push(envLocalFilePath); //watch is for resocket.json changes. //? do we also want to listen for changes to the package.json? const watcher = watch( [ findUpSync("resocket.json")!, findUpSync("package.json")!, ...envFilesToWatch, ], { ignoreInitial: true, } ); watcher.on("all", async () => { try { //manually rebuild on config & package.json changes await ctx.rebuild(); //read the latest const resocketConfig = getResocketConfig(overrides); //this will build the toml ctx = await buildDev( getWorkerFilePath(overrides.config, resocketConfig), resocketConfig ); } catch (error) { console.error(error); } }); childProcess .then((c) => { console.log(`complete `, c); }) .catch((e) => { console.log(`error `, e); }) .finally(async () => { watcher.close(); ctx.dispose(); }); };