Dev loop: debug-only page scripts from disk + tab rebuild on change (waybetter-host devloop, page_script!), generic devmode watcher, waybetter dev, buildRuntime watch, template scripts

This commit is contained in:
CRTkafa 2026-09-30 22:20:22 +07:00
parent 2fd866d8fb
commit 04a405c1ba
11 changed files with 377 additions and 26 deletions

View file

@ -2,9 +2,10 @@
// The `waybetter` command: `waybetter store build|sign|verify` (cli/store.mjs),
// `waybetter release windows|macos` (cli/release.mjs), `waybetter i18n check|extract`
// (cli/i18n.mjs), `waybetter privacy-scan` (cli/privacy.mjs) and `waybetter build-env`
// (cli/buildenv.mjs).
// (cli/buildenv.mjs), `waybetter dev` (cli/dev.mjs: watchers + tauri dev).
import { readFileSync } from 'node:fs';
import { BUILD_ENV_USAGE, buildEnvCommand } from '../cli/buildenv.mjs';
import { DEV_USAGE, devCommand } from '../cli/dev.mjs';
import { I18N_USAGE, i18nCommand } from '../cli/i18n.mjs';
import { PRIVACY_USAGE, privacyCommand } from '../cli/privacy.mjs';
import { STORE_USAGE, storeCommand } from '../cli/store.mjs';
@ -22,10 +23,14 @@ try {
process.exitCode = privacyCommand(rest);
} else if (area === 'build-env') {
process.exitCode = buildEnvCommand(rest);
} else if (area === 'dev') {
process.exitCode = await devCommand(rest);
} else if (area === '--version' || area === '-v') {
console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
} else {
console.log(`${STORE_USAGE}\n\n${RELEASE_USAGE}\n\n${I18N_USAGE}\n\n${PRIVACY_USAGE}\n\n${BUILD_ENV_USAGE}`);
console.log(`${STORE_USAGE}\n\n${RELEASE_USAGE}\n\n${I18N_USAGE}\n\n${PRIVACY_USAGE}\n\n${BUILD_ENV_USAGE}
${DEV_USAGE}`);
if (area && area !== '--help' && area !== '-h') process.exitCode = 1;
}
} catch (error) {

View file

@ -10,6 +10,8 @@
// jsx: 'automatic', // any other esbuild option passes through
// });
//
// `watch: true` (an app's build script passes `watchRequested()`) keeps esbuild watching and
// rebuilding `outfile`; a failed rebuild leaves the last good file in place.
// - `?inline` CSS imports become strings (Vite semantics); other CSS side-effect imports are
// dropped, because injected UI adopts its stylesheet into a shadow root explicitly
// (`inlineCss: false` turns this off).
@ -52,15 +54,15 @@ export function catalogPlugin(catalog, prefixes) {
/**
* Builds `entry` into `outfile` (paths relative to `cwd`). Defaults: bundled IIFE, es2022,
* minified, no source map, no legal comments. Returns esbuild's result.
* @param {{ entry: string, outfile: string, catalog?: string, prefixes?: string[], cwd?: string,
* @param {{ entry: string, outfile: string, watch?: boolean, catalog?: string, prefixes?: string[], cwd?: string,
* inlineCss?: boolean, esbuild?: { build: Function }, plugins?: object[], [option: string]: unknown }} options
*/
export async function buildRuntime(options) {
const { entry, outfile, catalog, prefixes = [], cwd = process.cwd(), inlineCss = true, esbuild, plugins = [], ...rest } = options;
const { entry, outfile, catalog, prefixes = [], cwd = process.cwd(), inlineCss = true, esbuild, plugins = [], watch = false, ...rest } = options;
if (!entry || !outfile) throw new Error('buildRuntime: entry and outfile are required');
if (catalog && !prefixes.length) throw new Error('buildRuntime: a catalog needs the key prefixes the runtime ships');
const bundler = esbuild ?? createRequire(path.join(path.resolve(cwd), 'package.json'))('esbuild');
return bundler.build({
const config = {
absWorkingDir: path.resolve(cwd),
entryPoints: [entry],
outfile,
@ -76,5 +78,28 @@ export async function buildRuntime(options) {
...(catalog ? [catalogPlugin(path.resolve(cwd, catalog), prefixes)] : []),
...plugins,
],
};
if (!watch) return bundler.build(config);
// Dev loop: rebuild `outfile` whenever a source changes (a debug host reloads its tabs when the
// file changes). The first build is done when this resolves; the returned context keeps watching.
const context = await bundler.context({
...config,
plugins: [
...config.plugins,
{
name: 'waybetter-watch-log',
setup(api) {
api.onEnd(result => {
const stamp = new Date().toTimeString().slice(0, 8);
console.log(result.errors.length ? `[${stamp}] ${outfile}: build failed, keeping the last good file` : `[${stamp}] rebuilt ${outfile}`);
});
},
},
],
});
await context.watch();
return context;
}
/** True when the calling script was started with `--watch`. */
export const watchRequested = (argv = process.argv) => argv.includes('--watch');

View file

@ -0,0 +1,97 @@
// `waybetter dev`: the dev loop in one command. Starts the app's build watchers, waits until each
// has built once, then runs `tauri dev`. In a debug build the host reads the page scripts from disk
// and rebuilds its tabs when a watcher rewrites one (`waybetter_host::page_script!`), and the
// shell hot-reloads through the frontend dev server (`beforeDevCommand`, e.g. vite).
//
// waybetter dev [--stable] [--watch "<command>"]... [-- <tauri dev args>]
//
// `--stable` adds `--no-watch`: Rust changes do not restart the app (restart it yourself); page
// script and shell changes still reload live. Every `--watch` command must keep running and print
// a line containing "watching" once its first build is done (`buildRuntime({ watch: true })`
// scripts print one); it is stopped with the app.
import { spawn, spawnSync } from 'node:child_process';
import { delimiter, join, resolve } from 'node:path';
export const DEV_USAGE = `Usage:
waybetter dev [--stable] [--watch "<command>"]... [-- <tauri dev args>]
Starts each --watch command (esbuild watchers), waits for its first build ("watching" on a
line of its output, at most 120 s), then runs \`tauri dev\`. --stable passes --no-watch so a
Rust file saved by someone else does not restart the app; Rust changes then need a manual
restart, page-script and shell changes reload live either way.`;
const READY = /watching/i;
const READY_TIMEOUT_MS = 120_000;
/** `waybetter dev` arguments: `{ stable, watch: string[], tauriArgs: string[] }`. */
export function parseDevArgs(args) {
const out = { stable: false, watch: [], tauriArgs: [] };
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
if (arg === '--') {
out.tauriArgs = args.slice(index + 1);
break;
}
if (arg === '--stable') out.stable = true;
else if (arg === '--watch') {
const command = args[(index += 1)];
if (!command) throw new Error('--watch needs a command');
out.watch.push(command);
} else throw new Error(`unknown argument: ${arg}`);
}
return out;
}
/** The `tauri dev` arguments. */
export function tauriDevArgs({ stable, tauriArgs }) {
return ['dev', ...(stable && !tauriArgs.includes('--no-watch') ? ['--no-watch'] : []), ...tauriArgs];
}
function stop(child) {
if (!child.pid || child.exitCode !== null) return;
if (process.platform === 'win32') spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
else child.kill('SIGTERM');
}
export async function devCommand(args, cwd = process.cwd()) {
const options = parseDevArgs(args);
// Local tools (tauri, esbuild) the way an npm script finds them.
const env = { ...process.env, PATH: [join(cwd, 'node_modules', '.bin'), resolve(cwd, '..', 'node_modules', '.bin'), resolve(cwd, '..', '..', 'node_modules', '.bin'), process.env.PATH].join(delimiter) };
const children = [];
const stopAll = () => children.forEach(stop);
process.on('exit', stopAll);
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => process.exit(130));
for (const command of options.watch) {
const child = spawn(command, { cwd, env, shell: true, stdio: ['ignore', 'pipe', 'inherit'] });
children.push(child);
await new Promise((done, fail) => {
const timer = setTimeout(() => fail(new Error(`watcher did not report "watching" in time: ${command}`)), READY_TIMEOUT_MS);
let ready = false;
child.stdout.on('data', chunk => {
process.stdout.write(chunk);
if (!ready && READY.test(String(chunk))) {
ready = true;
clearTimeout(timer);
done();
}
});
child.on('exit', code => {
clearTimeout(timer);
if (!ready) fail(new Error(`watcher exited (${code}) before its first build: ${command}`));
else console.error(`waybetter dev: a watcher stopped (${code}): ${command}`);
});
}).catch(error => {
stopAll();
throw error;
});
}
const tauri = spawn('tauri', tauriDevArgs(options), { cwd, env, shell: true, stdio: 'inherit' });
children.push(tauri);
return new Promise(done =>
tauri.on('exit', code => {
stopAll();
done(code ?? 0);
}),
);
}

View file

@ -53,3 +53,27 @@ test('css plugin: ?inline imports are text, other CSS imports are dropped', asyn
const drop = load.find(hook => hook.options.namespace === 'css-drop');
assert.deepEqual(drop.fn({}), { contents: '', loader: 'js' });
});
test('buildRuntime: watch mode keeps an esbuild context watching and logs each rebuild', async () => {
let seen;
let watching = false;
const esbuild = { context: async options => { seen = options; return { watch: async () => { watching = true; } } } };
const context = await buildRuntime({ entry: 'src/a.ts', outfile: 'out.js', cwd: tmpdir(), esbuild, watch: true });
assert.equal(watching, true);
assert.equal(typeof context.watch, 'function');
assert.equal('watch' in seen, false, 'the flag is not an esbuild option');
const log = seen.plugins.find(plugin => plugin.name === 'waybetter-watch-log');
let onEnd;
log.setup({ onEnd: fn => { onEnd = fn; } });
const lines = [];
const original = console.log;
console.log = line => lines.push(line);
try {
onEnd({ errors: [] });
onEnd({ errors: [{}] });
} finally {
console.log = original;
}
assert.match(lines[0], /rebuilt out\.js/);
assert.match(lines[1], /build failed, keeping the last good file/);
});

View file

@ -0,0 +1,17 @@
// `waybetter dev`: argument parsing and the `tauri dev` arguments (the processes themselves are not started).
import assert from 'node:assert/strict';
import test from 'node:test';
import { parseDevArgs, tauriDevArgs } from '../cli/dev.mjs';
test('dev: watchers, --stable and the tauri arguments after --', () => {
const options = parseDevArgs(['--watch', 'node a.mjs --watch', '--stable', '--watch', 'node b.mjs --watch', '--', '--release']);
assert.deepEqual(options, { stable: true, watch: ['node a.mjs --watch', 'node b.mjs --watch'], tauriArgs: ['--release'] });
assert.deepEqual(tauriDevArgs(options), ['dev', '--no-watch', '--release']);
assert.deepEqual(tauriDevArgs(parseDevArgs([])), ['dev']);
assert.deepEqual(tauriDevArgs(parseDevArgs(['--stable', '--', '--no-watch'])), ['dev', '--no-watch']);
});
test('dev: unknown arguments and a --watch without a command are refused', () => {
assert.throws(() => parseDevArgs(['--fast']), /unknown argument/);
assert.throws(() => parseDevArgs(['--watch']), /needs a command/);
});