import { execFile } from 'node:child_process'; import { mkdir, mkdtemp, realpath, rm, symlink, utimes, writeFile } from 'node:fs/promises'; import { createRequire } from 'node:module'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { promisify } from 'node:util'; import { afterEach, describe, expect, it } from 'vitest'; import { register } from 'tsx/esm/api'; import { NativeDevelopmentModuleRuntime, supportsNativeTypeScript, type ModuleRuntime, } from '../src/index.js'; import { resolve as resolveTypeScriptSpecifier } from '../src/typescript-specifier-remap.js'; const temporary: string[] = []; const execFileAsync = promisify(execFile); const tsxLoaderUrl = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href; const nativeTypeScriptIt = supportsNativeTypeScript() ? it : it.skip; const inheritedStripTypeArguments = process.execArgv.includes('--experimental-strip-types') ? ['--experimental-strip-types'] : []; afterEach(async () => { await Promise.all(temporary.splice(0).map((path) => rm(path, { force: true, recursive: true }))); }); describe('NativeDevelopmentModuleRuntime', () => { it.each(['helper', 'plugin-entry'] as const)('keeps unrelated Plugin entry side effects cached while refreshing %s', async mode => { const root = await fixture(); const key = `zhin-native-config-review:${root}`; for (const name of ['root', 'child', 'sibling']) { const directory = name === 'root' ? root : join(root, 'plugins', name); await mkdir(directory, { recursive: true }); await writeFile(join(directory, 'package.json'), JSON.stringify({ name: `native-${name}`, version: '1.0.0', type: 'module', // The shared fixture has a commands/ directory; an explicit (empty) features list keeps // the Command Feature from being required by convention inference. zhin: { protocol: 1, type: 'plugin', entry: './plugin.js', platformFeatures: false, features: [] } })); await writeFile(join(directory, 'plugin.js'), `${name === 'child' ? "import { value } from './helper.js';" : 'const value = 1;'} const counts = globalThis[Symbol.for(${JSON.stringify(key)})]; counts.${name} = (counts.${name} ?? 0) + 1; export default { name: '${name}', config: { toJsonSchema() { return { type: 'object', properties: { value: { type: 'number', default: value } } }; } } }; `); } const helper = join(root, 'plugins/child/helper.js'); await writeFile(helper, 'export const value = 1;'); const scenario = join(root, 'config-hmr-scenario.mjs'); await writeFile(scenario, ` import { writeFile } from 'node:fs/promises'; import { RootRuntime, NativeDevelopmentModuleRuntime } from ${JSON.stringify(new URL('../src/index.ts', import.meta.url).href)}; globalThis[Symbol.for(${JSON.stringify(key)})] = {}; const runtime = new RootRuntime({ projectRoot: ${JSON.stringify(root)}, config: { configVersion: 2, plugins: { child: './plugins/child', sibling: './plugins/sibling' } }, modules: new NativeDevelopmentModuleRuntime({ projectRoot: ${JSON.stringify(root)}, watch: false }), environment: { name: 'test', mode: 'test', platform: 'node' } }); try { await runtime.start(); const first = { ...globalThis[Symbol.for(${JSON.stringify(key)})] }; const versions = [...runtime.snapshot.tree.values()].map(node => node.packageVersion); ${mode === 'helper' ? `await writeFile(${JSON.stringify(helper)}, 'export const value = 2;');` : `const childEntry = ${JSON.stringify(join(root, 'plugins/child/plugin.js'))}; const { readFile } = await import('node:fs/promises'); await writeFile(childEntry, (await readFile(childEntry, 'utf8')).replace("import { value } from './helper.js';", 'const value = 2;'));`} const hmr = runtime.createHmrCoordinator({ onRestartRequired() { throw new Error('Unexpected process restart'); }, onError() {} }); await hmr.enqueue(${JSON.stringify(mode === 'helper' ? helper : join(root, 'plugins/child/plugin.js'))}); process.stdout.write(JSON.stringify({ first, counts: globalThis[Symbol.for(${JSON.stringify(key)})], generation: runtime.snapshot.generation, config: [...runtime.snapshot.config.values()], versions })); } finally { await runtime.stop(); } `); const { stdout } = await execFileAsync(process.execPath, [...inheritedStripTypeArguments, '--conditions=development', '--import', tsxLoaderUrl, scenario], { cwd: process.cwd() }); const result = JSON.parse(stdout); expect(result.first).toEqual({ root: 1, child: 1, sibling: 1 }); expect(result.counts).toEqual({ root: 1, child: 2, sibling: 1 }); expect(result.generation).toBe(2); expect(result.config).toContainEqual({ value: 2 }); expect(result.versions).toEqual(['1.0.0', '1.0.0', '1.0.0']); }); it('uses URL revisions to reload one directly owned ESM definition', async () => { const root = await fixture(); const source = join(root, 'commands/status/index.js'); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); await writeFile(source, 'export default 1;\n'); expect((await runtime.load<{ default: number }>(source)).default).toBe(1); await writeFile(source, 'export default 2;\n'); runtime.invalidate(source); expect((await runtime.load<{ default: number }>(source)).default).toBe(2); await runtime.close(); }); nativeTypeScriptIt('maps a transitive helper outside an entry directory back to that entry', async () => { const root = await fixture(); const source = join(root, 'commands/status/index.ts'); const helper = join(root, 'src/status-message.ts'); const bridge = join(root, 'src/status-command.ts'); await mkdir(join(root, 'src'), { recursive: true }); await writeFile(helper, "export const statusMessage = 'v1';\n"); await writeFile( bridge, "export { statusMessage } from './status-message.js';\n", ); await writeFile( source, "import { statusMessage } from '../../src/status-command.js';\nexport default statusMessage;\n", ); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); const modules: ModuleRuntime = runtime; expect((await runtime.load<{ default: string }>(source)).default).toBe('v1'); expect(modules.affectedSources?.(helper)).toEqual([helper, source]); expect(runtime.requiresProcessRestart(helper)).toBe(false); await runtime.close(); }); nativeTypeScriptIt('maps package-local import aliases back to their loaded entry', async () => { const root = await fixture(); const source = join(root, 'commands/status/index.ts'); const helper = join(root, 'src/status-message.ts'); await mkdir(join(root, 'src'), { recursive: true }); await writeFile(join(root, 'package.json'), JSON.stringify({ type: 'module', imports: { '#status-message': './src/status-message.ts' }, })); await writeFile(helper, "export const statusMessage = 'ready';\n"); await writeFile( source, "import { statusMessage } from '#status-message';\nexport default statusMessage;\n", ); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); expect((await runtime.load<{ default: string }>(source)).default).toBe('ready'); expect(runtime.affectedSources(helper)).toEqual([helper, source]); expect(runtime.requiresProcessRestart(helper)).toBe(false); await runtime.close(); }); nativeTypeScriptIt('reloads the complete relative import closure in a real Node process', async () => { const root = await fixture(); const runtimeEntry = new URL('../src/index.ts', import.meta.url).href; const scenario = join(root, 'hmr-scenario.mjs'); await writeFile(scenario, ` import { mkdir, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { ensureTypeScriptSpecifierRemap, NativeDevelopmentModuleRuntime } from ${JSON.stringify(runtimeEntry)}; const root = ${JSON.stringify(root)}; const entry = join(root, 'commands/status/index.ts'); const helper = join(root, 'src/status-message.ts'); const bridge = join(root, 'src/status-command.ts'); await mkdir(join(root, 'src'), { recursive: true }); await writeFile(helper, "export const statusMessage = 'v1';\\n"); await writeFile(bridge, "export { statusMessage } from './status-message.js';\\n"); await writeFile(entry, "import { statusMessage } from '../../src/status-command.js';\\nexport default statusMessage;\\n"); ensureTypeScriptSpecifierRemap(); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); const first = (await runtime.load(entry)).default; await writeFile(helper, "export const statusMessage = 'v2';\\n"); runtime.invalidate(helper); const second = (await runtime.load(entry)).default; await runtime.close(); process.stdout.write(JSON.stringify({ first, second })); `); const { stdout } = await execFileAsync( process.execPath, [...inheritedStripTypeArguments, '--import', tsxLoaderUrl, scenario], { cwd: process.cwd() }, ); expect(JSON.parse(stdout)).toEqual({ first: 'v1', second: 'v2' }); }); nativeTypeScriptIt('reloads a package-name import of a mounted workspace Plugin with its importer (#1250)', async () => { const root = await fixture(); const runtimeEntry = new URL('../src/index.ts', import.meta.url).href; const scenario = join(root, 'cross-package-scenario.mjs'); await writeFile(scenario, ` import { mkdir, symlink, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { NativeDevelopmentModuleRuntime } from ${JSON.stringify(runtimeEntry)}; const root = ${JSON.stringify(root)}; const weather = join(root, 'plugins/weather'); const shared = join(root, 'packages/shared'); const wttr = join(weather, 'src/wttr.ts'); const value = join(shared, 'value.ts'); const entry = join(root, 'tools/lookup/index.ts'); for (const directory of [join(weather, 'src'), shared, join(root, 'tools/lookup'), join(root, 'node_modules/@test')]) { await mkdir(directory, { recursive: true }); } // A workspace Plugin and a plain workspace library, linked like pnpm does. await writeFile(join(weather, 'package.json'), JSON.stringify({ name: '@test/weather', type: 'module', exports: { './wttr': './src/wttr.ts' } })); await writeFile(join(shared, 'package.json'), JSON.stringify({ name: '@test/shared', type: 'module', exports: { './value': './value.ts' } })); await symlink(weather, join(root, 'node_modules/@test/weather'), 'dir'); await symlink(shared, join(root, 'node_modules/@test/shared'), 'dir'); await writeFile(wttr, "export const forecast = 'v1';\\n"); await writeFile(value, "export const value = 's1';\\n"); await writeFile(entry, "import { forecast } from '@test/weather/wttr';\\nimport { value } from '@test/shared/value';\\nexport default forecast + ':' + value;\\n"); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); const first = (await runtime.load(entry)).default; // The committed generation mounts plugins/weather as a local child Plugin. runtime.updateRevisionableRoots([weather]); const affected = runtime.affectedSources(wttr); const stale = runtime.staleDependents(value); await writeFile(wttr, "export const forecast = 'v2';\\n"); await runtime.invalidate(wttr); const second = (await runtime.load(entry)).default; await runtime.close(); process.stdout.write(JSON.stringify({ first, second, affected, stale })); `); const { stdout } = await execFileAsync( process.execPath, [...inheritedStripTypeArguments, '--import', tsxLoaderUrl, scenario], { cwd: process.cwd() }, ); const entry = join(root, 'tools/lookup/index.ts'); expect(JSON.parse(stdout)).toEqual({ first: 'v1:s1', second: 'v2:s1', affected: [join(root, 'plugins/weather/src/wttr.ts'), entry], // A plain library is not revisioned: its importer keeps the old instance and is reported. stale: [entry], }); }); nativeTypeScriptIt('keeps one instance of an unchanged mounted Plugin package across importer reloads (#1250)', async () => { const root = await fixture(); const runtimeEntry = new URL('../src/index.ts', import.meta.url).href; const scenario = join(root, 'shared-package-scenario.mjs'); await writeFile(scenario, ` import { mkdir, symlink, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { NativeDevelopmentModuleRuntime } from ${JSON.stringify(runtimeEntry)}; const root = ${JSON.stringify(root)}; const weather = join(root, 'plugins/weather'); const wttr = join(weather, 'src/wttr.ts'); const lookup = join(root, 'tools/lookup/index.ts'); const local = join(root, 'tools/lookup/local.ts'); const other = join(root, 'tools/other/index.ts'); for (const directory of [join(weather, 'src'), join(root, 'tools/lookup'), join(root, 'tools/other'), join(root, 'node_modules/@test')]) { await mkdir(directory, { recursive: true }); } await writeFile(join(weather, 'package.json'), JSON.stringify({ name: '@test/weather', type: 'module', exports: { './wttr': './src/wttr.ts' } })); await symlink(weather, join(root, 'node_modules/@test/weather'), 'dir'); const module = (version) => "globalThis.evaluations = (globalThis.evaluations ?? 0) + 1;\\nexport const forecast = '" + version + "';\\nexport const state = {};\\n"; await writeFile(wttr, module('v1')); await writeFile(local, "export const local = 'l1';\\n"); await writeFile(lookup, "import { forecast, state } from '@test/weather/wttr';\\nimport { local } from './local.ts';\\nexport default { value: forecast + ':' + local, state };\\n"); await writeFile(other, "import { forecast, state } from '@test/weather/wttr';\\nexport default { value: forecast, state };\\n"); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); await runtime.load(lookup); await runtime.load(other); runtime.updateRevisionableRoots([weather]); const steps = []; const observe = async (reload) => { const a = (await runtime.load(lookup)).default; const b = (await runtime.load(other)).default; steps.push({ lookup: a.value, other: b.value, evaluations: globalThis.evaluations, shared: a.state === b.state }); }; // Only the importer's own helper changed: the package keeps its one instance. await writeFile(local, "export const local = 'l2';\\n"); await runtime.invalidate(local); await observe(); // The package changed: every importer that reloads shares one fresh instance. await writeFile(wttr, module('v2')); await runtime.invalidate(wttr); await observe(); // The importer reloads again for its own helper: the changed package is not evaluated again. await writeFile(local, "export const local = 'l3';\\n"); await runtime.invalidate(local); await observe(); await runtime.close(); process.stdout.write(JSON.stringify(steps)); `); const { stdout } = await execFileAsync( process.execPath, [...inheritedStripTypeArguments, '--import', tsxLoaderUrl, scenario], { cwd: process.cwd() }, ); expect(JSON.parse(stdout)).toEqual([ { lookup: 'v1:l2', other: 'v1', evaluations: 1, shared: true }, { lookup: 'v2:l2', other: 'v2', evaluations: 2, shared: true }, { lookup: 'v2:l3', other: 'v2', evaluations: 2, shared: true }, ]); }); it('does not follow a package-name import into linked sources outside its watch roots (#1250)', async () => { const workspace = await fixture(); const project = join(workspace, 'project'); const framework = join(workspace, 'framework'); for (const directory of [join(project, 'commands/status'), join(project, 'node_modules/@test'), framework]) { await mkdir(directory, { recursive: true }); } await writeFile(join(project, 'package.json'), '{"type":"module"}\n'); await writeFile(join(framework, 'package.json'), JSON.stringify({ name: '@test/framework', type: 'module', exports: './index.js' })); await writeFile(join(framework, 'index.js'), 'export const core = 1;\n'); await symlink(framework, join(project, 'node_modules/@test/framework'), 'dir'); const entry = join(project, 'commands/status/index.js'); await writeFile(entry, "import { core } from '@test/framework';\nexport default core;\n"); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: project, watch: false }); expect((await runtime.load<{ default: number }>(entry)).default).toBe(1); expect(runtime.affectedSources(join(framework, 'index.js'))).toEqual([join(framework, 'index.js')]); expect(runtime.staleDependents(join(framework, 'index.js'))).toEqual([]); await runtime.close(); }); nativeTypeScriptIt('loads native .mts and .cts capability entries consistently', async () => { const root = await fixture(); const mts = join(root, 'commands/status/index.mts'); const cts = join(root, 'commands/status/index.cts'); const cjsHelper = join(root, 'commands/status/helper.cjs'); await writeFile(mts, 'export default 1;\n'); await writeFile(cts, "module.exports = require('./helper.cjs');\n"); await writeFile(cjsHelper, 'module.exports = 2;\n'); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); expect((await runtime.load<{ default: number }>(mts)).default).toBe(1); expect((await runtime.load<{ default: number }>(cts)).default).toBe(2); expect(runtime.affectedSources(cjsHelper)).toEqual([cjsHelper, cts]); expect(runtime.requiresProcessRestart(mts)).toBe(false); expect(runtime.requiresProcessRestart(cts)).toBe(true); expect(runtime.requiresProcessRestart(cjsHelper)).toBe(true); await runtime.close(); }); it('keeps the committed dependency mapping when a replacement module fails to load', async () => { const root = await fixture(); const source = join(root, 'commands/status/index.js'); const helper = join(root, 'src/status-message.js'); await mkdir(join(root, 'src'), { recursive: true }); await writeFile(helper, "export const statusMessage = 'ready';\n"); await writeFile( source, "import { statusMessage } from '../../src/status-message.js';\nexport default statusMessage;\n", ); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); await runtime.load(source); await writeFile(source, 'export default {;\n'); runtime.invalidate(helper); await expect(runtime.load(source)).rejects.toThrow(); expect(runtime.affectedSources(helper)).toEqual([helper, source]); await runtime.close(); }); it('stages dependency changes until the generation transaction commits', async () => { const root = await fixture(); const source = join(root, 'commands/status/index.js'); const firstHelper = join(root, 'src/first-message.js'); const secondHelper = join(root, 'src/second-message.js'); await mkdir(join(root, 'src'), { recursive: true }); await writeFile(firstHelper, "export const statusMessage = 'first';\n"); await writeFile(secondHelper, "export const statusMessage = 'second';\n"); await writeFile( source, "import { statusMessage } from '../../src/first-message.js';\nexport default statusMessage;\n", ); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); await runtime.load(source); runtime.beginGeneration(); runtime.invalidate(source); await writeFile( source, "import { statusMessage } from '../../src/second-message.js';\nexport default statusMessage;\n", ); await runtime.load(source); runtime.rollbackGeneration(); expect(runtime.affectedSources(firstHelper)).toEqual([firstHelper, source]); expect(runtime.affectedSources(secondHelper)).toEqual([secondHelper]); runtime.beginGeneration(); await runtime.load(source); runtime.commitGeneration([source]); expect(runtime.affectedSources(firstHelper)).toEqual([firstHelper]); expect(runtime.affectedSources(secondHelper)).toEqual([secondHelper, source]); await runtime.close(); }); it('drops dependency mappings only when committed ownership removes an entry', async () => { const root = await fixture(); const source = join(root, 'commands/status/index.js'); const helper = join(root, 'src/status-message.js'); await mkdir(join(root, 'src'), { recursive: true }); await writeFile(helper, "export const statusMessage = 'ready';\n"); await writeFile( source, "import { statusMessage } from '../../src/status-message.js';\nexport default statusMessage;\n", ); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); await runtime.load(source); expect(runtime.affectedSources(helper)).toEqual([helper, source]); runtime.commitGeneration([]); expect(runtime.affectedSources(helper)).toEqual([helper]); await runtime.close(); }); it('loads a published JavaScript entry from node_modules without TypeScript stripping', async () => { const root = await fixture(); const packageRoot = join(root, 'node_modules/@test/plugin'); const source = join(packageRoot, 'plugin.js'); await mkdir(packageRoot, { recursive: true }); await writeFile(join(packageRoot, 'package.json'), '{"type":"module"}\n'); await writeFile(source, 'export default { installed: true };\n'); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); const loaded = await runtime.load<{ default: { installed: boolean } }>(source); expect(loaded.default).toEqual({ installed: true }); await runtime.close(); }); it('delegates TSX to the configured process loader and reloads revisions', async () => { const root = await fixture(); const source = join(root, 'commands/status/index.tsx'); const jsxPackage = join(root, 'node_modules/test-jsx'); await mkdir(jsxPackage, { recursive: true }); await writeFile(join(root, 'package.json'), '{"type":"module"}\n'); await writeFile(join(root, 'tsconfig.json'), JSON.stringify({ compilerOptions: { jsx: 'react-jsx', jsxImportSource: 'test-jsx' }, })); await writeFile(join(jsxPackage, 'package.json'), JSON.stringify({ type: 'module', exports: { './jsx-runtime': './jsx-runtime.js', './jsx-dev-runtime': './jsx-runtime.js', }, })); await writeFile( join(jsxPackage, 'jsx-runtime.js'), 'export const jsx=(type,props)=>({type,props});export const jsxs=jsx;export const jsxDEV=jsx;export const Fragment=Symbol();\n', ); const unregister = register({ tsconfig: join(root, 'tsconfig.json') }); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); try { await writeFile(source, 'export default ready;\n'); expect((await runtime.load<{ default: { props: { value: number } } }>(source)).default.props.value) .toBe(1); await writeFile(source, 'export default ready;\n'); runtime.invalidate(source); expect((await runtime.load<{ default: { props: { value: number } } }>(source)).default.props.value) .toBe(2); } finally { await runtime.close(); await unregister(); } }); it('keeps direct capabilities local and escalates support modules before they are indexed', async () => { const root = await fixture(); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); expect(runtime.requiresProcessRestart(join(root, 'commands/gh/status/index.ts'))).toBe(false); expect(runtime.requiresProcessRestart(join(root, 'commands/gh/status/index.tsx'))).toBe(false); expect(runtime.requiresProcessRestart(join(root, 'commands/gh/status/index.mts'))).toBe(false); expect(runtime.requiresProcessRestart(join(root, 'commands/gh/status/index.cts'))).toBe(true); expect(runtime.requiresProcessRestart(join(root, 'components/card/index.ts'))).toBe(false); expect(runtime.requiresProcessRestart(join(root, 'components/card/index.tsx'))).toBe(false); expect(runtime.requiresProcessRestart(join(root, 'tools/weather/index.ts'))).toBe(false); expect(runtime.requiresProcessRestart(join(root, 'tools/shared/client.ts'))).toBe(false); expect(runtime.requiresProcessRestart(join(root, 'src/helper.ts'))).toBe(true); expect(runtime.requiresProcessRestart(join(root, 'src/helper.mts'))).toBe(true); expect(runtime.requiresProcessRestart(join(root, 'src/helper.cts'))).toBe(true); expect(runtime.requiresProcessRestart(join(root, 'schema.json'))).toBe(false); // Root bootstrap files reload in place through a Root generation (#1250). expect(runtime.requiresProcessRestart(join(root, 'BOT.md'))).toBe(false); expect(runtime.requiresProcessRestart(join(root, 'AGENTS.md'))).toBe(false); expect(runtime.requiresProcessRestart(join(root, '.env'))).toBe(true); expect(runtime.requiresProcessRestart(join(root, '.env.production'))).toBe(true); await runtime.close(); }); it('escalates non-entry support files inside capability directories', async () => { const root = await fixture(); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root, watch: false }); expect(runtime.requiresProcessRestart(join(root, 'commands/_utils.ts'))).toBe(true); expect(runtime.requiresProcessRestart(join(root, 'commands/_utils/format.ts'))).toBe(true); expect(runtime.requiresProcessRestart(join(root, 'commands/utils.js'))).toBe(true); expect(runtime.requiresProcessRestart(join(root, 'commands/format/index.json'))).toBe(true); expect(runtime.requiresProcessRestart(join(root, 'components/Card.ts'))).toBe(true); expect(runtime.requiresProcessRestart(join(root, 'commands/notes.md'))).toBe(false); expect(runtime.requiresProcessRestart(join(root, 'commands/gh/status/index.ts'))).toBe(false); await runtime.close(); }); it('reports the native Node TypeScript version contract deterministically', () => { expect(supportsNativeTypeScript('22.14.0', [], '')).toBe(false); expect(supportsNativeTypeScript('22.14.0', ['--experimental-strip-types'], '')).toBe(true); expect(supportsNativeTypeScript('22.14.0', [], '--experimental-strip-types')).toBe(true); expect(supportsNativeTypeScript('22.18.0', [], '')).toBe(true); expect(supportsNativeTypeScript('23.5.0', [], '')).toBe(false); expect(supportsNativeTypeScript('23.6.0', [], '')).toBe(true); expect(supportsNativeTypeScript('24.0.0', [], '')).toBe(true); }); it('reports source changes without a third-party watcher', async () => { const root = await fixture(); const source = join(root, 'commands/status/index.tsx'); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root }); const observed = new Promise((resolve, reject) => { // fs events can be delayed for seconds when the harness runs suites in // parallel; keep the budget well above that instead of a tight 2s. const timeout = setTimeout(() => reject(new Error('watch timeout')), 15_000); const dispose = runtime.watch((changed) => { if (changed !== source) return; clearTimeout(timeout); dispose(); resolve(changed); }); }); // fs.watch attaches asynchronously on some platforms; keep rewriting until // the watcher observes a change so the attach race cannot lose the event. const writer = setInterval(() => { void writeFile(source, `export default ${Date.now()};\n`).catch(() => {}); }, 200); try { await writeFile(source, 'export default 1;\n'); await expect(observed).resolves.toBe(source); } finally { clearInterval(writer); await runtime.close(); } }); it('watches a sibling workspace child Plugin root after the graph commits', async () => { const root = await fixture(); const sibling = await fixture(); const source = join(sibling, 'commands/status/index.ts'); await writeFile(join(sibling, 'package.json'), JSON.stringify({ name: '@test/sibling', type: 'module', zhin: { protocol: 1, type: 'plugin', entry: './plugin.ts' }, })); await writeFile(join(sibling, 'plugin.ts'), 'export default {};\n'); await writeFile(source, 'export default 0;\n'); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root }); runtime.updateWatchRoots([{ root: sibling, source: 'workspace' }]); expect(runtime.requiresProcessRestart(source)).toBe(false); expect(runtime.requiresProcessRestart(join(root, 'node_modules/@test/plugin/commands/status/index.ts'))) .toBe(true); const observed = new Promise((resolve, reject) => { const timeout = setTimeout(() => reject(new Error('watch timeout')), 15_000); const dispose = runtime.watch((changed) => { if (changed !== source) return; clearTimeout(timeout); dispose(); resolve(changed); }); }); const writer = setInterval(() => { void writeFile(source, `export default ${Date.now()};\n`).catch(() => {}); }, 200); try { await expect(observed).resolves.toBe(source); } finally { clearInterval(writer); await runtime.close(); } }); it('ignores build output directories like the polling snapshot does', async () => { const root = await fixture(); await mkdir(join(root, 'lib'), { recursive: true }); const ignored = join(root, 'lib/bundle.js'); const source = join(root, 'commands/status/index.ts'); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root }); const reported: string[] = []; const observed = new Promise((resolve, reject) => { const timeout = setTimeout(() => reject(new Error('watch timeout')), 15_000); const dispose = runtime.watch((changed) => { reported.push(changed); if (changed !== source) return; clearTimeout(timeout); dispose(); resolve(); }); }); // Write both the ignored build output and a real source until the watcher // observes the source; any native event for lib/ would arrive first. const writer = setInterval(() => { void writeFile(ignored, `export default ${Date.now()};\n`).catch(() => {}); void writeFile(source, `export default ${Date.now()};\n`).catch(() => {}); }, 200); try { await writeFile(ignored, 'export default 0;\n'); await writeFile(source, 'export default 1;\n'); await observed; expect(reported).toContain(source); expect(reported).not.toContain(ignored); } finally { clearInterval(writer); await runtime.close(); } }); it('ignores runtime data/ directory so schedule-jobs.json cannot loop HMR', async () => { const root = await fixture(); await mkdir(join(root, 'data'), { recursive: true }); const ignored = join(root, 'data/schedule-jobs.json'); const source = join(root, 'commands/status/index.ts'); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root }); const reported: string[] = []; const observed = new Promise((resolve, reject) => { const timeout = setTimeout(() => reject(new Error('watch timeout')), 15_000); const dispose = runtime.watch((changed) => { reported.push(changed); if (changed !== source) return; clearTimeout(timeout); dispose(); resolve(); }); }); const writer = setInterval(() => { void writeFile(ignored, `${JSON.stringify({ version: 1, jobs: [], t: Date.now() })}\n`).catch(() => {}); void writeFile(source, `export default ${Date.now()};\n`).catch(() => {}); }, 200); try { await writeFile(ignored, '{"version":1,"jobs":[]}\n'); await writeFile(source, 'export default 1;\n'); await observed; expect(reported).toContain(source); expect(reported).not.toContain(ignored); } finally { clearInterval(writer); await runtime.close(); } }); it('ignores editor temp and backup files next to a real source (#857)', async () => { const root = await fixture(); const directory = join(root, 'commands/status'); const ignored = ['.!97910!index.ts', '.index.ts.swp', 'index.ts~', 'index.ts___jb_tmp___'] .map((name) => join(directory, name)); const source = join(directory, 'index.ts'); const runtime = new NativeDevelopmentModuleRuntime({ projectRoot: root }); const reported: string[] = []; const observed = new Promise((resolve, reject) => { const timeout = setTimeout(() => reject(new Error('watch timeout')), 15_000); const dispose = runtime.watch((changed) => { reported.push(changed); if (changed !== source) return; clearTimeout(timeout); dispose(); resolve(); }); }); // Temp files are written before the real source on every tick, so any // event for them would be reported before the source event resolves. const writeAll = async (): Promise => { for (const path of ignored) await writeFile(path, `export default ${Date.now()};\n`).catch(() => {}); await writeFile(source, `export default ${Date.now()};\n`).catch(() => {}); }; const writer = setInterval(() => { void writeAll(); }, 200); try { await writeAll(); await observed; expect(reported).toContain(source); for (const path of ignored) expect(reported).not.toContain(path); } finally { clearInterval(writer); await runtime.close(); } }); it('prefers newer src/*.ts over stale compiled lib/*.js during specifier remap', async () => { const prevCi = process.env.CI; delete process.env.CI; try { const root = await fixture(); const srcTs = join(root, 'src/helper.ts'); const libJs = join(root, 'lib/helper.js'); await mkdir(join(root, 'src'), { recursive: true }); await mkdir(join(root, 'lib'), { recursive: true }); await writeFile(srcTs, "export const v = 'ts';\n"); await writeFile(libJs, "export const v = 'lib';\n"); const parentURL = pathToFileURL(join(root, 'src/index.ts')).href; const nextResolve = async (specifier: string) => { if (specifier === './helper.js') { const err = new Error('Not found') as Error & { code?: string }; err.code = 'ERR_MODULE_NOT_FOUND'; throw err; } return { url: specifier }; }; // When lib/helper.js is newer than src/helper.ts, remap prefers lib/helper.js const baseTime = new Date(2_000_000_000_000); const newerTime = new Date(2_000_000_010_000); await utimes(srcTs, baseTime, baseTime); await utimes(libJs, newerTime, newerTime); const resolvedFromLib = await resolveTypeScriptSpecifier('./helper.js', { parentURL }, nextResolve); expect(resolvedFromLib.url).toBe(pathToFileURL(libJs).href); // When src/helper.ts is edited and becomes newer than lib/helper.js, remap prefers src/helper.ts const newestTime = new Date(2_000_000_020_000); await utimes(srcTs, newestTime, newestTime); const resolvedFromTs = await resolveTypeScriptSpecifier('./helper.js', { parentURL }, nextResolve); expect(resolvedFromTs.url).toBe(pathToFileURL(srcTs).href); // When src/helper.ts contains strip-only incompatible syntax (e.g. enum), remap keeps lib/helper.js await writeFile(srcTs, 'export enum Mode { Fast = 1 }\n'); await utimes(srcTs, newestTime, newestTime); const resolvedEnumFallback = await resolveTypeScriptSpecifier('./helper.js', { parentURL }, nextResolve); expect(resolvedEnumFallback.url).toBe(pathToFileURL(libJs).href); } finally { if (prevCi === undefined) delete process.env.CI; else process.env.CI = prevCi; } }); }); async function fixture(): Promise { const root = await mkdtemp(join(tmpdir(), 'zhin-native-runtime-')); temporary.push(root); await mkdir(join(root, 'commands/status'), { recursive: true }); await writeFile(join(root, 'package.json'), '{"type":"module"}\n'); return realpath(root); }