Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Fail declared guards that read files their declaration omits (#7377)
Nick Gomezb12994766ff4
diff --git a/knip.config.ts b/knip.config.tsindex da29e330e..e04bf5228 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -107,6 +107,8 @@ export default {'.': {entry: ['test-support/fixtures/no-net-connect/no-net-connect.fixture.ts',+ 'test-support/fixtures/read-declarations/vitest.read-declarations-fixture.config.ts',+ 'test-support/fixtures/read-declarations/*.cjs','scripts/check-no-major-changeset.mjs',],vitest: { entry: ['**/*.uncached.test.{ts,tsx,mjs}'] },diff --git a/packages/app/tests/foundation/ownership-run-config.reads.ts b/packages/app/tests/foundation/ownership-run-config.reads.tsindex 744070d49..bb678f913 100644--- a/packages/app/tests/foundation/ownership-run-config.reads.ts+++ b/packages/app/tests/foundation/ownership-run-config.reads.ts@@ -1,19 +1,15 @@-import { OWNER_LIFETIME_READS } from '../meta/port-ownership-lifetime.reads.ts';-export const ROUND_READS = {test: './ownership-run-config.node.test.ts',- reads: 'the nested ownership config and lifetime case, and the modules its run loads',- include: [- 'packages/app/playwright.config.ts',- 'packages/app/tests/stress/_helpers/setup-non-result-reporter.ts',- 'packages/app/tests/stress/_helpers/setup-non-result.ts',+ reads:+ 'the nested ownership config, its lifetime case, global setup, reporter, preloads and the server script they start, with everything they import, and the package and TypeScript configuration its loader reads',+ roots: ['packages/app/tests/stress/_helpers/port-ownership/ownership-run.config.ts','packages/app/tests/stress/_helpers/port-ownership/lifetime.ownership-case.ts','packages/app/tests/stress/_helpers/port-ownership/lifetime-global-setup.ts','packages/app/tests/stress/_helpers/port-ownership/lifetime-server.cjs','packages/app/tests/stress/_helpers/port-ownership/occupy-selected-port.cjs',- 'packages/app/tests/stress/_helpers/port-ownership/owner-scratch-lease.cjs','packages/app/tests/stress/_helpers/port-ownership/owner-scratch-janitor.cjs',- ...OWNER_LIFETIME_READS,+ 'packages/app/tests/stress/_helpers/setup-non-result-reporter.ts',],+ include: ['packages/app/package.json', 'packages/app/tsconfig.json', 'tsconfig.json'],};diff --git a/packages/app/tests/foundation/worker-server-lifetime-ipc.reads.ts b/packages/app/tests/foundation/worker-server-lifetime-ipc.reads.tsindex 9becc1805..3324f4ce3 100644--- a/packages/app/tests/foundation/worker-server-lifetime-ipc.reads.ts+++ b/packages/app/tests/foundation/worker-server-lifetime-ipc.reads.ts@@ -1,13 +1,8 @@export const ROUND_READS = {test: './worker-server-lifetime-ipc.node.test.ts',- reads: 'the lifetime owner and its closure, and the failing send preload its child loads',- include: [- 'packages/app/src/build/test-server-startup-contract.ts',- 'packages/app/tests/free-port.test-helper.ts',- 'packages/app/tests/stress/_helpers/seed-key.ts',- 'packages/app/tests/stress/_helpers/server-process.ts',- 'packages/app/tests/stress/_helpers/teardown-fs.ts',- 'packages/app/tests/stress/_helpers/worker-server-command.ts',+ reads:+ 'the lifetime owner it starts, with everything the owner requires, and the failing send preload its child loads',+ roots: ['packages/app/tests/stress/_helpers/worker-server-lifetime.cjs','packages/app/tests/foundation/worker-lifetime/failing-ipc-send.cjs',],diff --git a/packages/app/tests/meta/port-ownership-lifetime.reads.ts b/packages/app/tests/meta/port-ownership-lifetime.reads.tsindex 0b4dc0f7e..b2ab43b15 100644--- a/packages/app/tests/meta/port-ownership-lifetime.reads.ts+++ b/packages/app/tests/meta/port-ownership-lifetime.reads.ts@@ -1,9 +1,5 @@-export const OWNER_LIFETIME_READS = [- 'packages/app/tests/stress/_helpers/port-ownership/owner-lifetime.cjs',-] as const;-export const ROUND_READS = {test: './port-ownership-lifetime.test.ts',- reads: 'the owner-loss handler module it loads with createRequire',- include: [...OWNER_LIFETIME_READS],+ reads: 'the owner-loss handler module it loads with createRequire, with everything it requires',+ roots: ['packages/app/tests/stress/_helpers/port-ownership/owner-lifetime.cjs'],};diff --git a/packages/app/tests/meta/worker-lifetime-owner-safety.reads.ts b/packages/app/tests/meta/worker-lifetime-owner-safety.reads.tsnew file mode 100644index 000000000..f447db4d4--- /dev/null+++ b/packages/app/tests/meta/worker-lifetime-owner-safety.reads.ts@@ -0,0 +1,12 @@+export const ROUND_READS = {+ test: './worker-lifetime-owner-safety.test.ts',+ reads:+ 'the owner, subject and observer scripts it starts from the worker-lifetime fixtures, with everything they require',+ roots: [+ 'packages/app/tests/foundation/worker-lifetime/process-identity.cjs',+ 'packages/app/tests/foundation/worker-lifetime/resource-owner.cjs',+ 'packages/app/tests/foundation/worker-lifetime/safety-outer-owner.cjs',+ 'packages/app/tests/foundation/worker-lifetime/safety-subject.cjs',+ 'packages/app/tests/foundation/worker-lifetime/startup-observer.cjs',+ ],+};diff --git a/packages/app/tests/meta/worker-server-boot-verdict.reads.ts b/packages/app/tests/meta/worker-server-boot-verdict.reads.tsindex 25205ab71..1e2894625 100644--- a/packages/app/tests/meta/worker-server-boot-verdict.reads.ts+++ b/packages/app/tests/meta/worker-server-boot-verdict.reads.ts@@ -1,13 +1,16 @@-import { FIXTURE_CLOSURE } from './worker-server-budget.reads.ts';-export const ROUND_READS = {test: './worker-server-boot-verdict.test.ts',- reads: 'the nested Playwright config and the static closure of the stress fixture it runs',- include: [- 'packages/app/playwright.config.ts',- ...FIXTURE_CLOSURE,+ reads:+ 'the nested Playwright config and cases with everything they import, the reporter the config names, the worker-server owner the fixture starts, and the package and TypeScript configuration its loader reads',+ roots: ['packages/app/tests/stress/_helpers/boot-verdict/**','packages/app/tests/stress/_helpers/setup-non-result-reporter.ts','packages/app/tests/stress/_helpers/worker-server-lifetime.cjs',],+ include: [+ 'packages/app/package.json',+ 'packages/app/tsconfig.json',+ 'packages/core/tsconfig.json',+ 'tsconfig.json',+ ],};diff --git a/packages/app/tests/meta/worker-server-budget.reads.ts b/packages/app/tests/meta/worker-server-budget.reads.tsindex 59d983e5d..8b1f7c71d 100644--- a/packages/app/tests/meta/worker-server-budget.reads.ts+++ b/packages/app/tests/meta/worker-server-budget.reads.ts@@ -1,36 +1,10 @@-export const FIXTURE_CLOSURE = [- 'packages/app/src/build/e2e-coverage-contract.ts',- 'packages/app/src/build/prebuilt-dev-contract.ts',- 'packages/app/src/build/test-server-loaded-inputs.ts',- 'packages/app/src/build/test-server-startup-contract.ts',- 'packages/app/tests/foundation/test-server-inputs.ts',- 'packages/app/tests/free-port.test-helper.ts',- 'packages/app/tests/stress/_helpers/content-reset.ts',- 'packages/app/tests/stress/_helpers/e2e-coverage/e2e-coverage.ts',- 'packages/app/tests/stress/_helpers/fixtures.ts',- 'packages/app/tests/stress/_helpers/load-progress.ts',- 'packages/app/tests/stress/_helpers/prebuilt/prebuilt-serving.ts',- 'packages/app/tests/stress/_helpers/production-shell-readiness.ts',- 'packages/app/tests/stress/_helpers/production-shell-server.ts',- 'packages/app/tests/stress/_helpers/reuse/fresh-slot.ts',- 'packages/app/tests/stress/_helpers/reuse/lease-fixture.ts',- 'packages/app/tests/stress/_helpers/reuse/lease-protocol.ts',- 'packages/app/tests/stress/_helpers/reuse/reuse-run.ts',- 'packages/app/tests/stress/_helpers/reuse/server-supervisor.ts',- 'packages/app/tests/stress/_helpers/reuse/supervisor-socket.ts',- 'packages/app/tests/stress/_helpers/seed-key.ts',- 'packages/app/tests/stress/_helpers/server-process.ts',- 'packages/app/tests/stress/_helpers/setup-non-result.ts',- 'packages/app/tests/stress/_helpers/teardown-fs.ts',- 'packages/app/tests/stress/_helpers/worker-server-command.ts',- 'packages/app/tests/stress/_helpers/worker-server-lifetime.ts',-] as const;-export const ROUND_READS = {test: './worker-server-budget.test.ts',- reads: 'the static closure of the worker-server fixture loaded by its runtime checks',+ reads:+ 'the worker-server fixture its runtime checks load, with everything it imports, the app package.json and a timeline fixture',+ roots: ['packages/app/tests/stress/_helpers/fixtures.ts'],include: [- ...FIXTURE_CLOSURE,+ 'packages/app/package.json','packages/app/tests/meta/fixtures/first-load-crossing-timeline.json',],};diff --git a/test-support/fixtures/read-declarations/declared.txt b/test-support/fixtures/read-declarations/declared.txtnew file mode 100644index 000000000..718464ced--- /dev/null+++ b/test-support/fixtures/read-declarations/declared.txt@@ -0,0 +1 @@+declareddiff --git a/test-support/fixtures/read-declarations/load-leaf.cjs b/test-support/fixtures/read-declarations/load-leaf.cjsnew file mode 100644index 000000000..021f312d8--- /dev/null+++ b/test-support/fixtures/read-declarations/load-leaf.cjs@@ -0,0 +1 @@+module.exports = { name: 'load-leaf' };diff --git a/test-support/fixtures/read-declarations/load-root.cjs b/test-support/fixtures/read-declarations/load-root.cjsnew file mode 100644index 000000000..0313f7d5c--- /dev/null+++ b/test-support/fixtures/read-declarations/load-root.cjs@@ -0,0 +1,3 @@+const leaf = require('./load-leaf.cjs');++process.stdout.write(`${leaf.name}\n`);diff --git a/test-support/fixtures/read-declarations/open-file.cjs b/test-support/fixtures/read-declarations/open-file.cjsnew file mode 100644index 000000000..7bb316c5e--- /dev/null+++ b/test-support/fixtures/read-declarations/open-file.cjs@@ -0,0 +1,14 @@+const { closeSync, fstatSync, open, readSync } = require('node:fs');++const [path, flags] = process.argv.slice(2);++function printOpened(error, fd) {+ if (error) throw error;+ const bytes = Buffer.alloc(fstatSync(fd).size);+ const length = readSync(fd, bytes, 0, bytes.length, 0);+ closeSync(fd);+ process.stdout.write(bytes.subarray(0, length).toString('utf8'));+}++if (flags === undefined) open(path, printOpened);+else open(path, flags, printOpened);diff --git a/test-support/fixtures/read-declarations/read-file.cjs b/test-support/fixtures/read-declarations/read-file.cjsnew file mode 100644index 000000000..ea75adda9--- /dev/null+++ b/test-support/fixtures/read-declarations/read-file.cjs@@ -0,0 +1,3 @@+const { readFileSync } = require('node:fs');++process.stdout.write(readFileSync(process.argv[2], 'utf8'));diff --git a/test-support/fixtures/read-declarations/undeclared.txt b/test-support/fixtures/read-declarations/undeclared.txtnew file mode 100644index 000000000..5f8d0323b--- /dev/null+++ b/test-support/fixtures/read-declarations/undeclared.txt@@ -0,0 +1 @@+undeclareddiff --git a/test-support/fixtures/read-declarations/vitest.read-declarations-fixture.config.ts b/test-support/fixtures/read-declarations/vitest.read-declarations-fixture.config.tsnew file mode 100644index 000000000..dfd57e2b6--- /dev/null+++ b/test-support/fixtures/read-declarations/vitest.read-declarations-fixture.config.ts@@ -0,0 +1,12 @@+import { defineConfig } from 'vitest/config';+import { okVitestBase } from '../../vitest.base';++export default defineConfig({+ ...okVitestBase,+ test: {+ ...okVitestBase.test,+ globals: true,+ include: ['*.guard.test.mjs'],+ maxWorkers: 1,+ },+});diff --git a/test-support/owner-lifeline.test.ts b/test-support/owner-lifeline.test.tsnew file mode 100644index 000000000..d83418951--- /dev/null+++ b/test-support/owner-lifeline.test.ts@@ -0,0 +1,122 @@+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';+import { fileURLToPath } from 'node:url';+import { describe, expect, test } from 'vitest';+import {+ type CommandResult,+ type HolderSeams,+ holdUntilOwnerLeaves,+ spawnUnderOwnerLifeline,+} from './owner-lifeline';++const OK_ROOT = fileURLToPath(new URL('../', import.meta.url));+const FALLBACK_MS = 20_000;+const LEAKED = 'L';++const announceThenIdle = (ready: string): string =>+ `process.stdout.write(${JSON.stringify(ready)}); setTimeout(() => process.stdout.write(${JSON.stringify(LEAKED)}), ${FALLBACK_MS});`;++const grandchild = (ready: string): string =>+ `require('node:child_process').spawn(process.execPath, ['-e', ${JSON.stringify(announceThenIdle(ready))}], { stdio: 'inherit' })`;++type Finished = { signal: NodeJS.Signals | null; stdout: string };++function recordingSeams(reportStatus: HolderSeams['reportStatus']) {+ const command = new EventEmitter();+ const steps: string[] = [];+ const seams: HolderSeams = {+ startCommand: () => command,+ lifeline: new PassThrough(),+ reportStatus: (result) => {+ steps.push('report');+ reportStatus(result);+ },+ stopGroup: () => {+ steps.push('stop');+ },+ };+ return { command, steps, seams };+}++function childEnv(): NodeJS.ProcessEnv {+ const env: NodeJS.ProcessEnv = { ...process.env };+ delete env.NODE_OPTIONS;+ return env;+}++function finish(+ child: ReturnType<typeof spawnUnderOwnerLifeline>['child'],+ onStdout: (stdout: string) => void = () => {},+): Promise<Finished> {+ return new Promise((resolve, reject) => {+ let stdout = '';+ child.stdout.setEncoding('utf8').on('data', (chunk: string) => {+ stdout += chunk;+ onStdout(stdout);+ });+ child.stderr.resume();+ child.once('error', reject);+ child.once('close', (_code, signal) => resolve({ signal, stdout }));+ });+}++describe('owner lifeline', () => {+ test("reports the command's exit status, then ends its group, when the command ends on its own", async () => {+ const { child, commandResult } = spawnUnderOwnerLifeline(+ process.execPath,+ ['-e', "process.stdout.write('done'); process.exitCode = 3;"],+ { cwd: OK_ROOT, env: childEnv() },+ );+ expect(await finish(child)).toEqual({ signal: 'SIGKILL', stdout: 'done' });+ expect(await commandResult).toEqual({ code: 3, signal: null });+ });++ test('stops a process the command left running when the command ends', async () => {+ const { child, commandResult } = spawnUnderOwnerLifeline(+ process.execPath,+ ['-e', `${grandchild('G')}.unref();`],+ { cwd: OK_ROOT, env: childEnv() },+ );+ const finished = await finish(child);+ expect(finished.signal).toBe('SIGKILL');+ expect(finished.stdout).not.toContain(LEAKED);+ expect(await commandResult).toEqual({ code: 0, signal: null });+ });++ test("stops every process in its group once its owner's end of the lifeline closes", async () => {+ const { child, commandResult } = spawnUnderOwnerLifeline(+ process.execPath,+ ['-e', `${grandchild('G')};\n${announceThenIdle('C')}`],+ { cwd: OK_ROOT, env: childEnv() },+ );+ const finished = await finish(child, (stdout) => {+ if (stdout.includes('G') && stdout.includes('C')) child.stdin.end();+ });+ expect(finished.signal).toBe('SIGKILL');+ expect([...finished.stdout].sort().join('')).toBe('CG');+ expect(await commandResult).toBeNull();+ });+});++describe('owner lifeline holder', () => {+ test("reports the command's status, then stops its group, when the command exits", () => {+ const reported: CommandResult[] = [];+ const { command, steps, seams } = recordingSeams((result) => {+ reported.push(result);+ });+ holdUntilOwnerLeaves('command', [], seams);+ command.emit('exit', 0, null);+ expect(reported).toEqual([{ code: 0, signal: null }]);+ expect(steps).toEqual(['report', 'stop']);+ });++ test("still stops its group when reporting the command's status fails", () => {+ const brokenPipe = Object.assign(new Error('write EPIPE'), { code: 'EPIPE' });+ const { command, steps, seams } = recordingSeams(() => {+ throw brokenPipe;+ });+ holdUntilOwnerLeaves('command', [], seams);+ expect(() => command.emit('exit', 0, null)).toThrow(brokenPipe);+ expect(steps).toEqual(['report', 'stop']);+ });+});diff --git a/test-support/owner-lifeline.ts b/test-support/owner-lifeline.tsnew file mode 100644index 000000000..a3d97ba00--- /dev/null+++ b/test-support/owner-lifeline.ts@@ -0,0 +1,86 @@+import { spawn } from 'node:child_process';+import { realpathSync, writeSync } from 'node:fs';+import type { Readable } from 'node:stream';+import { fileURLToPath, pathToFileURL } from 'node:url';++const LIFELINE = fileURLToPath(import.meta.url);+const STATUS_FD = 3;++export type CommandResult = { code: number | null; signal: NodeJS.Signals | null };++export function spawnUnderOwnerLifeline(+ command: string,+ args: readonly string[],+ options: { cwd: string; env: NodeJS.ProcessEnv },+) {+ const child = spawn(process.execPath, [LIFELINE, command, ...args], {+ ...options,+ detached: true,+ stdio: ['pipe', 'pipe', 'pipe', 'pipe'],+ });+ const statusChannel = child.stdio[STATUS_FD] as Readable;+ const commandResult = new Promise<CommandResult | null>((resolve) => {+ let reported = '';+ statusChannel.setEncoding('utf8').on('data', (chunk: string) => {+ reported += chunk;+ });+ statusChannel.once('end', () => {+ resolve(reported === '' ? null : (JSON.parse(reported) as CommandResult));+ });+ });+ return { child, commandResult };+}++function stopOwnGroup(): void {+ try {+ process.kill(-process.pid, 'SIGKILL');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;+ }+}++type ExitingCommand = {+ once(+ event: 'exit',+ listener: (code: number | null, signal: NodeJS.Signals | null) => void,+ ): unknown;+};++export type HolderSeams = {+ startCommand: (command: string, args: readonly string[]) => ExitingCommand;+ lifeline: Pick<NodeJS.ReadableStream, 'once' | 'resume'>;+ reportStatus: (result: CommandResult) => void;+ stopGroup: () => void;+};++const holderProcessSeams = (): HolderSeams => ({+ startCommand: (command, args) =>+ spawn(command, [...args], { stdio: ['ignore', 'inherit', 'inherit'] }),+ lifeline: process.stdin,+ reportStatus: (result) => {+ writeSync(STATUS_FD, JSON.stringify(result));+ },+ stopGroup: stopOwnGroup,+});++export function holdUntilOwnerLeaves(+ command: string,+ args: readonly string[],+ seams: HolderSeams = holderProcessSeams(),+): void {+ const child = seams.startCommand(command, args);+ seams.lifeline.once('end', seams.stopGroup);+ seams.lifeline.resume();+ child.once('exit', (code, signal) => {+ try {+ seams.reportStatus({ code, signal });+ } finally {+ seams.stopGroup();+ }+ });+}++if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {+ const [command, ...args] = process.argv.slice(2);+ holdUntilOwnerLeaves(command, args);+}diff --git a/test-support/read-declarations-closure.test.ts b/test-support/read-declarations-closure.test.tsnew file mode 100644index 000000000..00c9abfcd--- /dev/null+++ b/test-support/read-declarations-closure.test.ts@@ -0,0 +1,149 @@+import { mkdirSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { afterAll, describe, expect, test } from 'vitest';+import { deriveReadClosure, derivedReads } from './read-declarations-closure';+import { createTempDirFactory } from './temp-dir.test-helper';++const makeTempDir = createTempDirFactory(afterAll);++function tree(files: Record<string, string>): string {+ const root = makeTempDir('ok-read-closure-');+ for (const [path, body] of Object.entries(files)) {+ mkdirSync(dirname(join(root, path)), { recursive: true });+ writeFileSync(join(root, path), body);+ }+ return root;+}++const everyPath = (glob: string, path: string): boolean => glob === path;++describe('what a declared root loads, derived from its module graph', () => {+ test('a root brings in its static imports, re-exports, literal dynamic imports and JSON imports, and no module it reaches only through a computed specifier', () => {+ const root = tree({+ 'start.ts': [+ "import { a } from './a.ts';",+ "export * from './b.ts';",+ "import data from './data.json' with { type: 'json' };",+ "const name = 'computed';",+ "await import('./' + name + '.ts');",+ "await import('./c.ts');",+ 'export const all = [a, data];',+ '',+ ].join('\n'),+ 'a.ts': "import { deep } from './nested/deep.ts';\nexport const a = deep;\n",+ 'nested/deep.ts': 'export const deep = 1;\n',+ 'b.ts': 'export const b = 2;\n',+ 'c.ts': 'export const c = 3;\n',+ 'data.json': '{ "value": 4 }\n',+ 'computed.ts': 'export const computed = 5;\n',+ 'unrelated.ts': 'export const unrelated = 6;\n',+ });+ expect(deriveReadClosure(root, ['start.ts'])).toEqual([+ 'a.ts',+ 'b.ts',+ 'c.ts',+ 'data.json',+ 'nested/deep.ts',+ 'start.ts',+ ]);+ });++ test('a CommonJS root brings in what it requires, through CommonJS and TypeScript modules alike', () => {+ const root = tree({+ 'owner.cjs': "require('./lease.cjs');\nrequire('./server.ts');\n",+ 'lease.cjs': "require('./clock.cjs');\nmodule.exports = {};\n",+ 'clock.cjs': 'module.exports = {};\n',+ 'server.ts': "import { port } from './port.ts';\nexport const server = port;\n",+ 'port.ts': 'export const port = 0;\n',+ });+ expect(deriveReadClosure(root, ['owner.cjs'])).toEqual([+ 'clock.cjs',+ 'lease.cjs',+ 'owner.cjs',+ 'port.ts',+ 'server.ts',+ ]);+ });++ test("a root brings in what it imports through its package's tsconfig path alias, and what that module imports in turn", () => {+ const root = tree({+ 'tsconfig.json': '{ "compilerOptions": { "strict": true } }\n',+ 'packages/app/tsconfig.json': [+ '{',+ ' "extends": "../../tsconfig.json",',+ ' // the editor package',+ ' "compilerOptions": {',+ ' "allowImportingTsExtensions": true,',+ ' "paths": { "@/*": ["./src/*"] }',+ ' }',+ '}',+ '',+ ].join('\n'),+ 'packages/app/tests/start.ts': "import { x } from '@/lib/x.ts';\nexport const seen = x;\n",+ 'packages/app/src/lib/x.ts': "import { y } from './y.ts';\nexport const x = y;\n",+ 'packages/app/src/lib/y.ts': 'export const y = 1;\n',+ 'packages/app/src/lib/unused.ts': 'export const unused = 2;\n',+ });+ expect(deriveReadClosure(root, ['packages/app/tests/start.ts'])).toEqual([+ 'packages/app/src/lib/x.ts',+ 'packages/app/src/lib/y.ts',+ 'packages/app/tests/start.ts',+ ]);+ });++ test('a tsconfig above the tree does not govern a root inside it', () => {+ const outer = tree({+ 'tsconfig.json': '{ "compilerOptions": { "paths": { "@/*": ["./tree/src/*"] } } }\n',+ 'tree/start.ts': "import { x } from '@/x.ts';\nexport const seen = x;\n",+ 'tree/src/x.ts': 'export const x = 1;\n',+ });+ expect(deriveReadClosure(outer, ['tree/start.ts'])).toEqual(['tree/src/x.ts', 'tree/start.ts']);+ expect(deriveReadClosure(join(outer, 'tree'), ['start.ts'])).toEqual(['start.ts']);+ });++ test('compiler options this TypeScript does not know leave the tsconfig path alias in force', () => {+ const root = tree({+ 'tsconfig.json':+ '{ "compilerOptions": { "checkers": 4, "builders": 2, "paths": { "@/*": ["./src/*"] } } }\n',+ 'tests/start.ts': "import { x } from '@/x.ts';\nexport const seen = x;\n",+ 'src/x.ts': 'export const x = 1;\n',+ });+ expect(deriveReadClosure(root, ['tests/start.ts'])).toEqual(['src/x.ts', 'tests/start.ts']);+ });++ test('a root whose tsconfig, or a config that tsconfig extends, cannot be read is refused, naming that tsconfig', () => {+ const root = tree({+ 'truncated/tsconfig.json': '{ "compilerOptions": { "paths": { "@/*": ["./src/*"]\n',+ 'truncated/start.ts': 'export const start = 1;\n',+ 'orphaned/tsconfig.json': '{ "extends": "./missing.json" }\n',+ 'orphaned/start.ts': 'export const start = 2;\n',+ });+ expect(() => deriveReadClosure(root, ['truncated/start.ts'])).toThrow(+ 'truncated/tsconfig.json',+ );+ expect(() => deriveReadClosure(root, ['orphaned/start.ts'])).toThrow('orphaned/tsconfig.json');+ });++ test('the walk stops at node_modules, so a package that imports back into the tree adds nothing', () => {+ const root = tree({+ 'start.mjs': "import 'pkg';\n",+ 'node_modules/pkg/package.json': '{ "name": "pkg", "main": "index.js" }\n',+ 'node_modules/pkg/index.js': "import '../../local.mjs';\n",+ 'local.mjs': 'export const local = 1;\n',+ });+ expect(deriveReadClosure(root, ['start.mjs'])).toEqual(['start.mjs']);+ });++ test('derived reads keep only the files the listing holds, and a root glob that matches none is refused by name', () => {+ const root = tree({+ 'start.mjs': "import './kept.mjs';\nimport './ignored.mjs';\n",+ 'kept.mjs': 'export {};\n',+ 'ignored.mjs': 'export {};\n',+ });+ const listed = new Set(['start.mjs', 'kept.mjs']);+ expect(derivedReads(root, ['start.mjs'], listed, everyPath)).toEqual(['kept.mjs', 'start.mjs']);+ expect(() => derivedReads(root, ['missing.mjs'], listed, everyPath)).toThrow(+ 'the root glob "missing.mjs" matches no file in this tree',+ );+ });+});diff --git a/test-support/read-declarations-closure.ts b/test-support/read-declarations-closure.tsnew file mode 100644index 000000000..042485b96--- /dev/null+++ b/test-support/read-declarations-closure.ts@@ -0,0 +1,139 @@+import { createRequire } from 'node:module';+import { dirname, isAbsolute, join, relative, sep } from 'node:path';+import type { CompilerOptions, Diagnostic, ParseConfigHost } from 'typescript';++type TypeScript = typeof import('typescript');++const IN_NODE_MODULES = /(^|[\\/])node_modules([\\/]|$)/;+const UNKNOWN_COMPILER_OPTION_DIAGNOSTICS: readonly number[] = [5023, 5025];+const NO_INPUTS_FOUND_DIAGNOSTIC = 18003;++let typescript: TypeScript | null = null;++function loadTypeScript(): TypeScript {+ typescript ??= createRequire(import.meta.url)('typescript') as TypeScript;+ return typescript;+}++function treePath(okRoot: string, path: string): string | null {+ const within = relative(okRoot, path);+ if (within === '' || within.startsWith('..') || isAbsolute(within)) return null;+ return within.split(sep).join('/');+}++function fixedOptions(ts: TypeScript): CompilerOptions {+ return {+ allowArbitraryExtensions: true,+ allowImportingTsExtensions: true,+ allowJs: true,+ module: ts.ModuleKind.Preserve,+ moduleResolution: ts.ModuleResolutionKind.Bundler,+ noEmit: true,+ noLib: true,+ preserveSymlinks: true,+ resolveJsonModule: true,+ types: [],+ };+}++function governingConfig(ts: TypeScript, okRoot: string, rootFile: string): string | undefined {+ return ts.findConfigFile(+ dirname(rootFile),+ (file) => treePath(okRoot, file) !== null && ts.sys.fileExists(file),+ );+}++function unreadableConfig(+ ts: TypeScript,+ okRoot: string,+ config: string,+ diagnostics: readonly Diagnostic[],+): Error {+ const messages = diagnostics.map((diagnostic) =>+ ts.flattenDiagnosticMessageText(diagnostic.messageText, ' '),+ );+ return new Error(+ `TypeScript could not read the path mapping of ${treePath(okRoot, config)}: ${messages.join('; ')}`,+ );+}++function pathMapping(ts: TypeScript, okRoot: string, config: string): CompilerOptions {+ const read = ts.readConfigFile(config, ts.sys.readFile);+ if (read.error !== undefined) throw unreadableConfig(ts, okRoot, config, [read.error]);+ const host: ParseConfigHost = {+ useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,+ fileExists: ts.sys.fileExists,+ readFile: ts.sys.readFile,+ readDirectory: () => [],+ };+ const { options, errors } = ts.parseJsonConfigFileContent(+ read.config,+ host,+ dirname(config),+ undefined,+ config,+ );+ const fatal = errors.filter(+ (diagnostic) =>+ diagnostic.code !== NO_INPUTS_FOUND_DIAGNOSTIC &&+ !UNKNOWN_COMPILER_OPTION_DIAGNOSTICS.includes(diagnostic.code),+ );+ if (fatal.length > 0) throw unreadableConfig(ts, okRoot, config, fatal);+ return { paths: options.paths, pathsBasePath: options.pathsBasePath };+}++function programFiles(+ ts: TypeScript,+ okRoot: string,+ rootNames: readonly string[],+ options: CompilerOptions,+): string[] {+ const host = ts.createCompilerHost(options);+ const readSourceFile = host.getSourceFile.bind(host);+ host.getSourceFile = (file, ...rest) =>+ IN_NODE_MODULES.test(file) ? undefined : readSourceFile(file, ...rest);+ const files: string[] = [];+ for (const source of ts.createProgram({ rootNames, options, host }).getSourceFiles()) {+ if (IN_NODE_MODULES.test(source.fileName)) continue;+ const within = treePath(okRoot, source.fileName);+ if (within !== null) files.push(within);+ }+ return files;+}++export function deriveReadClosure(okRoot: string, roots: readonly string[]): string[] {+ if (roots.length === 0) return [];+ const ts = loadTypeScript();+ const byConfig = new Map<string | undefined, string[]>();+ for (const root of roots) {+ const rootFile = join(okRoot, root);+ const config = governingConfig(ts, okRoot, rootFile);+ byConfig.set(config, [...(byConfig.get(config) ?? []), rootFile]);+ }+ const files = new Set<string>();+ for (const [config, rootNames] of byConfig) {+ const options =+ config === undefined+ ? fixedOptions(ts)+ : { ...fixedOptions(ts), ...pathMapping(ts, okRoot, config) };+ for (const file of programFiles(ts, okRoot, rootNames, options)) files.add(file);+ }+ return [...files].sort();+}++export function derivedReads(+ okRoot: string,+ roots: readonly string[],+ listed: ReadonlySet<string>,+ matches: (glob: string, path: string) => boolean,+): string[] {+ const files: string[] = [];+ for (const root of roots) {+ const matched = [...listed].filter((path) => matches(root, path));+ if (matched.length === 0) {+ throw new Error(`the root glob ${JSON.stringify(root)} matches no file in this tree`);+ }+ files.push(...matched);+ }+ return deriveReadClosure(okRoot, [...new Set(files)].sort()).filter((path) => listed.has(path));+}diff --git a/test-support/read-declarations-match.ts b/test-support/read-declarations-match.tsnew file mode 100644index 000000000..031aa4e83--- /dev/null+++ b/test-support/read-declarations-match.ts@@ -0,0 +1,69 @@+export type ReadDeclaration = {+ readonly include: readonly string[];+ readonly exclude?: readonly string[];+};++const GLOB_PATTERNS = new Map<string, RegExp>();++function segmentPattern(segment: string): string {+ let pattern = '';+ for (const character of segment) {+ if (character === '*') pattern += '[^/]*';+ else if (character === '?') pattern += '[^/]';+ else pattern += character.replace(/[.+^${}()|[\]\\]/g, '\\$&');+ }+ return pattern;+}++function globMatches(glob: string, path: string): boolean {+ let pattern = GLOB_PATTERNS.get(glob);+ if (pattern === undefined) {+ const segments = glob.split('/');+ let source = '^';+ for (let index = 0; index < segments.length; index += 1) {+ const last = index === segments.length - 1;+ if (segments[index] === '**') source += last ? '.*' : '(?:[^/]+/)*';+ else source += segmentPattern(segments[index]) + (last ? '' : '/');+ }+ pattern = new RegExp(`${source}$`);+ GLOB_PATTERNS.set(glob, pattern);+ }+ return pattern.test(path);+}++function expandBraces(glob: string): string[] | null {+ const open = glob.indexOf('{');+ if (open === -1) return [glob];+ const close = glob.indexOf('}', open);+ if (close === -1) return null;+ const body = glob.slice(open + 1, close);+ if (body.includes('{')) return null;+ const rest = expandBraces(glob.slice(close + 1));+ if (rest === null) return null;+ return body+ .split(',')+ .flatMap((option) => rest.map((tail) => glob.slice(0, open) + option + tail));+}++function matchesAny(globs: readonly string[], path: string): boolean {+ return globs.some((glob) => {+ const variants = expandBraces(glob);+ if (variants === null) {+ throw new Error(+ `The read declaration glob ${JSON.stringify(glob)} has a nested or unterminated brace alternation.`,+ );+ }+ return variants.some((variant) => globMatches(variant, path));+ });+}++export function withDerivedReads(+ declaration: ReadDeclaration,+ derived: readonly string[],+): ReadDeclaration {+ return { ...declaration, include: [...new Set([...declaration.include, ...derived])] };+}++export function declares(declaration: ReadDeclaration, path: string): boolean {+ return matchesAny(declaration.include, path) && !matchesAny(declaration.exclude ?? [], path);+}diff --git a/test-support/read-declarations-observer.ts b/test-support/read-declarations-observer.tsnew file mode 100644index 000000000..67a8dfbac--- /dev/null+++ b/test-support/read-declarations-observer.ts@@ -0,0 +1,181 @@+import { Buffer } from 'node:buffer';+import childProcess from 'node:child_process';+import fs from 'node:fs';+import { registerHooks, syncBuiltinESMExports } from 'node:module';+import { join, resolve, sep } from 'node:path';+import { fileURLToPath, pathToFileURL, URL } from 'node:url';+import { promisify } from 'node:util';++export const READ_LOG_ENV = 'OK_READ_DECLARATION_LOG';+export const READ_ROOT_ENV = 'OK_READ_DECLARATION_ROOT';++const OBSERVER_IMPORT = `--import=${pathToFileURL(fileURLToPath(import.meta.url)).href}`;+const INSTALLED = Symbol.for('ok.test.readDeclarations.observerInstalled');++const openLog = fs.openSync;+const closeLog = fs.closeSync;+const writeLog = fs.writeSync;++type Log = { dir: string; fd: number; seen: Set<string> };+let log: Log | null = null;++function openLogFile(path: string): number {+ try {+ return openLog(path, 'a');+ } catch (cause) {+ throw new Error(+ `The read-declaration observer could not open ${path}, the log ${READ_LOG_ENV} names for this process, so the files this process reads could not be checked against its read declaration.`,+ { cause },+ );+ }+}++function logFor(dir: string): Log {+ if (log?.dir === dir) return log;+ const fd = openLogFile(join(dir, `${process.pid}.log`));+ if (log !== null) closeLog(log.fd);+ log = { dir, fd, seen: new Set() };+ return log;+}++function note(path: string | null): void {+ const dir = process.env[READ_LOG_ENV];+ const root = process.env[READ_ROOT_ENV];+ if (!dir || !root || path === null) return;+ if (!path.startsWith(`${root}${sep}`) || path.includes(`${sep}node_modules${sep}`)) return;+ const current = logFor(dir);+ if (current.seen.has(path)) return;+ current.seen.add(path);+ writeLog(current.fd, `${path}\n`);+}++function fsPath(target: unknown): string | null {+ if (typeof target === 'string') return resolve(target);+ if (target instanceof URL) return target.protocol === 'file:' ? fileURLToPath(target) : null;+ if (Buffer.isBuffer(target)) return resolve(target.toString());+ return null;+}++const { O_CREAT, O_EXCL, O_TRUNC, O_WRONLY } = fs.constants;+const CREATES_EXCLUSIVELY = O_CREAT | O_EXCL;+const READING_FLAG = /[r+]/;+const TRUNCATING_OR_EXCLUSIVE_FLAG = /[wx]/;++function opensForRead(flags: unknown): boolean {+ if (flags === undefined || flags === null || typeof flags === 'function') return true;+ if (typeof flags === 'string') {+ return READING_FLAG.test(flags) && !TRUNCATING_OR_EXCLUSIVE_FLAG.test(flags);+ }+ if (typeof flags === 'number') {+ return (+ (flags & 3) !== O_WRONLY &&+ (flags & O_TRUNC) === 0 &&+ (flags & CREATES_EXCLUSIVELY) !== CREATES_EXCLUSIVELY+ );+ }+ return false;+}++type Callable = (this: unknown, ...args: unknown[]) => unknown;++function replace(target: object, name: string, make: (original: Callable) => Callable): void {+ const host = target as Record<string, unknown>;+ const original = host[name];+ if (typeof original !== 'function') return;+ const wrapped = make(original as Callable);+ for (const key of Reflect.ownKeys(original)) {+ if (key === 'length' || key === 'name' || key === 'prototype') continue;+ const descriptor = Reflect.getOwnPropertyDescriptor(original, key);+ if (descriptor === undefined) continue;+ if (key === promisify.custom) descriptor.value = make(descriptor.value);+ Reflect.defineProperty(wrapped, key, descriptor);+ }+ Reflect.defineProperty(wrapped, 'name', { value: original.name });+ host[name] = wrapped;+}++function observeRead(target: object, name: string, pick: (args: unknown[]) => unknown): void {+ replace(+ target,+ name,+ (original) =>+ function (this: unknown, ...args: unknown[]) {+ note(fsPath(pick(args)));+ return original.apply(this, args);+ },+ );+}++export function observerNodeOptions(current: string | undefined): string {+ const options = current ?? '';+ return options.includes(OBSERVER_IMPORT) ? options : `${options} ${OBSERVER_IMPORT}`.trim();+}++function withObserver(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {+ const dir = process.env[READ_LOG_ENV];+ const root = process.env[READ_ROOT_ENV];+ if (!dir || !root) return env;+ return {+ ...env,+ [READ_LOG_ENV]: dir,+ [READ_ROOT_ENV]: root,+ NODE_OPTIONS: observerNodeOptions(env.NODE_OPTIONS),+ };+}++function observeSpawner(name: string, takesArgs: boolean): void {+ replace(+ childProcess,+ name,+ (original) =>+ function (this: unknown, ...args: unknown[]) {+ const at = takesArgs && Array.isArray(args[1]) ? 2 : 1;+ const options = args[at];+ if (options !== null && typeof options === 'object' && 'env' in options) {+ const env = (options as { env?: NodeJS.ProcessEnv }).env;+ if (env !== undefined && env !== null) args[at] = { ...options, env: withObserver(env) };+ }+ return original.apply(this, args);+ },+ );+}++export function installReadObserver(logDir: string): void {+ logFor(logDir);+ const state = globalThis as typeof globalThis & { [INSTALLED]?: true };+ if (state[INSTALLED] === true) return;+ state[INSTALLED] = true;++ const first = (args: unknown[]) => args[0];+ const readOpen = (args: unknown[]) => (opensForRead(args[1]) ? args[0] : null);+ for (const name of [+ 'readFileSync',+ 'readFile',+ 'createReadStream',+ 'copyFileSync',+ 'copyFile',+ 'cpSync',+ 'cp',+ ]) {+ observeRead(fs, name, first);+ }+ for (const name of ['openSync', 'open']) observeRead(fs, name, readOpen);+ for (const name of ['readFile', 'copyFile', 'cp']) observeRead(fs.promises, name, first);+ observeRead(fs.promises, 'open', readOpen);++ for (const name of ['spawn', 'spawnSync', 'execFile', 'execFileSync', 'fork'])+ observeSpawner(name, true);+ for (const name of ['exec', 'execSync']) observeSpawner(name, false);+ syncBuiltinESMExports();++ registerHooks({+ resolve(specifier, context, nextResolve) {+ const resolved = nextResolve(specifier, context);+ if (resolved.url.startsWith('file:')) note(fileURLToPath(resolved.url));+ return resolved;+ },+ });+}++const inheritedLogDir = process.env[READ_LOG_ENV];+if (inheritedLogDir && process.env[READ_ROOT_ENV]) installReadObserver(inheritedLogDir);diff --git a/test-support/read-declarations.ts b/test-support/read-declarations.tsnew file mode 100644index 000000000..f14c7a04b--- /dev/null+++ b/test-support/read-declarations.ts@@ -0,0 +1,201 @@+import childProcess from 'node:child_process';+import {+ type Dirent,+ existsSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ realpathSync,+ rmSync,+ statSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import {+ basename,+ dirname,+ isAbsolute,+ join,+ matchesGlob,+ relative,+ resolve,+ sep,+} from 'node:path';+import { fileURLToPath } from 'node:url';+import { aroundAll, expect } from 'vitest';+import { derivedReads } from './read-declarations-closure';+import { declares, type ReadDeclaration, withDerivedReads } from './read-declarations-match';+import {+ installReadObserver,+ observerNodeOptions,+ READ_LOG_ENV,+ READ_ROOT_ENV,+} from './read-declarations-observer';++const runGit = childProcess.spawnSync;+const OK_ROOT = realpathSync(join(dirname(fileURLToPath(import.meta.url)), '..'));+const DECLARATION_MODULE = /\.reads\.(?:ts|mjs)$/;+const LISTING_BUFFER_BYTES = 256 * 1024 * 1024;+const PUBLIC_TREE_OMITS = '*.private.*';+const UNWALKED_DIRECTORIES = new Set(['.git', 'node_modules']);++type Declared = { module: string; declaration: ReadDeclaration; roots: string[] };++function isGlobList(value: unknown): value is string[] {+ return Array.isArray(value) && value.every((glob) => typeof glob === 'string');+}++function display(path: string): string {+ const within = relative(OK_ROOT, path);+ return within.startsWith('..') || isAbsolute(within) ? path : within.split(sep).join('/');+}++function entriesOf(dir: string): Dirent[] {+ try {+ return readdirSync(dir, { withFileTypes: true });+ } catch (error) {+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return [];+ throw error;+ }+}++function holdsOnDiskAFileThePublicTreeOmits(): boolean {+ const pending = [OK_ROOT];+ for (const dir of pending) {+ for (const entry of entriesOf(dir)) {+ if (entry.isFile() && matchesGlob(entry.name, PUBLIC_TREE_OMITS)) return true;+ if (entry.isDirectory() && !UNWALKED_DIRECTORIES.has(entry.name)) {+ pending.push(join(dir, entry.name));+ }+ }+ }+ return false;+}++function holdsAPathThePublicTreeOmits(): boolean {+ const listed = runGit('git', ['ls-files', '-z', '--', PUBLIC_TREE_OMITS], {+ cwd: OK_ROOT,+ encoding: 'utf8',+ maxBuffer: LISTING_BUFFER_BYTES,+ });+ if (listed.error === undefined && listed.status === 0) return listed.stdout !== '';+ return holdsOnDiskAFileThePublicTreeOmits();+}++async function declarationFor(testPath: string): Promise<Declared | null> {+ const dir = dirname(testPath);+ const testName = basename(testPath);+ const candidates = readdirSync(dir)+ .filter(+ (entry) =>+ DECLARATION_MODULE.test(entry) &&+ testName.startsWith(`${entry.replace(DECLARATION_MODULE, '')}.`),+ )+ .sort();+ if (candidates.length === 0 || !holdsAPathThePublicTreeOmits()) return null;+ for (const name of candidates) {+ const module = join(dir, name);+ const loaded = (await import(module)) as {+ ROUND_READS?: { test?: unknown; include?: unknown; exclude?: unknown; roots?: unknown };+ };+ const declared = loaded.ROUND_READS;+ if (typeof declared?.test !== 'string' || resolve(dir, declared.test) !== testPath) continue;+ const { include = [], exclude = [], roots = [] } = declared;+ if (!isGlobList(include) || !isGlobList(exclude) || !isGlobList(roots)) {+ throw new Error(+ `The read declaration ${display(module)} names ${display(testPath)} but its include, exclude or roots is not a list of globs.`,+ );+ }+ return { module, declaration: { include, exclude }, roots };+ }+ return null;+}++function listedPaths(): Set<string> {+ const listed = runGit('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], {+ cwd: OK_ROOT,+ encoding: 'utf8',+ maxBuffer: LISTING_BUFFER_BYTES,+ });+ if (listed.error !== undefined || listed.status !== 0) {+ throw new Error(+ `git ls-files could not list the files under ${OK_ROOT} (${listed.error?.message ?? listed.stderr.trim()}), so no read declaration can be checked.`,+ );+ }+ return new Set(listed.stdout.split('\0').filter((path) => path !== ''));+}++function undeclaredReads(declared: Declared, logDir: string, testPath: string): string[] {+ const read = new Set<string>();+ for (const name of readdirSync(logDir)) {+ for (const line of readFileSync(join(logDir, name), 'utf8').split('\n')) {+ if (line !== '') read.add(line);+ }+ }+ const listed = listedPaths();+ const coverage = withDerivedReads(+ declared.declaration,+ derivedReads(OK_ROOT, declared.roots, listed, (glob, path) =>+ declares({ include: [glob] }, path),+ ),+ );+ const exempt = new Set([display(testPath), display(declared.module)]);+ const undeclared = new Set<string>();+ const judge = (path: string): void => {+ if (listed.has(path) && !exempt.has(path) && !declares(coverage, path)) undeclared.add(path);+ };+ for (const path of read) {+ const real = existsSync(path) ? realpathSync(path) : path;+ const within = relative(OK_ROOT, real);+ if (within === '' || within.startsWith('..') || isAbsolute(within)) continue;+ const okPath = within.split(sep).join('/');+ if (existsSync(real) && statSync(real).isDirectory()) {+ for (const entry of listed) if (entry.startsWith(`${okPath}/`)) judge(entry);+ } else {+ judge(okPath);+ }+ }+ return [...undeclared].sort();+}++function undeclaredFailure(declared: Declared, testPath: string, undeclared: string[]): Error {+ const declaration = display(declared.module);+ return new Error(+ [+ `${display(testPath)} read ${undeclared.length} tracked file(s) at run time that its read declaration ${declaration} does not list, so a change to one of them would not select it:`,+ ...undeclared.map((path) => ` ${path}`),+ `List each path, or a glob covering it, in ROUND_READS.include of ${declaration}; a module the run loads by path goes in ROUND_READS.roots instead, which also covers what it imports.`,+ ].join('\n'),+ );+}++const testPath = expect.getState().testPath;+const declared = testPath === undefined ? null : await declarationFor(testPath);++if (testPath !== undefined && declared !== null) {+ const logDir = mkdtempSync(join(tmpdir(), 'ok-read-declaration-'));+ const saved = [READ_LOG_ENV, READ_ROOT_ENV, 'NODE_OPTIONS'].map(+ (name) => [name, process.env[name]] as const,+ );+ process.env[READ_ROOT_ENV] = OK_ROOT;+ process.env[READ_LOG_ENV] = logDir;+ process.env.NODE_OPTIONS = observerNodeOptions(process.env.NODE_OPTIONS);+ installReadObserver(logDir);+ process.once('exit', () => rmSync(logDir, { recursive: true, force: true }));++ aroundAll(async (runSuite) => {+ try {+ await runSuite();+ } finally {+ for (const [name, value] of saved) {+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }+ }+ try {+ const undeclared = undeclaredReads(declared, logDir, testPath);+ if (undeclared.length > 0) throw undeclaredFailure(declared, testPath, undeclared);+ } finally {+ rmSync(logDir, { recursive: true, force: true });+ }+ });+}diff --git a/test-support/setup-files-contract.test.ts b/test-support/setup-files-contract.test.tsindex 78ac92046..408df0080 100644--- a/test-support/setup-files-contract.test.ts+++ b/test-support/setup-files-contract.test.ts@@ -39,6 +39,7 @@ const KNOWN_TEST_PROJECTS = ['packages/server/vitest.mcp-inspector.config.ts','packages/server/vitest.network.config.ts','test-support/fixtures/no-net-connect/vitest.no-net-connect-fixture.config.ts',+ 'test-support/fixtures/read-declarations/vitest.read-declarations-fixture.config.ts','vitest.scripts.config.ts','vitest.uncached.config.ts',];@@ -54,7 +55,7 @@ const KNOWN_BUILD_CONFIGS = ['packages/desktop/electron.vite.config.ts',];-const REQUIRED_BASE_SETUP_FILES = ['bun-global-shim.ts', 'no-net-connect.ts'];+const REQUIRED_BASE_SETUP_FILES = ['bun-global-shim.ts', 'no-net-connect.ts', 'read-declarations.ts'];const BROWSER_PROJECT_SETUP_FILES: Readonly<Record<string, readonly string[]>> = {'packages/app/tests/foundation/fixtures/vitest.browser-fixture.config.ts': ['browser-setup.ts'],diff --git a/test-support/tsconfig.no-net-connect.json b/test-support/tsconfig.no-net-connect.jsonindex 5d125a40f..c170ba911 100644--- a/test-support/tsconfig.no-net-connect.json+++ b/test-support/tsconfig.no-net-connect.json@@ -7,6 +7,13 @@},"include": ["no-net-connect*.ts",+ "owner-lifeline.ts",+ "owner-lifeline.test.ts",+ "read-declarations.ts",+ "read-declarations-closure.ts",+ "read-declarations-match.ts",+ "read-declarations-observer.ts",+ "read-declarations*.test.ts","turbo-typecheck-attachment.test.ts","fixtures/no-net-connect/**/*.ts"]diff --git a/test-support/vitest.base.ts b/test-support/vitest.base.tsindex 1b9626da2..bc65a3720 100644--- a/test-support/vitest.base.ts+++ b/test-support/vitest.base.ts@@ -25,6 +25,8 @@ const bunGlobalShimPath = fileURLToPath(new URL('./bun-global-shim.ts', import.mconst noNetConnectPath = fileURLToPath(new URL('./no-net-connect.ts', import.meta.url));+const readDeclarationsPath = fileURLToPath(new URL('./read-declarations.ts', import.meta.url));+export const okVitestBase = {plugins: [importMetaDirPlugin, vitestRunEvidence()],resolve: {@@ -55,7 +57,7 @@ export const okVitestBase = {'A flaky test declared skipped with an issue, an owner and an expiry; listed by pnpm known-reds.',},],- setupFiles: [bunGlobalShimPath, noNetConnectPath],+ setupFiles: [bunGlobalShimPath, noNetConnectPath, readDeclarationsPath],include: ['**/*.test.ts?(x)'],exclude: [...configDefaults.exclude,