An open source design system that's fully customizable and agent ready
TypeScript
test(scripts): the i18n watcher's signal test runs the forwarding runner alone (#10063)
Christopher Chedeau08313899e017
diff --git a/scripts/generate-i18n-runtime.mjs b/scripts/generate-i18n-runtime.mjsindex 7b00b7d5be..2ab028bd5c 100644--- a/scripts/generate-i18n-runtime.mjs+++ b/scripts/generate-i18n-runtime.mjs@@ -220,11 +220,22 @@ export function createSpawnInvocation(};}-async function watchRuntimeCatalogs(command) {+/**+ * Runs `command` once the runtime catalogs are current and regenerates them+ * while it runs. A test passes its own `generate`, `run` and `watch`.+ */+export async function watchRuntimeCatalogs(+ command,+ {+ generate = generateRuntimeCatalogs,+ run = runForwardingSignals,+ watch = fs.watch,+ } = {},+) {let debounce;let regeneration = Promise.resolve();const queueGeneration = () => {- const next = regeneration.then(() => generateRuntimeCatalogs());+ const next = regeneration.then(() => generate());regeneration = next.catch(() => {});return next;};@@ -239,14 +250,14 @@ async function watchRuntimeCatalogs(command) {});}, 75);};- const watcher = fs.watch(SOURCE_LOCALES_DIR, (_event, file) => {+ const watcher = watch(SOURCE_LOCALES_DIR, (_event, file) => {const fileName = file == null ? null : String(file);if (fileName !== null && !isSourceLocaleFile(fileName)) return;scheduleGeneration();});// Core modules decide which keys each English fallback map holds, so a// module edit regenerates the maps too.- const sourceWatcher = fs.watch(+ const sourceWatcher = watch(CORE_SRC_DIR,{recursive: true},(_event, file) => {@@ -261,24 +272,7 @@ async function watchRuntimeCatalogs(command) {// Register the watcher first so an edit during initial generation queues a// second pass instead of leaving the child process on stale catalogs.await queueGeneration();-- const spawnOptions = {env: process.env, stdio: 'inherit'};- const invocation = createSpawnInvocation(command);- const child = spawn(invocation.file, invocation.args, spawnOptions);- const forwardInterrupt = () => child.kill('SIGINT');- const forwardTermination = () => child.kill('SIGTERM');- process.on('SIGINT', forwardInterrupt);- process.on('SIGTERM', forwardTermination);-- try {- return await new Promise((resolve, reject) => {- child.once('error', reject);- child.once('exit', (code, signal) => resolve(signal ? 1 : (code ?? 1)));- });- } finally {- process.removeListener('SIGINT', forwardInterrupt);- process.removeListener('SIGTERM', forwardTermination);- }+ return await run(command);} finally {clearTimeout(debounce);watcher.close();@@ -286,6 +280,32 @@ async function watchRuntimeCatalogs(command) {}}+/**+ * Runs `command` as a child and forwards SIGINT and SIGTERM to it until it+ * exits. Resolves with the child's exit code, or 1 when a signal ended it.+ */+export async function runForwardingSignals(command) {+ const invocation = createSpawnInvocation(command);+ const child = spawn(invocation.file, invocation.args, {+ env: process.env,+ stdio: 'inherit',+ });+ const forwardInterrupt = () => child.kill('SIGINT');+ const forwardTermination = () => child.kill('SIGTERM');+ process.on('SIGINT', forwardInterrupt);+ process.on('SIGTERM', forwardTermination);++ try {+ return await new Promise((resolve, reject) => {+ child.once('error', reject);+ child.once('exit', (code, signal) => resolve(signal ? 1 : (code ?? 1)));+ });+ } finally {+ process.removeListener('SIGINT', forwardInterrupt);+ process.removeListener('SIGTERM', forwardTermination);+ }+}+async function main() {const args = process.argv.slice(2);if (args.includes('--watch')) {diff --git a/scripts/generate-i18n-runtime.test.mjs b/scripts/generate-i18n-runtime.test.mjsindex 97756420f9..6351c894ea 100644--- a/scripts/generate-i18n-runtime.test.mjs+++ b/scripts/generate-i18n-runtime.test.mjs@@ -5,7 +5,7 @@ import {once} from 'node:events';import {mkdtempSync, rmSync, symlinkSync} from 'node:fs';import {tmpdir} from 'node:os';import path from 'node:path';-import {fileURLToPath} from 'node:url';+import {fileURLToPath, pathToFileURL} from 'node:url';import {describe, expect, it} from 'vitest';import {createRuntimeCatalog,@@ -14,12 +14,16 @@ import {getGeneratedModuleName,isSourceLocaleFile,renderRuntimeCatalogModule,+ watchRuntimeCatalogs,} from './generate-i18n-runtime.mjs';const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url));const GENERATOR = fileURLToPath(new URL('./generate-i18n-runtime.mjs', import.meta.url),);+// Windows runs a watch command through cmd.exe, which takes only shell-safe+// tokens: a bare `node` and no spaces or parentheses.+const EXIT_3_COMMAND = ['node', '-e', 'process.exitCode=3'];function waitForMatch(stream, pattern, timeoutMs = 5_000) {return new Promise((resolve, reject) => {@@ -61,6 +65,30 @@ describe('generator CLI', () => {rmSync(temp, {recursive: true, force: true});}});++ it('--watch runs the command after generation and returns its exit code', async ({+ signal,+ }) => {+ // An asynchronous spawn leaves the test timeout free to fire, and the+ // test's signal then stops a `--watch` that never exits.+ const cli = spawn(+ process.execPath,+ [GENERATOR, '--watch', '--', ...EXIT_3_COMMAND],+ {cwd: REPO_ROOT, signal, stdio: ['ignore', 'pipe', 'pipe']},+ );+ let stdout = '';+ let stderr = '';+ cli.stdout.on('data', chunk => {+ stdout += chunk;+ });+ cli.stderr.on('data', chunk => {+ stderr += chunk;+ });+ const [code] = await once(cli, 'exit');++ expect(code, stderr).toBe(3);+ expect(stdout).toMatch(/Generated \d+ runtime locale modules/);+ });});describe('createRuntimeCatalog', () => {@@ -168,6 +196,41 @@ describe('locale source watcher', () => {).toThrow('cannot contain spaces or shell metacharacters');});+ it('runs the command only once its catalogs are current, then closes both watchers', async () => {+ const events = [];+ const watch = () => ({close: () => events.push('close watcher')});+ const code = await watchRuntimeCatalogs(['tool', 'argument'], {+ generate: async () => {+ events.push('generation starts');+ await Promise.resolve();+ events.push('generation ends');+ },+ run: async command => {+ events.push(`run ${command.join(' ')}`);+ return 7;+ },+ watch,+ });++ expect(code).toBe(7);+ expect(events).toEqual([+ 'generation starts',+ 'generation ends',+ 'run tool argument',+ 'close watcher',+ 'close watcher',+ ]);+ });++ it('runs the command through the forwarding runner by default and returns its exit code', async () => {+ const code = await watchRuntimeCatalogs(EXIT_3_COMMAND, {+ generate: async () => {},+ watch: () => ({close: () => {}}),+ });++ expect(code).toBe(3);+ });+it.skipIf(process.platform === 'win32')('forwards repeated termination signals until the child exits',async () => {@@ -180,9 +243,16 @@ describe('locale source watcher', () => {console.log('child-ready:' + process.pid);setInterval(() => {}, 1_000);`;+ // The runner that `--watch` starts once its catalogs are current. Run+ // alone, the wait for the child's ready line covers the child's start,+ // not a full catalog generation.+ const runnerCode = `+ import {runForwardingSignals} from ${JSON.stringify(pathToFileURL(GENERATOR).href)};+ process.exitCode = await runForwardingSignals(${JSON.stringify([process.execPath, '-e', childCode])});+ `;const wrapper = spawn(process.execPath,- [GENERATOR, '--watch', '--', process.execPath, '-e', childCode],+ ['--input-type=module', '-e', runnerCode],{cwd: REPO_ROOT,stdio: ['ignore', 'pipe', 'pipe'],