From 89f3ecdd392c37e8e6f7275fd37a83220bde2fc4 Mon Sep 17 00:00:00 2001 From: Izan Gil <66965250+SrIzan10@users.noreply.github.com> Date: Wed, 29 Jan 2025 21:46:09 +0100 Subject: [PATCH 1/6] feat: watch command execute on successful build --- src/commands/build.ts | 66 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 60 insertions(+), 6 deletions(-) diff --git a/src/commands/build.ts b/src/commands/build.ts index 26b5c65..6485f26 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -7,10 +7,11 @@ import assert from 'node:assert'; import defaultEsbuild from '../utilities/defaultEsbuildConfig'; import { require } from '../utilities/require'; import { pathExists, pathExistsSync } from 'find-up'; -import { mkdir, writeFile, readFile } from 'fs/promises'; +import { mkdir, writeFile } from 'fs/promises'; import * as Preprocessor from '../utilities/preprocessor'; import { bold, magentaBright } from 'colorette'; import { parseTsConfig } from '../utilities/parseTsconfig'; +import { execa, type ExecaChildProcess } from 'execa'; const VALID_EXTENSIONS = ['.ts', '.js' ]; @@ -48,7 +49,12 @@ type BuildOptions = { * flag: default false */ sourcemap?: boolean; - + /** + * command to run. + * defaults to your package + * manager's start command. + */ + watchCommand?: string; }; const CommandHandlerPlugin = (buildConfig: Partial, ambientFilePath: string, sernTsConfigPath: string) => { @@ -58,18 +64,63 @@ const CommandHandlerPlugin = (buildConfig: Partial, ambientFilePat const options = build.initialOptions const defVersion = () => JSON.stringify(require(p.resolve('package.json')).version); + // for some reason it errored out, should fix it options.define = { - ...buildConfig.define ?? {}, + ...(buildConfig.define ?? {}), __DEV__: `${buildConfig.mode === 'development'}`, __PROD__: `${buildConfig.mode === 'production'}`, __VERSION__: `${buildConfig.defineVersion ? `${defVersion()}` : 'undefined'}` - } ?? {} + } Preprocessor.writeTsConfig(buildConfig.format!, sernTsConfigPath, writeFile); Preprocessor.writeAmbientFile(ambientFilePath, options.define!, writeFile); } } as esbuild.Plugin } +const CommandOnEndPlugin = (watching: boolean, watchCommand?: string) => { + // for some reason it runs the command twice on first build + let isFirstBuild = true; + let currentProcess: ExecaChildProcess | null = null; + + return { + name: 'command-on-end', + setup(build: esbuild.PluginBuild) { + build.onEnd((result) => { + if (!watching || result.errors.length !== 0) return; + if (isFirstBuild) { + isFirstBuild = false; + return; + } + if (watchCommand === '') { + console.log('[watch] no command provided, skipping'); + return; + } + + if (currentProcess) { + console.log('[watch] stopping previous process...'); + currentProcess.cancel() + currentProcess = null; + } + + const cmd = watchCommand || (() => { + if (pathExistsSync('package-lock.json')) return 'npm start'; + if (pathExistsSync('yarn.lock')) return 'yarn start'; + if (pathExistsSync('pnpm-lock.yaml')) return 'pnpm start'; + if (pathExistsSync('bun.lockb')) return 'bun run start'; + throw new Error('[watch] no package manager lockfile found, cannot run default command'); + })(); + + console.log(`[watch] running command: ${cmd}`); + + currentProcess = execa(cmd, { stdio: 'inherit', shell: true }); + currentProcess.catch(error => { + if (error.isCanceled) return; + console.error(`[watch] Command execution error: ${error.message}`); + }); + }); + } + } as esbuild.Plugin; +}; const resolveBuildConfig = (path: string|undefined, language: string) => { if(language === 'javascript') { return path ?? 'jsconfig.json' @@ -146,14 +197,17 @@ export async function build(options: Record) { //https://esbuild.github.io/content-types/#tsconfig-json const ctx = await esbuild.context({ entryPoints, - plugins: [CommandHandlerPlugin(buildConfig, ambientFilePath, sernTsConfigPath)], + plugins: [ + CommandHandlerPlugin(buildConfig, ambientFilePath, sernTsConfigPath), + CommandOnEndPlugin(options.watch, buildConfig.watchCommand) + ], sourcemap: buildConfig.sourcemap, ...defaultEsbuild(buildConfig.format!, buildConfig.tsconfig), dropLabels: [buildConfig.mode === 'production' ? '__DEV__' : '__PROD__', ...buildConfig.dropLabels!], }); await ctx.rebuild() - if(options.watch) { + if (options.watch) { await ctx.watch() } else { await ctx.dispose() From fba0f59ab8163986bfb4baec21bc3cd41f349374 Mon Sep 17 00:00:00 2001 From: Izan Gil <66965250+SrIzan10@users.noreply.github.com> Date: Wed, 29 Jan 2025 21:50:00 +0100 Subject: [PATCH 2/6] chore: clarify comment --- src/commands/build.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/build.ts b/src/commands/build.ts index 6485f26..e255f9e 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -64,7 +64,7 @@ const CommandHandlerPlugin = (buildConfig: Partial, ambientFilePat const options = build.initialOptions const defVersion = () => JSON.stringify(require(p.resolve('package.json')).version); - // for some reason it errored out, should fix it + // should fix a type error options.define = { ...(buildConfig.define ?? {}), __DEV__: `${buildConfig.mode === 'development'}`, From ac8a09b3ba674f44950b39e68b3f46ecfd2fedbe Mon Sep 17 00:00:00 2001 From: Izan Gil <66965250+SrIzan10@users.noreply.github.com> Date: Wed, 29 Jan 2025 21:52:45 +0100 Subject: [PATCH 3/6] chore: respect casing --- src/commands/build.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/commands/build.ts b/src/commands/build.ts index e255f9e..c324c6c 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -83,7 +83,7 @@ const CommandOnEndPlugin = (watching: boolean, watchCommand?: string) => { let currentProcess: ExecaChildProcess | null = null; return { - name: 'command-on-end', + name: 'watchruncommand', setup(build: esbuild.PluginBuild) { build.onEnd((result) => { if (!watching || result.errors.length !== 0) return; @@ -115,7 +115,7 @@ const CommandOnEndPlugin = (watching: boolean, watchCommand?: string) => { currentProcess = execa(cmd, { stdio: 'inherit', shell: true }); currentProcess.catch(error => { if (error.isCanceled) return; - console.error(`[watch] Command execution error: ${error.message}`); + console.error(`[watch] command execution error: ${error.message}`); }); }); } From d3015da02d5affc31f7c8688cddf12a5ccb79251 Mon Sep 17 00:00:00 2001 From: Izan Gil <66965250+SrIzan10@users.noreply.github.com> Date: Fri, 31 Jan 2025 16:59:42 +0100 Subject: [PATCH 4/6] refactor: convert to camelcase --- src/commands/build.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/commands/build.ts b/src/commands/build.ts index c324c6c..0679507 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -59,7 +59,7 @@ type BuildOptions = { const CommandHandlerPlugin = (buildConfig: Partial, ambientFilePath: string, sernTsConfigPath: string) => { return { - name: "commandhandler", + name: "commandHandler", setup(build) { const options = build.initialOptions @@ -83,7 +83,7 @@ const CommandOnEndPlugin = (watching: boolean, watchCommand?: string) => { let currentProcess: ExecaChildProcess | null = null; return { - name: 'watchruncommand', + name: 'watchRunCommand', setup(build: esbuild.PluginBuild) { build.onEnd((result) => { if (!watching || result.errors.length !== 0) return; From f14cf5f3c24df94f7790cce198142145f5851d73 Mon Sep 17 00:00:00 2001 From: Izan Gil <66965250+SrIzan10@users.noreply.github.com> Date: Fri, 31 Jan 2025 20:26:30 +0100 Subject: [PATCH 5/6] feat: add timeout --- src/commands/build.ts | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/commands/build.ts b/src/commands/build.ts index 0679507..bd79dff 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -12,6 +12,7 @@ import * as Preprocessor from '../utilities/preprocessor'; import { bold, magentaBright } from 'colorette'; import { parseTsConfig } from '../utilities/parseTsconfig'; import { execa, type ExecaChildProcess } from 'execa'; +import { setTimeout } from 'node:timers/promises'; const VALID_EXTENSIONS = ['.ts', '.js' ]; @@ -85,9 +86,9 @@ const CommandOnEndPlugin = (watching: boolean, watchCommand?: string) => { return { name: 'watchRunCommand', setup(build: esbuild.PluginBuild) { - build.onEnd((result) => { + build.onEnd(async (result) => { if (!watching || result.errors.length !== 0) return; - if (isFirstBuild) { + if (isFirstBuild === true) { isFirstBuild = false; return; } @@ -106,12 +107,16 @@ const CommandOnEndPlugin = (watching: boolean, watchCommand?: string) => { if (pathExistsSync('package-lock.json')) return 'npm start'; if (pathExistsSync('yarn.lock')) return 'yarn start'; if (pathExistsSync('pnpm-lock.yaml')) return 'pnpm start'; - if (pathExistsSync('bun.lockb')) return 'bun run start'; - throw new Error('[watch] no package manager lockfile found, cannot run default command'); + if (pathExistsSync('bun.lockb')) return 'bun start'; + if (pathExistsSync('bun.lock')) return 'bun start'; + + throw new Error('[watch] default package manager start command not found'); })(); - console.log(`[watch] running command: ${cmd}`); + console.log(`[watch] waiting 1 second before running command...`); + await setTimeout(1000); + console.log(`[watch] running command: ${cmd}`); currentProcess = execa(cmd, { stdio: 'inherit', shell: true }); currentProcess.catch(error => { if (error.isCanceled) return; @@ -121,8 +126,8 @@ const CommandOnEndPlugin = (watching: boolean, watchCommand?: string) => { } } as esbuild.Plugin; }; -const resolveBuildConfig = (path: string|undefined, language: string) => { - if(language === 'javascript') { +const resolveBuildConfig = (path: string | undefined, language: string) => { + if (language === 'javascript') { return path ?? 'jsconfig.json' } return path ?? 'tsconfig.json' From f1fb978871f4e50572b168b887033b6fe93e7734 Mon Sep 17 00:00:00 2001 From: Jacob Nguyen <76754747+jacoobes@users.noreply.github.com> Date: Thu, 6 Feb 2025 22:04:18 -0600 Subject: [PATCH 6/6] addwatchcommandtocli --- src/commands/build.ts | 74 +++++++++++++++++++++++++++++-------------- src/index.ts | 1 + 2 files changed, 51 insertions(+), 24 deletions(-) diff --git a/src/commands/build.ts b/src/commands/build.ts index bd79dff..82397a5 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -12,7 +12,7 @@ import * as Preprocessor from '../utilities/preprocessor'; import { bold, magentaBright } from 'colorette'; import { parseTsConfig } from '../utilities/parseTsconfig'; import { execa, type ExecaChildProcess } from 'execa'; -import { setTimeout } from 'node:timers/promises'; +import { InvalidArgumentError } from 'commander'; const VALID_EXTENSIONS = ['.ts', '.js' ]; @@ -50,12 +50,16 @@ type BuildOptions = { * flag: default false */ sourcemap?: boolean; - /** - * command to run. - * defaults to your package - * manager's start command. - */ - watchCommand?: string; + + watch?: { + /** + * command to run. + * defaults to your package + * manager's start command. + */ + command?: string; + } + }; const CommandHandlerPlugin = (buildConfig: Partial, ambientFilePath: string, sernTsConfigPath: string) => { @@ -82,7 +86,7 @@ const CommandOnEndPlugin = (watching: boolean, watchCommand?: string) => { // for some reason it runs the command twice on first build let isFirstBuild = true; let currentProcess: ExecaChildProcess | null = null; - + let restartTimeout: NodeJS.Timeout | null = null; return { name: 'watchRunCommand', setup(build: esbuild.PluginBuild) { @@ -113,15 +117,20 @@ const CommandOnEndPlugin = (watching: boolean, watchCommand?: string) => { throw new Error('[watch] default package manager start command not found'); })(); - console.log(`[watch] waiting 1 second before running command...`); - await setTimeout(1000); - - console.log(`[watch] running command: ${cmd}`); - currentProcess = execa(cmd, { stdio: 'inherit', shell: true }); - currentProcess.catch(error => { - if (error.isCanceled) return; - console.error(`[watch] command execution error: ${error.message}`); - }); + // Clear any pending restart + if (restartTimeout) clearTimeout(restartTimeout); + + console.log('[watch] debouncing command for 1.5 seconds...'); + + // Set new debounced timeout + restartTimeout = setTimeout(() => { + console.log(`[watch] running command: ${cmd}`); + currentProcess = execa(cmd, { stdio: 'inherit', shell: true }); + currentProcess.catch(error => { + if (error.isCanceled) return; + console.error(`[watch] command execution error: ${error.message}`); + }); + }, 1500); }); } } as esbuild.Plugin; @@ -134,10 +143,15 @@ const resolveBuildConfig = (path: string | undefined, language: string) => { } export async function build(options: Record) { + //console.log(options) if (!options.supressWarnings) { console.info(`${magentaBright('EXPERIMENTAL')}: This API has not been stabilized. add -W or --suppress-warnings flag to suppress`); } - console.log(options) + // if watch was not enabled and watchCommand is present + if(!options.watch && options.watchCommand) { + throw new InvalidArgumentError("enable watch to use --watch-command") + } + const sernConfig = await getConfig(); let buildConfig: BuildOptions; const buildConfigPath = p.resolve(options.project ?? 'sern.build.js'); @@ -150,22 +164,34 @@ export async function build(options: Record) { sourcemap: options.sourceMaps, tsconfig: resolveBuildConfig(options.tsconfig, sernConfig.language), env: options.env ?? '.env', - include: [] + include: [], + watch: { + command: options.watchCommand + } }; + + // merging configuration with sern.build.js, if exists buildConfigPath if (pathExistsSync(buildConfigPath)) { - //throwable, buildConfigPath may not exist - buildConfig = { ...defaultBuildConfig, ...(await import('file:///' + buildConfigPath)).default }; + let fileConfig; + try { fileConfig=await import('file:///' + buildConfigPath).then(r=>r.default) } + catch(e) { + console.error("Could not find buildConfigPath") + throw e; + } + //throwable, buildConfigPath may not exist, todo, merge + buildConfig = { ...defaultBuildConfig, ...fileConfig }; } else { buildConfig = defaultBuildConfig; console.log('No build config found, defaulting'); } + configDotenv({ path: buildConfig.env }); if (process.env.NODE_ENV) { buildConfig.mode = process.env.NODE_ENV as 'production' | 'development'; console.log(magentaBright('NODE_ENV:'), 'Found NODE_ENV variable, setting `mode` to this.'); } - assert(buildConfig.mode === 'development' || buildConfig.mode === 'production', 'Mode is not `production` or `development`'); + assert(buildConfig.mode === 'development' || buildConfig.mode === 'production', 'NODE_ENV is not `production` or `development`'); try { let config = await parseTsConfig(buildConfig.tsconfig!); config?.extends && console.warn("Extend the generated tsconfig") @@ -186,7 +212,7 @@ export async function build(options: Record) { console.log(' ', magentaBright('sourceMaps'), buildConfig.sourcemap); const sernDir = p.resolve('.sern'), - [ambientFilePath, sernTsConfigPath, genDir] = + [ambientFilePath, sernTsConfigPath, genDir] = // resolves the file paths in the .sern dir ['ambient.d.ts', 'tsconfig.json', 'generated'].map(f => p.resolve(sernDir, f)); if (!(await pathExists(genDir))) { @@ -204,7 +230,7 @@ export async function build(options: Record) { entryPoints, plugins: [ CommandHandlerPlugin(buildConfig, ambientFilePath, sernTsConfigPath), - CommandOnEndPlugin(options.watch, buildConfig.watchCommand) + CommandOnEndPlugin(options.watch, buildConfig.watch?.command) ], sourcemap: buildConfig.sourcemap, ...defaultEsbuild(buildConfig.format!, buildConfig.tsconfig), diff --git a/src/index.ts b/src/index.ts index 2ee63eb..bd1f4ae 100644 --- a/src/index.ts +++ b/src/index.ts @@ -58,6 +58,7 @@ program .option('-f --format [fmt]', 'The module system of your application. `cjs` or `esm`', 'esm') .option('-m --mode [mode]', 'the mode for sern to build in. `production` or `development`', 'development') .option('-w --watch') + .option('--watch-command [cmd]', 'the command for sern to watch. if watch is not enabled, an error is thrown', '') .option('-W --suppress-warnings', 'suppress experimental warning') .option('-p --project [filePath]', 'build with the provided sern.build file') .option('-e --env', 'path to .env file')