Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Add the OK browser and Node test tiers with an E2E reuse foundation (#5726)
Nick Gomezd7a7584c9bda
diff --git a/packages/app/package.json b/packages/app/package.jsonindex 4124671ff..95d5518a6 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -25,6 +25,8 @@"format": "biome check --write .","test": "vitest run --config vitest.config.ts src/","test:dom": "vitest run --config vitest.dom.config.ts",+ "test:browser": "vitest run --config vitest.browser.config.ts",+ "test:node": "vitest run --config vitest.node.config.ts","check": "tsc --noEmit && biome check . && pnpm run test && pnpm run test:dom && pnpm run test:integration && pnpm run test:conversion && pnpm -w run test:uncached","test:integration": "vitest run --config vitest.integration.config.ts","test:integration:shard1": "vitest run --config vitest.integration.config.ts --shard=1/3",@@ -208,6 +210,7 @@"@types/react-dom": "^19.2.3","@types/ws": "^8.18.1","@vitejs/plugin-react": "^6.0.1",+ "@vitest/browser-playwright": "^5.0.3","axe-core": "~4.12.1","babel-plugin-react-compiler": "0.0.0-experimental-a8e64ef-20260402","commonmark.json": "0.31.0",diff --git a/packages/app/tests/foundation/api-routes.test-helper.ts b/packages/app/tests/foundation/api-routes.test-helper.tsnew file mode 100644index 000000000..515476b49--- /dev/null+++ b/packages/app/tests/foundation/api-routes.test-helper.ts@@ -0,0 +1,19 @@+import { vi } from 'vitest';++type ApiRoute = (url: URL) => Response;++export function stubApiRoutes(routes: Readonly<Record<string, ApiRoute>>): void {+ const passthrough = globalThis.fetch;+ vi.stubGlobal(+ 'fetch',+ async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {+ const url = new URL(input instanceof Request ? input.url : String(input), location.href);+ const route = routes[url.pathname];+ if (route) return route(url);+ if (url.pathname.startsWith('/api/')) {+ throw new Error(`the test stubs no response for ${url.pathname}`);+ }+ return passthrough(input, init);+ },+ );+}diff --git a/packages/app/tests/foundation/browser-engine.browser.test.tsx b/packages/app/tests/foundation/browser-engine.browser.test.tsxnew file mode 100644index 000000000..aaffb2e5b--- /dev/null+++ b/packages/app/tests/foundation/browser-engine.browser.test.tsx@@ -0,0 +1,50 @@+import { render } from '@testing-library/react';+import { describe, expect, test, vi } from 'vitest';+import { Button } from '@/components/ui/button';++describe('the browser tier exposes the engine, with two Node-shaped names', () => {+ test('global names the same object as globalThis', () => {+ expect(global).toBe(globalThis);+ });++ test('assigning localStorage keeps the engine Storage object', () => {+ const engineStorage = localStorage;++ globalThis.localStorage = window.localStorage;++ expect(localStorage).toBe(engineStorage);+ expect(Object.getPrototypeOf(localStorage)).toBe(Storage.prototype);+ localStorage.setItem('round-trip', 'kept');+ expect(window.localStorage.getItem('round-trip')).toBe('kept');+ });++ test('platform APIs are the engine implementations, not emulator stand-ins', () => {+ expect(Function.prototype.toString.call(ResizeObserver)).toContain('[native code]');+ expect(window.matchMedia('(min-width: 1px)').matches).toBe(true);+ expect(navigator.userAgent).toContain('HeadlessChrome');+ });++ test('the engine lays out a row of real icon buttons from production CSS', () => {+ const view = render(+ <div data-testid="row" className="inline-flex gap-2">+ <Button size="icon" aria-label="first" />+ <Button size="icon" aria-label="second" />+ <Button size="icon" aria-label="third" />+ </div>,+ );++ const first = view.getByRole('button', { name: 'first' }).getBoundingClientRect();+ const third = view.getByRole('button', { name: 'third' }).getBoundingClientRect();+ expect([first.width, first.height]).toEqual([32, 32]);+ expect(third.left - first.left).toBe(80);+ expect(view.getByTestId('row').getBoundingClientRect().width).toBe(112);+ });++ test('vi.resetModules does not reload an ES module in the browser, so the next import returns the same instance', async () => {+ const first = await import('./fixtures/mock-subject');++ vi.resetModules();++ expect(await import('./fixtures/mock-subject')).toBe(first);+ });+});diff --git a/packages/app/tests/foundation/browser-fixture-command.ts b/packages/app/tests/foundation/browser-fixture-command.tsnew file mode 100644index 000000000..2c4931f6c--- /dev/null+++ b/packages/app/tests/foundation/browser-fixture-command.ts@@ -0,0 +1,79 @@+import { execFile } from 'node:child_process';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrowserCommand } from 'vitest/node';+import {+ APP_ROOT,+ type BrowserFixtureFile,+ type BrowserFixtureRequest,+ type BrowserFixtureRun,+ fixtureDeadlineMs,+ fixtureEnv,+ fixtureFilePaths,+ fixtureRunArguments,+ parseFixtureReport,+ unfinishedRunMessage,+} from './browser-fixture-run';+import { NESTED_RUN_STOP_GRACE_MS } from './nested-run-budget';++const OUTPUT_LIMIT_BYTES = 16 * 1024 * 1024;++function readReport(path: string): BrowserFixtureFile[] | null {+ let text: string;+ try {+ text = readFileSync(path, 'utf8');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw error;+ }+ return parseFixtureReport(text);+}++export const runBrowserFixture: BrowserCommand<[BrowserFixtureRequest]> = (_context, request) => {+ const filePaths = fixtureFilePaths(request.files);+ const deadlineMs = fixtureDeadlineMs(request);+ const reportDir = mkdtempSync(join(tmpdir(), 'ok-browser-fixture-'));+ const reportPath = join(reportDir, 'report.json');+ return new Promise<BrowserFixtureRun>((resolveRun, rejectRun) => {+ let stopped = false;+ let deadline: NodeJS.Timeout | undefined;+ let forcedStop: NodeJS.Timeout | undefined;+ const child = execFile(+ process.execPath,+ fixtureRunArguments(filePaths, reportPath),+ {+ cwd: APP_ROOT,+ env: fixtureEnv(request, process.env, join(reportDir, 'node_modules', '.vite')),+ maxBuffer: OUTPUT_LIMIT_BYTES,+ },+ (error, stdout, stderr) => {+ clearTimeout(deadline);+ clearTimeout(forcedStop);+ try {+ if (stopped) {+ rejectRun(+ new Error(unfinishedRunMessage(request.files, deadlineMs, { stdout, stderr })),+ );+ return;+ }+ resolveRun({+ exitCode: typeof error?.code === 'number' ? error.code : error ? null : 0,+ files: readReport(reportPath),+ stdout,+ stderr,+ });+ } catch (failure) {+ rejectRun(failure);+ } finally {+ rmSync(reportDir, { recursive: true, force: true });+ }+ },+ );+ deadline = setTimeout(() => {+ stopped = true;+ child.kill('SIGTERM');+ forcedStop = setTimeout(() => child.kill('SIGKILL'), NESTED_RUN_STOP_GRACE_MS);+ }, deadlineMs);+ });+};diff --git a/packages/app/tests/foundation/browser-fixture-run.ts b/packages/app/tests/foundation/browser-fixture-run.tsnew file mode 100644index 000000000..bb56b114e--- /dev/null+++ b/packages/app/tests/foundation/browser-fixture-run.ts@@ -0,0 +1,138 @@+import { dirname, join, relative, resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';+import { NESTED_RUN_DEADLINE_MS } from './nested-run-budget';++export const BROWSER_FIXTURE_ORDER_ENV = 'OK_BROWSER_FIXTURE_ORDER';+export const BROWSER_FIXTURE_CACHE_DIR_ENV = 'OK_BROWSER_FIXTURE_CACHE_DIR';++export type BrowserFixtureRequest = {+ readonly files: readonly string[];+ readonly ci?: string;+ readonly debugGc?: boolean;+ readonly deadlineMs?: number;+};++type BrowserFixtureTestStatus = 'passed' | 'failed' | 'skipped' | 'pending' | 'todo';++type BrowserFixtureTest = {+ readonly title: string;+ readonly status: BrowserFixtureTestStatus;+ readonly failureMessages: readonly string[];+};++export type BrowserFixtureFile = {+ readonly file: string;+ readonly status: string;+ readonly message: string;+ readonly tests: readonly BrowserFixtureTest[];+};++export type BrowserFixtureRun = {+ readonly exitCode: number | null;+ readonly files: readonly BrowserFixtureFile[] | null;+ readonly stdout: string;+ readonly stderr: string;+};++declare module 'vitest/browser' {+ interface BrowserCommands {+ runBrowserFixture: (request: BrowserFixtureRequest) => Promise<BrowserFixtureRun>;+ }+}++export const APP_ROOT = fileURLToPath(new URL('../../', import.meta.url));+const FIXTURE_DIR = fileURLToPath(new URL('./fixtures/', import.meta.url));+const FIXTURE_CONFIG = join(FIXTURE_DIR, 'vitest.browser-fixture.config.ts');+const VITEST_CLI = resolve(+ dirname(fileURLToPath(import.meta.resolve('vitest/package.json'))),+ 'vitest.mjs',+);+const FIXTURE_FILE = /^[\w-]+(?:\.[\w-]+)*\.fixture\.tsx?$/;++export function fixtureFilePaths(files: readonly string[]): string[] {+ if (files.length === 0 || files.some((file) => !FIXTURE_FILE.test(file))) {+ throw new Error(`runBrowserFixture takes fixture file names only, got ${files.join(', ')}`);+ }+ return files.map((file) => join(FIXTURE_DIR, file));+}++export function fixtureDeadlineMs(request: BrowserFixtureRequest): number {+ const { deadlineMs = NESTED_RUN_DEADLINE_MS } = request;+ if (!Number.isInteger(deadlineMs) || deadlineMs <= 0 || deadlineMs > NESTED_RUN_DEADLINE_MS) {+ throw new Error(+ `runBrowserFixture takes a deadline of 1 to ${NESTED_RUN_DEADLINE_MS} ms, got ${deadlineMs}`,+ );+ }+ return deadlineMs;+}++const UNFINISHED_RUN_OUTPUT_LINES = 30;++export function unfinishedRunMessage(+ files: readonly string[],+ deadlineMs: number,+ output: { readonly stdout: string; readonly stderr: string },+): string {+ const lastLines = `${output.stdout}\n${output.stderr}`+ .split('\n')+ .filter((line) => line.trim() !== '')+ .slice(-UNFINISHED_RUN_OUTPUT_LINES);+ return [+ `The nested browser fixture run of ${files.join(', ')} did not finish within ${deadlineMs} ms, so it was stopped. Its last output:`,+ ...(lastLines.length > 0 ? lastLines : ['(none)']),+ ].join('\n');+}++export function fixtureRunArguments(filePaths: readonly string[], reportPath: string): string[] {+ return [+ VITEST_CLI,+ 'run',+ '--config',+ FIXTURE_CONFIG,+ '--reporter=default',+ '--reporter=json',+ `--outputFile.json=${reportPath}`,+ ...filePaths,+ ];+}++export function fixtureEnv(+ request: BrowserFixtureRequest,+ inherited: NodeJS.ProcessEnv,+ cacheDir: string,+): NodeJS.ProcessEnv {+ const { CI: _ci, DEBUG: _debug, ...env } = inherited;+ return {+ ...env,+ FORCE_COLOR: '0',+ NO_COLOR: '1',+ [BROWSER_FIXTURE_ORDER_ENV]: request.files.join(','),+ [BROWSER_FIXTURE_CACHE_DIR_ENV]: cacheDir,+ ...(request.ci === undefined ? {} : { CI: request.ci }),+ ...(request.debugGc ? { DEBUG: 'vitest:browser:gc' } : {}),+ };+}++type JsonAssertion = { title: string; status: BrowserFixtureTestStatus; failureMessages: string[] };+type JsonFile = {+ name: string;+ status: string;+ message: string;+ assertionResults: JsonAssertion[];+};++export function parseFixtureReport(text: string): BrowserFixtureFile[] {+ const report = JSON.parse(text) as { testResults: JsonFile[] };+ return report.testResults+ .map((file) => ({+ file: relative(FIXTURE_DIR, file.name).split(sep).join('/'),+ status: file.status,+ message: file.message,+ tests: file.assertionResults.map(({ title, status, failureMessages }) => ({+ title,+ status,+ failureMessages,+ })),+ }))+ .sort((left, right) => left.file.localeCompare(right.file));+}diff --git a/packages/app/tests/foundation/browser-globals.ts b/packages/app/tests/foundation/browser-globals.tsnew file mode 100644index 000000000..d35361531--- /dev/null+++ b/packages/app/tests/foundation/browser-globals.ts@@ -0,0 +1,13 @@+Object.defineProperty(globalThis, 'global', {+ value: globalThis,+ writable: true,+ configurable: true,+ enumerable: false,+});++Object.defineProperty(globalThis, 'localStorage', {+ value: globalThis.localStorage,+ writable: true,+ configurable: true,+ enumerable: true,+});diff --git a/packages/app/tests/foundation/browser-isolation.browser.test.ts b/packages/app/tests/foundation/browser-isolation.browser.test.tsnew file mode 100644index 000000000..42c951fff--- /dev/null+++ b/packages/app/tests/foundation/browser-isolation.browser.test.ts@@ -0,0 +1,185 @@+import { describe, expect, test } from 'vitest';+import { commands } from 'vitest/browser';+import type { BrowserFixtureFile } from './browser-fixture-run';+import { NESTED_RUN_DEADLINE_MS, NESTED_RUN_TIMEOUT_MS } from './nested-run-budget';++const REJECTED_FACTORY_ERROR =+ 'vi.mock factory for /tests/foundation/fixtures/mock-subject.ts rejected';++function verdicts(files: readonly BrowserFixtureFile[] | null) {+ return files?.map(({ file, status, tests }) => ({+ file,+ status,+ tests: tests.map(({ title, status: testStatus }) => [title, testStatus]),+ }));+}++describe('the browser tier keeps one file failure inside that file', {+ timeout: NESTED_RUN_TIMEOUT_MS,+}, () => {+ test('a vi.mock factory that rejects fails only its own file, and the files after it still run', async () => {+ const run = await commands.runBrowserFixture({+ files: [+ 'rejected-factory.fixture.ts',+ 'rejected-import-observed.fixture.ts',+ 'unrelated-neighbor.fixture.ts',+ ],+ });++ expect(verdicts(run.files)).toEqual([+ { file: 'rejected-factory.fixture.ts', status: 'failed', tests: [] },+ {+ file: 'rejected-import-observed.fixture.ts',+ status: 'passed',+ tests: [+ ['a test that expects its mocked import to reject observes the rejection', 'passed'],+ ],+ },+ {+ file: 'unrelated-neighbor.fixture.ts',+ status: 'passed',+ tests: [['an unrelated file imports the real module', 'passed']],+ },+ ]);+ expect(run.files?.[0]?.message).toContain('Failed to import test file');+ expect(`${run.stdout}${run.stderr}`).toContain(+ `Caused by: Error: ${REJECTED_FACTORY_ERROR}: [vitest] There was an error when mocking a module.`,+ );+ expect(run.exitCode).toBe(1);+ });+});++describe('the browser tier reads CI from its launch environment', {+ timeout: NESTED_RUN_TIMEOUT_MS,+}, () => {+ const SET = 'the browser graph reads CI as set, with no Node process global';+ const UNSET = 'the browser graph reads CI as unset, with no Node process global';++ test('a launch without CI reads as local', async () => {+ const run = await commands.runBrowserFixture({ files: ['ci-mode.fixture.ts'] });++ expect(verdicts(run.files)).toEqual([+ {+ file: 'ci-mode.fixture.ts',+ status: 'failed',+ tests: [+ [SET, 'failed'],+ [UNSET, 'passed'],+ ],+ },+ ]);+ });++ test('a launch with CI=true reads as CI', async () => {+ const run = await commands.runBrowserFixture({ files: ['ci-mode.fixture.ts'], ci: 'true' });++ expect(verdicts(run.files)).toEqual([+ {+ file: 'ci-mode.fixture.ts',+ status: 'failed',+ tests: [+ [SET, 'passed'],+ [UNSET, 'failed'],+ ],+ },+ ]);+ });+});++describe('each browser test file starts with clean storage', {+ timeout: NESTED_RUN_TIMEOUT_MS,+}, () => {+ const POISON = 'storage-poison.fixture.ts';+ const WITNESS = 'storage-witness.fixture.ts';+ const passing = {+ [POISON]: {+ file: POISON,+ status: 'passed',+ tests: [['a file writes web storage and leaves an IndexedDB connection open', 'passed']],+ },+ [WITNESS]: {+ file: WITNESS,+ status: 'passed',+ tests: [['a file starts with empty web storage and no IndexedDB databases', 'passed']],+ },+ };++ test('storage the first file writes is gone when the second file starts', async () => {+ const run = await commands.runBrowserFixture({ files: [POISON, WITNESS] });++ expect(verdicts(run.files)).toEqual([passing[POISON], passing[WITNESS]]);+ expect(run.exitCode).toBe(0);+ });++ test('the same two files pass in the reverse order', async () => {+ const run = await commands.runBrowserFixture({ files: [WITNESS, POISON] });++ expect(verdicts(run.files)).toEqual([passing[POISON], passing[WITNESS]]);+ expect(run.exitCode).toBe(0);+ });++ test('Vitest collects Chromium garbage after every file when launched with the documented settings', async () => {+ const run = await commands.runBrowserFixture({ files: [POISON, WITNESS], debugGc: true });++ expect(run.exitCode).toBe(0);+ expect(run.stderr.match(/Vitest triggered Chromium garbage collection/g)).toHaveLength(2);+ expect(run.stderr).not.toContain('failed to collect Chromium garbage');+ });++ test('an IndexedDB database that cannot be deleted after a test fails that test', async () => {+ const run = await commands.runBrowserFixture({ files: ['storage-blocked.fixture.ts'] });++ expect(verdicts(run.files)).toEqual([+ {+ file: 'storage-blocked.fixture.ts',+ status: 'failed',+ tests: [['a database a worker keeps open cannot be deleted after the test', 'failed']],+ },+ ]);+ expect(run.files?.[0]?.tests[0]?.failureMessages.join('\n')).toContain(+ 'IndexedDB held-by-worker could not be deleted: a connection outside this test file is still open',+ );+ });+});++describe('test-side node: substitutes keep unsupported operations failing', {+ timeout: NESTED_RUN_TIMEOUT_MS,+}, () => {+ test('a file importing a node:fs export the browser tier does not provide fails at import', async () => {+ const run = await commands.runBrowserFixture({ files: ['unsupported-node-export.fixture.ts'] });++ expect(verdicts(run.files)).toEqual([+ { file: 'unsupported-node-export.fixture.ts', status: 'failed', tests: [] },+ ]);+ expect(`${run.stdout}${run.stderr}`).toContain("does not provide an export named 'watch'");+ });+});++describe('the nested fixture run', { timeout: NESTED_RUN_TIMEOUT_MS }, () => {+ test('refuses a file name that is not a fixture in the fixture directory', async () => {+ await expect(+ commands.runBrowserFixture({ files: ['../browser-isolation.browser.test.ts'] }),+ ).rejects.toThrow('runBrowserFixture takes fixture file names only');+ });++ test('refuses a deadline longer than the shared nested-run budget', async () => {+ await expect(+ commands.runBrowserFixture({+ files: ['never-settles.fixture.ts'],+ deadlineMs: NESTED_RUN_DEADLINE_MS + 1,+ }),+ ).rejects.toThrow(+ `runBrowserFixture takes a deadline of 1 to ${NESTED_RUN_DEADLINE_MS} ms, got ${NESTED_RUN_DEADLINE_MS + 1}`,+ );+ });++ test('stops a run that does not finish by its deadline and fails naming that run', async () => {+ const deadlineMs = 3_000;++ await expect(+ commands.runBrowserFixture({ files: ['never-settles.fixture.ts'], deadlineMs }),+ ).rejects.toThrow(+ `The nested browser fixture run of never-settles.fixture.ts did not finish within ${deadlineMs} ms, so it was stopped. Its last output:\n`,+ );+ });+});diff --git a/packages/app/tests/foundation/browser-mock-provider.ts b/packages/app/tests/foundation/browser-mock-provider.tsnew file mode 100644index 000000000..4d23e2607--- /dev/null+++ b/packages/app/tests/foundation/browser-mock-provider.ts@@ -0,0 +1,141 @@+import {+ PlaywrightBrowserProvider,+ type PlaywrightProviderOptions,+} from '@vitest/browser-playwright';+import type { BrowserContext } from 'playwright';+import { parseSync, type ViteDevServer } from 'vite';+import type { BrowserModuleMocker, BrowserProviderOption, TestProject } from 'vitest/node';++type MockedModule = Parameters<BrowserModuleMocker['register']>[1];+type ManualMockedModule = Extract<MockedModule, { type: 'manual' }>;+type RouteHandler = Parameters<BrowserContext['route']>[1];++const CAUSE_DEPTH = 8;++type ErrorLike = { message?: unknown; cause?: unknown };++function errorChain(error: unknown): string {+ const messages: string[] = [];+ let current: unknown = error;+ while (current !== undefined && current !== null && messages.length < CAUSE_DEPTH) {+ const { message, cause } = (typeof current === 'object' ? current : {}) as ErrorLike;+ messages.push(typeof message === 'string' ? message : String(current));+ current = cause;+ }+ return messages.join(' <- caused by: ');+}++const REJECTED_BINDING = '__okRejectedMockBinding';++function rejectedMockModuleSource(+ pathname: string,+ exportNames: ReadonlySet<string>,+ error: unknown,+): string {+ const message = `vi.mock factory for ${pathname} rejected: ${errorChain(error)}`;+ const exported = [...exportNames]+ .map((name) => `${REJECTED_BINDING} as ${JSON.stringify(name)}`)+ .join(', ');+ return [+ `throw new Error(${JSON.stringify(message)});`,+ `let ${REJECTED_BINDING};`,+ `export { ${exported} };`,+ '',+ ].join('\n');+}++function answerRejectedFactories(handler: RouteHandler, vite: ViteDevServer): RouteHandler {+ return async (route, request) => {+ try {+ return await handler(route, request);+ } catch (error) {+ const { pathname } = new URL(request.url());+ await route.fulfill({+ headers: moduleResponseHeaders(vite),+ body: rejectedMockModuleSource(pathname, await moduleExportNames(vite, pathname), error),+ });+ }+ };+}++const guardedContexts = new WeakSet<BrowserContext>();++function guardMockRoutes(context: BrowserContext, vite: ViteDevServer): void {+ if (guardedContexts.has(context)) return;+ guardedContexts.add(context);+ const route = context.route.bind(context);+ context.route = (url, handler, options) =>+ route(url, answerRejectedFactories(handler, vite), options);+}++async function moduleExportNames(+ vite: ViteDevServer,+ url: string,+ seen: Set<string> = new Set(),+): Promise<Set<string>> {+ const names = new Set<string>();+ if (seen.has(url)) return names;+ seen.add(url);+ const transformed = await vite.environments.client.transformRequest(url);+ if (transformed === null) return names;+ const { module } = parseSync('module.js', transformed.code, { lang: 'js', sourceType: 'module' });+ for (const { entries } of module.staticExports) {+ for (const { exportName, importName, moduleRequest } of entries) {+ if (exportName.kind === 'Default') names.add('default');+ if (exportName.kind === 'Name' && exportName.name !== null) names.add(exportName.name);+ if (exportName.kind === 'None' && importName.kind === 'AllButDefault' && moduleRequest) {+ for (const reexported of await moduleExportNames(vite, moduleRequest.value, seen)) {+ if (reexported !== 'default') names.add(reexported);+ }+ }+ }+ }+ return names;+}++function completeFactoryExports(vite: ViteDevServer, module: ManualMockedModule): void {+ const resolve = module.resolve.bind(module);+ module.resolve = async () => {+ const exports = await resolve();+ const missing = [...(await moduleExportNames(vite, module.url))].filter(+ (name) => !Object.hasOwn(exports, name),+ );+ return { ...Object.fromEntries(missing.map((name) => [name, undefined])), ...exports };+ };+}++function viteOf(project: TestProject): ViteDevServer {+ const vite = project.browser?.vite;+ if (vite === undefined) throw new Error(`${project.name} has no browser Vite server`);+ return vite;+}++function moduleResponseHeaders(vite: ViteDevServer): Record<string, string> {+ const headers: Record<string, string> = { 'Content-Type': 'application/javascript' };+ for (const [name, value] of Object.entries(vite.config.server.headers ?? {})) {+ headers[name] = String(value);+ }+ return headers;+}++export function withMockContracts(+ base: BrowserProviderOption<PlaywrightProviderOptions>,+): BrowserProviderOption<PlaywrightProviderOptions> {+ return {+ ...base,+ providerFactory(project) {+ const provider = base.providerFactory(project);+ if (!(provider instanceof PlaywrightBrowserProvider)) {+ throw new Error('withMockContracts wraps only the Playwright provider');+ }+ const register = provider.mocker.register;+ provider.mocker.register = async (sessionId, module) => {+ const vite = viteOf(project);+ guardMockRoutes(provider.getPage(sessionId).context(), vite);+ if (module.type === 'manual') completeFactoryExports(vite, module);+ return register(sessionId, module);+ };+ return provider;+ },+ };+}diff --git a/packages/app/tests/foundation/browser-network-check.ts b/packages/app/tests/foundation/browser-network-check.tsnew file mode 100644index 000000000..de0392b3b--- /dev/null+++ b/packages/app/tests/foundation/browser-network-check.ts@@ -0,0 +1,16 @@+import { afterAll, afterEach } from 'vitest';+import { commands } from 'vitest/browser';++await commands.installNetworkGuard();++async function failOnBlockedRequests(when: string): Promise<void> {+ const blocked = await commands.takeBlockedNetworkRequests();+ if (blocked.length > 0) {+ throw new Error(+ `The browser tier reaches only loopback hosts, and ${when} requested ${blocked.join(', ')}. Fake the dependency at its seam, or serve it from the test server.`,+ );+ }+}++afterEach(() => failOnBlockedRequests('this test'));+afterAll(() => failOnBlockedRequests('this file, after its last test,'));diff --git a/packages/app/tests/foundation/browser-network-guard.ts b/packages/app/tests/foundation/browser-network-guard.tsnew file mode 100644index 000000000..4daec0750--- /dev/null+++ b/packages/app/tests/foundation/browser-network-guard.ts@@ -0,0 +1,37 @@+import type { BrowserContext } from 'playwright';+import type { BrowserCommand } from 'vitest/node';+import { isLoopbackHostname } from '../../../../test-support/no-net-connect-loopback';++declare module 'vitest/browser' {+ interface BrowserCommands {+ installNetworkGuard: () => Promise<void>;+ takeBlockedNetworkRequests: () => Promise<string[]>;+ }+}++function leavesLoopback(url: URL): boolean {+ return (+ (url.protocol === 'http:' || url.protocol === 'https:') && !isLoopbackHostname(url.hostname)+ );+}++const guardedContexts = new WeakSet<BrowserContext>();+const blockedBySession = new Map<string, string[]>();++export const installNetworkGuard: BrowserCommand<[]> = async ({ context, sessionId }) => {+ if (guardedContexts.has(context)) return;+ guardedContexts.add(context);+ await context.route(leavesLoopback, async (route) => {+ blockedBySession.set(sessionId, [+ ...(blockedBySession.get(sessionId) ?? []),+ route.request().url(),+ ]);+ await route.abort('blockedbyclient');+ });+};++export const takeBlockedNetworkRequests: BrowserCommand<[]> = ({ sessionId }) => {+ const blocked = blockedBySession.get(sessionId) ?? [];+ blockedBySession.delete(sessionId);+ return blocked;+};diff --git a/packages/app/tests/foundation/browser-node-compat.ts b/packages/app/tests/foundation/browser-node-compat.tsnew file mode 100644index 000000000..ceffe48fd--- /dev/null+++ b/packages/app/tests/foundation/browser-node-compat.ts@@ -0,0 +1,154 @@+import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';+import { EOL, tmpdir } from 'node:os';+import { isAbsolute, join, resolve, sep } from 'node:path';+import { fileURLToPath } from 'node:url';+import type { Plugin } from 'vite';+import { type BridgeHostFacts, FILE_BRIDGE_ROUTE } from './node-substitutes/file-bridge-contract';++export const NODE_MODULES = /[/\\]node_modules[/\\]/;++export const BROWSER_TEST_MODULES: readonly RegExp[] = [+ /\.(?:test|test-helper)\.[cm]?[jt]sx?(?:$|\?)/,+ /[/\\]packages[/\\]app[/\\]tests[/\\]/,+ /[/\\]packages[/\\]app[/\\]src[/\\]test-utils[/\\]/,+ /[/\\]test-support[/\\]/,+];++export const BROWSER_PRODUCT_MODULE_EXCLUDES: readonly RegExp[] = [+ NODE_MODULES,+ ...BROWSER_TEST_MODULES,+];++function isBrowserTestModule(id: string): boolean {+ return !NODE_MODULES.test(id) && BROWSER_TEST_MODULES.some((pattern) => pattern.test(id));+}++const CI_READ = /\bprocess\.env\.CI\b(?![\w$])/g;++export function browserCiValue(env: Readonly<Record<string, string | undefined>>): Plugin {+ const literal = env.CI === undefined ? 'undefined' : JSON.stringify(env.CI);+ return {+ name: 'ok-browser-ci-value',+ enforce: 'pre',+ transform(code, id) {+ if (!isBrowserTestModule(id) || !code.includes('process.env.CI')) return null;+ return { code: code.replace(CI_READ, literal), map: null };+ },+ };+}++const SUBSTITUTED_NODE_MODULE = /^node:(crypto|fs|os|path|process|url)$/;+const SUBSTITUTE_DIR = fileURLToPath(new URL('./node-substitutes/', import.meta.url));++export function nodeSubstituteFor(source: string, importer: string | undefined): string | null {+ const module = SUBSTITUTED_NODE_MODULE.exec(source)?.[1];+ if (module === undefined || importer === undefined || !isBrowserTestModule(importer)) return null;+ return join(SUBSTITUTE_DIR, `${module}.ts`);+}++export type BridgePathResolution =+ | { readonly ok: true; readonly path: string }+ | { readonly ok: false; readonly status: 400 | 403; readonly reason: string };++function realpathOrSelf(path: string): string {+ try {+ return realpathSync(path);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return path;+ throw error;+ }+}++function within(path: string, roots: readonly string[]): boolean {+ return roots.some((root) => path === root || path.startsWith(`${root}${sep}`));+}++export function resolveBridgePath(+ requested: string,+ roots: readonly string[],+): BridgePathResolution {+ if (!isAbsolute(requested)) {+ return { ok: false, status: 400, reason: `EINVAL: ${requested} is not an absolute path` };+ }+ if (requested.split(/[/\\]/).includes('..')) {+ return { ok: false, status: 403, reason: `EACCES: ${requested}: path traversal is refused` };+ }+ const declared = roots.map((root) => resolve(root));+ const path = resolve(requested);+ if (!within(path, declared)) {+ return { ok: false, status: 403, reason: `EACCES: ${requested} is outside the declared roots` };+ }+ const real = realpathOrSelf(path);+ if (!within(real, declared.map(realpathOrSelf))) {+ return {+ ok: false,+ status: 403,+ reason: `EACCES: ${requested} resolves through a symlink outside the declared roots`,+ };+ }+ return { ok: true, path: real };+}++type BridgeResponse = { readonly status: number; readonly body: string };++function answerFileBridge(+ operation: string | null,+ requested: string,+ roots: readonly string[],+ facts: BridgeHostFacts,+): BridgeResponse {+ if (operation === 'host') return { status: 200, body: JSON.stringify(facts) };+ if (operation !== 'read' && operation !== 'exists' && operation !== 'readdir') {+ return { status: 400, body: `EINVAL: unknown file bridge operation ${operation}` };+ }+ const resolved = resolveBridgePath(requested, roots);+ if (!resolved.ok) return { status: resolved.status, body: resolved.reason };+ if (operation === 'exists') return { status: 200, body: String(existsSync(resolved.path)) };+ try {+ return {+ status: 200,+ body:+ operation === 'read'+ ? readFileSync(resolved.path, 'utf8')+ : JSON.stringify(readdirSync(resolved.path)),+ };+ } catch (error) {+ const { code, message } = error as NodeJS.ErrnoException;+ if (code === undefined) throw error;+ return { status: code === 'ENOENT' ? 404 : 500, body: message };+ }+}++export function browserNodeSubstitutes(roots: readonly string[]): Plugin {+ return {+ name: 'ok-browser-node-substitutes',+ enforce: 'pre',+ resolveId(source, importer) {+ return nodeSubstituteFor(source, importer);+ },+ configureServer(server) {+ const facts: BridgeHostFacts = {+ cwd: server.config.root,+ platform: process.platform,+ tmpdir: tmpdir(),+ eol: EOL,+ ci: process.env.CI ?? null,+ };+ server.middlewares.use(FILE_BRIDGE_ROUTE, (request, response) => {+ const url = new URL(request.url ?? '/', 'http://file-bridge');+ const { status, body } =+ request.method === 'GET'+ ? answerFileBridge(+ url.searchParams.get('op'),+ url.searchParams.get('path') ?? '',+ roots,+ facts,+ )+ : { status: 405, body: 'EINVAL: the file bridge answers GET only' };+ response.statusCode = status;+ response.setHeader('Content-Type', 'text/plain; charset=utf-8');+ response.end(body);+ });+ },+ };+}diff --git a/packages/app/tests/foundation/browser-setup.ts b/packages/app/tests/foundation/browser-setup.tsnew file mode 100644index 000000000..cf4f8729f--- /dev/null+++ b/packages/app/tests/foundation/browser-setup.ts@@ -0,0 +1,15 @@+import './browser-globals';+import '@fontsource-variable/inter';+import '@fontsource-variable/jetbrains-mono';+import 'react-medium-image-zoom/dist/styles.css';+import 'katex/dist/katex.min.css';+import '@/globals.css';+import '@/lib/i18n';+import './browser-storage-lifecycle';+import './browser-network-check';+import { cleanup } from '@testing-library/react';+import { afterEach } from 'vitest';++afterEach(() => {+ cleanup();+});diff --git a/packages/app/tests/foundation/browser-storage-lifecycle.ts b/packages/app/tests/foundation/browser-storage-lifecycle.tsnew file mode 100644index 000000000..476ebb4a9--- /dev/null+++ b/packages/app/tests/foundation/browser-storage-lifecycle.ts@@ -0,0 +1,45 @@+import { afterEach } from 'vitest';++const openConnections = new Set<IDBDatabase>();+const openDatabase = IDBFactory.prototype.open;++IDBFactory.prototype.open = function trackedOpen(+ this: IDBFactory,+ ...args: Parameters<IDBFactory['open']>+): IDBOpenDBRequest {+ const request = openDatabase.apply(this, args);+ request.addEventListener('success', () => {+ openConnections.add(request.result);+ });+ return request;+};++function deleteDatabase(name: string): Promise<void> {+ return new Promise((resolve, reject) => {+ const request = indexedDB.deleteDatabase(name);+ request.onsuccess = () => resolve();+ request.onerror = () =>+ reject(new Error(`IndexedDB ${name} could not be deleted`, { cause: request.error }));+ request.onblocked = () =>+ reject(+ new Error(+ `IndexedDB ${name} could not be deleted: a connection outside this test file is still open`,+ ),+ );+ });+}++async function deleteAllDatabases(): Promise<void> {+ for (const connection of openConnections) connection.close();+ openConnections.clear();+ const databases = await indexedDB.databases();+ await Promise.all(+ databases.flatMap(({ name }) => (name === undefined ? [] : [deleteDatabase(name)])),+ );+}++localStorage.clear();+sessionStorage.clear();+await deleteAllDatabases();++afterEach(deleteAllDatabases);diff --git a/packages/app/tests/foundation/chromium-gc-launch-env.ts b/packages/app/tests/foundation/chromium-gc-launch-env.tsnew file mode 100644index 000000000..72caeea9a--- /dev/null+++ b/packages/app/tests/foundation/chromium-gc-launch-env.ts@@ -0,0 +1,63 @@+import { statfsSync } from 'node:fs';+import type { Plugin } from 'vite';++export const CHROMIUM_GC_THRESHOLD_ENV = 'VITEST_CHROMIUM_GC_DISK_THRESHOLD_GB';+export const CHROMIUM_GC_FORCE_ENV = 'VITEST_CHROMIUM_GC_FORCE';++export const BROWSER_TIER_COMMAND =+ 'env VITEST_CHROMIUM_GC_DISK_THRESHOLD_GB=100000 VITEST_CHROMIUM_GC_FORCE=1 pnpm --dir packages/app run test:browser';++const BYTES_PER_GB = 1024 ** 3;++export type ChromiumGcLaunchEnv =+ | { readonly ok: true; readonly thresholdBytes: number }+ | { readonly ok: false; readonly problems: readonly string[] };++export function readChromiumGcLaunchEnv(+ env: Readonly<Record<string, string | undefined>>,+ availableTempBytes: number,+): ChromiumGcLaunchEnv {+ const problems: string[] = [];+ const rawThreshold = env[CHROMIUM_GC_THRESHOLD_ENV];+ const thresholdGb = rawThreshold === undefined ? Number.NaN : Number(rawThreshold);+ const thresholdBytes = thresholdGb * BYTES_PER_GB;+ if (rawThreshold === undefined) {+ problems.push(`${CHROMIUM_GC_THRESHOLD_ENV} is not set`);+ } else if (!Number.isFinite(thresholdGb) || thresholdGb <= 0) {+ problems.push(`${CHROMIUM_GC_THRESHOLD_ENV}=${rawThreshold} is not a positive number of GB`);+ } else if (thresholdBytes <= availableTempBytes) {+ problems.push(+ `${CHROMIUM_GC_THRESHOLD_ENV}=${rawThreshold} does not exceed the ${(availableTempBytes / BYTES_PER_GB).toFixed(1)} GB free in the temp directory, so Vitest would skip the collection after each file`,+ );+ }+ const force = env[CHROMIUM_GC_FORCE_ENV];+ if (force === undefined) {+ problems.push(`${CHROMIUM_GC_FORCE_ENV} is not set`);+ } else if (force !== '1') {+ problems.push(`${CHROMIUM_GC_FORCE_ENV}=${force} is not 1`);+ }+ return problems.length === 0 ? { ok: true, thresholdBytes } : { ok: false, problems };+}++export function describeChromiumGcLaunchRefusal(problems: readonly string[]): string {+ return [+ 'The browser tier refuses to start: Vitest reads its Chromium memory controls when it is imported, so they must be in the launch environment.',+ ...problems.map((problem) => ` - ${problem}`),+ `Run it as: ${BROWSER_TIER_COMMAND}`,+ ].join('\n');+}++function availableTempBytes(): number {+ const stats = statfsSync(process.env.TMPDIR || '/tmp');+ return stats.bavail * stats.bsize;+}++export function chromiumGcLaunchEnvGuard(): Plugin {+ return {+ name: 'ok:chromium-gc-launch-env',+ config() {+ const launch = readChromiumGcLaunchEnv(process.env, availableTempBytes());+ if (!launch.ok) throw new Error(describeChromiumGcLaunchRefusal(launch.problems));+ },+ };+}diff --git a/packages/app/tests/foundation/compiled-destination.browser.test.tsx b/packages/app/tests/foundation/compiled-destination.browser.test.tsxnew file mode 100644index 000000000..48015d68f--- /dev/null+++ b/packages/app/tests/foundation/compiled-destination.browser.test.tsx@@ -0,0 +1,67 @@+import { act, render } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { useRef } from 'react';+import { afterEach, describe, expect, test } from 'vitest';+import { ChangedOutsideBadge } from '@/components/ChangedOutsideBadge';+import { useFindInViewer } from '@/hooks/use-find-in-viewer';+import { dynamicActivate } from '@/lib/activate-locale';+import { renderWithI18n } from './render-with-i18n.test-helper';++type FindState = ReturnType<typeof useFindInViewer>;++function FindProbe({ pass, seen }: { pass: number; seen: FindState[] }) {+ const rootRef = useRef<HTMLDivElement>(null);+ seen.push(useFindInViewer(rootRef));+ return (+ <div ref={rootRef} data-pass={pass}>+ <button type="button">inside the viewer</button>+ </div>+ );+}++describe('the compiled browser destination', () => {+ afterEach(async () => {+ await act(() => dynamicActivate('en'));+ });++ test('a product hook compiled by the React Compiler returns the same object across a re-render that leaves its state unchanged', () => {+ const seen: FindState[] = [];+ const view = render(<FindProbe pass={0} seen={seen} />);+ view.rerender(<FindProbe pass={1} seen={seen} />);++ expect(seen).toHaveLength(2);+ expect(seen[1]?.findOpen).toBe(false);+ expect(seen[1]).toBe(seen[0]);+ });++ test('Ctrl+F inside the viewer opens find, and the compiled hook then returns a new object carrying it', async () => {+ const seen: FindState[] = [];+ const view = render(<FindProbe pass={0} seen={seen} />);+ const before = seen.at(-1);++ await userEvent.click(view.getByRole('button', { name: 'inside the viewer' }));+ await userEvent.keyboard('{Control>}f{/Control}');++ const after = seen.at(-1);+ expect(after?.findOpen).toBe(true);+ expect(after).not.toBe(before);+ });++ test('a product component renders its string from the real English catalog and from the real Spanish catalog once Spanish activates', async () => {+ const view = renderWithI18n(<ChangedOutsideBadge testId="changed-outside" />);+ const badge = view.getByTestId('changed-outside');+ expect(badge.textContent).toBe('changed outside');++ await act(() => dynamicActivate('es'));++ expect(badge.textContent).toBe('modificado fuera');+ });++ test('production CSS lays the component out in the real engine', () => {+ const view = renderWithI18n(<ChangedOutsideBadge testId="changed-outside" />);+ const badge = view.getByTestId('changed-outside');++ expect(getComputedStyle(badge).display).toBe('inline-flex');+ expect(badge.getBoundingClientRect().height).toBe(20);+ });+});diff --git a/packages/app/tests/foundation/custom-theme-editor.browser.test.tsx b/packages/app/tests/foundation/custom-theme-editor.browser.test.tsxnew file mode 100644index 000000000..5b91df513--- /dev/null+++ b/packages/app/tests/foundation/custom-theme-editor.browser.test.tsx@@ -0,0 +1,123 @@+import {+ bindConfigDoc,+ type ConfigBinding,+} from '@inkeep/open-knowledge-core/config/bind-config-doc';+import { type RenderResult, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import * as Y from 'yjs';+import { CustomThemeEditor } from '@/components/settings/CustomThemeEditor';+import { SavedThemesProvider } from '@/lib/saved-themes-client';+import { expectKnownBug } from '../../../../test-support/known-bug.vitest.test-helper';+import { stubApiRoutes } from './api-routes.test-helper';+import { renderWithI18n } from './render-with-i18n.test-helper';++const PASTED_SCHEME = `system: "base16"+name: "Ayu Dark"+author: "A. Scheme Author"+variant: "dark"+palette:+ base00: "#0f1419"+ base01: "#131721"+ base02: "#272d38"+ base03: "#3e4b59"+ base04: "#bfbdb6"+ base05: "#e6e1cf"+ base06: "#e6e1cf"+ base07: "#f3f4f5"+ base08: "#f07178"+ base09: "#ff8f40"+ base0A: "#ffb454"+ base0B: "#b8cc52"+ base0C: "#95e6cb"+ base0D: "#59c2ff"+ base0E: "#d2a6ff"+ base0F: "#e6b673"+`;++function inMemoryUserConfig(): ConfigBinding {+ return bindConfigDoc(+ { document: new Y.Doc(), on: (_event, synced) => synced(), off: () => {} },+ 'user',+ );+}++async function renderEditor(binding: ConfigBinding): Promise<RenderResult> {+ const view = renderWithI18n(+ <SavedThemesProvider>+ <CustomThemeEditor userBinding={binding} />+ </SavedThemesProvider>,+ );+ await waitFor(() => {+ expect(view.getByTestId('custom-theme-import')).toBeTruthy();+ });+ return view;+}++async function pasteIntoImport(view: RenderResult, text: string): Promise<void> {+ await userEvent.click(view.getByTestId('custom-theme-import'));+ await userEvent.paste(text);+}++describe('CustomThemeEditor under the real Lingui runtime', () => {+ beforeEach(() => {+ stubApiRoutes({+ '/api/saved-themes': () => Response.json({ themes: [], truncated: false }),+ });+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ test('importing a valid pasted scheme writes all sixteen slots and its metadata, and announces the import', async () => {+ const binding = inMemoryUserConfig();+ const view = await renderEditor(binding);++ await pasteIntoImport(view, PASTED_SCHEME);++ expect(binding.current().appearance?.customTheme).toEqual({+ name: 'Ayu Dark',+ author: 'A. Scheme Author',+ variant: 'dark',+ base00: '#0f1419',+ base01: '#131721',+ base02: '#272d38',+ base03: '#3e4b59',+ base04: '#bfbdb6',+ base05: '#e6e1cf',+ base06: '#e6e1cf',+ base07: '#f3f4f5',+ base08: '#f07178',+ base09: '#ff8f40',+ base0A: '#ffb454',+ base0B: '#b8cc52',+ base0C: '#95e6cb',+ base0D: '#59c2ff',+ base0E: '#d2a6ff',+ base0F: '#e6b673',+ });+ expect(view.getByRole('status').textContent).toBe('Theme imported.');+ });++ test('an unparseable paste shows a translated inline error and writes nothing', {+ tags: ['known-bug'],+ meta: {+ issue: 'https://github.com/inkeep/agents-private/issues/5612',+ owner: 'get-main-green',+ until: '2026-12-31',+ },+ }, async () => {+ const binding = inMemoryUserConfig();+ const view = await renderEditor(binding);++ await pasteIntoImport(view, 'not a scheme');++ await expectKnownBug(/expected undefined to be 'That parsed, but it isn’t a base16 th/, () => {+ expect(view.queryByTestId('custom-theme-import-error')?.textContent).toBe(+ 'That parsed, but it isn’t a base16 theme.',+ );+ });+ expect(binding.current().appearance?.customTheme).toBeUndefined();+ });+});diff --git a/packages/app/tests/foundation/fixtures/bridge-readable.txt b/packages/app/tests/foundation/fixtures/bridge-readable.txtnew file mode 100644index 000000000..6c461e36a--- /dev/null+++ b/packages/app/tests/foundation/fixtures/bridge-readable.txt@@ -0,0 +1 @@+readable through the file bridgediff --git a/packages/app/tests/foundation/fixtures/ci-mode.fixture.ts b/packages/app/tests/foundation/fixtures/ci-mode.fixture.tsnew file mode 100644index 000000000..cb4bd8a82--- /dev/null+++ b/packages/app/tests/foundation/fixtures/ci-mode.fixture.ts@@ -0,0 +1,11 @@+import { expect, test } from 'vitest';++test('the browser graph reads CI as set, with no Node process global', () => {+ expect('process' in globalThis).toBe(false);+ expect(process.env.CI ? 'set' : 'unset').toBe('set');+});++test('the browser graph reads CI as unset, with no Node process global', () => {+ expect('process' in globalThis).toBe(false);+ expect(process.env.CI ? 'set' : 'unset').toBe('unset');+});diff --git a/packages/app/tests/foundation/fixtures/dom-defined-at-load.node-fixture.ts b/packages/app/tests/foundation/fixtures/dom-defined-at-load.node-fixture.tsnew file mode 100644index 000000000..d539a98a1--- /dev/null+++ b/packages/app/tests/foundation/fixtures/dom-defined-at-load.node-fixture.ts@@ -0,0 +1,7 @@+import { expect, test } from 'vitest';++Object.defineProperty(globalThis, 'window', { value: {}, configurable: true });++test('a test whose module defines window when it loads', () => {+ expect(typeof process.versions.node).toBe('string');+});diff --git a/packages/app/tests/foundation/fixtures/dom-defined-in-test.node-fixture.ts b/packages/app/tests/foundation/fixtures/dom-defined-in-test.node-fixture.tsnew file mode 100644index 000000000..2520e3754--- /dev/null+++ b/packages/app/tests/foundation/fixtures/dom-defined-in-test.node-fixture.ts@@ -0,0 +1,6 @@+import { expect, test } from 'vitest';++test('a test that defines localStorage while it runs', () => {+ Object.defineProperty(globalThis, 'localStorage', { value: {}, configurable: true });+ expect(typeof process.versions.node).toBe('string');+});diff --git a/packages/app/tests/foundation/fixtures/dom-free.node-fixture.ts b/packages/app/tests/foundation/fixtures/dom-free.node-fixture.tsnew file mode 100644index 000000000..34a51a7f2--- /dev/null+++ b/packages/app/tests/foundation/fixtures/dom-free.node-fixture.ts@@ -0,0 +1,5 @@+import { expect, test } from 'vitest';++test('a test that needs no DOM', () => {+ expect(typeof process.versions.node).toBe('string');+});diff --git a/packages/app/tests/foundation/fixtures/idb-fixture.test-helper.ts b/packages/app/tests/foundation/fixtures/idb-fixture.test-helper.tsnew file mode 100644index 000000000..0eaee6100--- /dev/null+++ b/packages/app/tests/foundation/fixtures/idb-fixture.test-helper.ts@@ -0,0 +1,17 @@+export function openDatabase(name: string): Promise<IDBDatabase> {+ return new Promise((resolve, reject) => {+ const request = indexedDB.open(name, 1);+ request.onupgradeneeded = () => request.result.createObjectStore('entries');+ request.onsuccess = () => resolve(request.result);+ request.onerror = () => reject(request.error);+ });+}++export function putEntry(database: IDBDatabase, key: string, value: string): Promise<void> {+ return new Promise((resolve, reject) => {+ const transaction = database.transaction('entries', 'readwrite');+ transaction.objectStore('entries').put(value, key);+ transaction.oncomplete = () => resolve();+ transaction.onerror = () => reject(transaction.error);+ });+}diff --git a/packages/app/tests/foundation/fixtures/known-bug-ansi.fixture.ts b/packages/app/tests/foundation/fixtures/known-bug-ansi.fixture.tsnew file mode 100644index 000000000..cb9b74a0e--- /dev/null+++ b/packages/app/tests/foundation/fixtures/known-bug-ansi.fixture.ts@@ -0,0 +1,10 @@+import { test } from 'vitest';+import { expectKnownBug } from '../../../../../test-support/known-bug.vitest.test-helper';++const ESC = String.fromCharCode(27);++test('the wrong outcome is reported with ANSI colour codes', async () => {+ await expectKnownBug(/expected 41 to be 42/, () => {+ throw new Error(`${ESC}[31mexpected${ESC}[39m 41 to be 42`);+ });+});diff --git a/packages/app/tests/foundation/fixtures/known-bug-fixed.fixture.ts b/packages/app/tests/foundation/fixtures/known-bug-fixed.fixture.tsnew file mode 100644index 000000000..84d2301c1--- /dev/null+++ b/packages/app/tests/foundation/fixtures/known-bug-fixed.fixture.ts@@ -0,0 +1,10 @@+import { expect, test } from 'vitest';+import { expectKnownBug } from '../../../../../test-support/known-bug.vitest.test-helper';++const answer = 42;++test('the pinned wrong outcome no longer occurs', async () => {+ await expectKnownBug(/expected 41 to be 42/, () => {+ expect(answer).toBe(42);+ });+});diff --git a/packages/app/tests/foundation/fixtures/known-bug-present.fixture.ts b/packages/app/tests/foundation/fixtures/known-bug-present.fixture.tsnew file mode 100644index 000000000..179a54a78--- /dev/null+++ b/packages/app/tests/foundation/fixtures/known-bug-present.fixture.ts@@ -0,0 +1,10 @@+import { expect, test } from 'vitest';+import { expectKnownBug } from '../../../../../test-support/known-bug.vitest.test-helper';++const answer = 41;++test('the pinned wrong outcome is still present', async () => {+ await expectKnownBug(/expected 41 to be 42/, () => {+ expect(answer).toBe(42);+ });+});diff --git a/packages/app/tests/foundation/fixtures/known-bug-unrelated-inside.fixture.ts b/packages/app/tests/foundation/fixtures/known-bug-unrelated-inside.fixture.tsnew file mode 100644index 000000000..055e6a7b4--- /dev/null+++ b/packages/app/tests/foundation/fixtures/known-bug-unrelated-inside.fixture.ts@@ -0,0 +1,10 @@+import { test } from 'vitest';+import { expectKnownBug } from '../../../../../test-support/known-bug.vitest.test-helper';++function readAnswer(): number {+ throw new TypeError('the subject could not be read');+}++test('a different error is thrown inside the pinned assertion', async () => {+ await expectKnownBug(/expected 41 to be 42/, () => readAnswer());+});diff --git a/packages/app/tests/foundation/fixtures/known-bug-unrelated-outside.fixture.ts b/packages/app/tests/foundation/fixtures/known-bug-unrelated-outside.fixture.tsnew file mode 100644index 000000000..2c78a5288--- /dev/null+++ b/packages/app/tests/foundation/fixtures/known-bug-unrelated-outside.fixture.ts@@ -0,0 +1,13 @@+import { expect, test } from 'vitest';+import { expectKnownBug } from '../../../../../test-support/known-bug.vitest.test-helper';++function prepareAnswer(): number {+ throw new RangeError('the fixture setup failed');+}++test('an error is thrown before the pinned assertion runs', async () => {+ const answer = prepareAnswer();+ await expectKnownBug(/expected 41 to be 42/, () => {+ expect(answer).toBe(42);+ });+});diff --git a/packages/app/tests/foundation/fixtures/mock-consumer.ts b/packages/app/tests/foundation/fixtures/mock-consumer.tsnew file mode 100644index 000000000..1bcf8ed9b--- /dev/null+++ b/packages/app/tests/foundation/fixtures/mock-consumer.ts@@ -0,0 +1,5 @@+import { alpha, beta } from './mock-subject';++export function describeBoth(): string {+ return `${alpha}+${beta}`;+}diff --git a/packages/app/tests/foundation/fixtures/mock-subject.ts b/packages/app/tests/foundation/fixtures/mock-subject.tsnew file mode 100644index 000000000..d07c98344--- /dev/null+++ b/packages/app/tests/foundation/fixtures/mock-subject.ts@@ -0,0 +1,2 @@+export const alpha = 'real-alpha';+export const beta = 'real-beta';diff --git a/packages/app/tests/foundation/fixtures/network-loopback.fixture.ts b/packages/app/tests/foundation/fixtures/network-loopback.fixture.tsnew file mode 100644index 000000000..81b3fcecf--- /dev/null+++ b/packages/app/tests/foundation/fixtures/network-loopback.fixture.ts@@ -0,0 +1,15 @@+import { expect, test, vi } from 'vitest';+import { stubApiRoutes } from '../api-routes.test-helper';+import { describeBoth } from './mock-consumer';++vi.mock('./mock-subject', () => ({ alpha: 'mocked-alpha', beta: 'mocked-beta' }));++test('requests to the test server, another loopback address, a stubbed API route and a mocked module', async () => {+ expect((await fetch(location.href)).ok).toBe(true);+ const samePageOnAnotherLoopbackAddress = new URL(location.href);+ samePageOnAnotherLoopbackAddress.hostname = '127.0.0.1';+ await fetch(samePageOnAnotherLoopbackAddress, { mode: 'no-cors' }).catch(() => undefined);+ stubApiRoutes({ '/api/ping': () => new Response('pong') });+ expect(await (await fetch('/api/ping')).text()).toBe('pong');+ expect(describeBoth()).toBe('mocked-alpha+mocked-beta');+});diff --git a/packages/app/tests/foundation/fixtures/network-outside.fixture.ts b/packages/app/tests/foundation/fixtures/network-outside.fixture.tsnew file mode 100644index 000000000..eb384769e--- /dev/null+++ b/packages/app/tests/foundation/fixtures/network-outside.fixture.ts@@ -0,0 +1,9 @@+import { expect, test } from 'vitest';++test('a request to a host outside loopback whose error the test catches', async () => {+ const outcome = await fetch('https://network-guard.example/data.json').then(+ () => 'answered',+ () => 'failed',+ );+ expect(outcome).toBe('failed');+});diff --git a/packages/app/tests/foundation/fixtures/never-settles.fixture.ts b/packages/app/tests/foundation/fixtures/never-settles.fixture.tsnew file mode 100644index 000000000..c94109c85--- /dev/null+++ b/packages/app/tests/foundation/fixtures/never-settles.fixture.ts@@ -0,0 +1,6 @@+import { expect, test } from 'vitest';++test('a test whose work never settles', async () => {+ await new Promise<never>(() => {});+ expect.unreachable();+});diff --git a/packages/app/tests/foundation/fixtures/rejected-factory.fixture.ts b/packages/app/tests/foundation/fixtures/rejected-factory.fixture.tsnew file mode 100644index 000000000..efe2a8061--- /dev/null+++ b/packages/app/tests/foundation/fixtures/rejected-factory.fixture.ts@@ -0,0 +1,10 @@+import { expect, test, vi } from 'vitest';+import { describeBoth } from './mock-consumer';++vi.mock('./mock-subject', async () => {+ throw new Error('planted factory rejection');+});++test('a file whose mocked import rejects never reaches its tests', () => {+ expect(describeBoth()).toBe('unreachable');+});diff --git a/packages/app/tests/foundation/fixtures/rejected-import-observed.fixture.ts b/packages/app/tests/foundation/fixtures/rejected-import-observed.fixture.tsnew file mode 100644index 000000000..981dff6a1--- /dev/null+++ b/packages/app/tests/foundation/fixtures/rejected-import-observed.fixture.ts@@ -0,0 +1,11 @@+import { expect, test, vi } from 'vitest';++vi.mock('./mock-subject', async () => {+ throw new Error('planted factory rejection');+});++test('a test that expects its mocked import to reject observes the rejection', async () => {+ await expect(import('./mock-consumer')).rejects.toThrow(+ 'vi.mock factory for /tests/foundation/fixtures/mock-subject.ts rejected',+ );+});diff --git a/packages/app/tests/foundation/fixtures/storage-blocked.fixture.ts b/packages/app/tests/foundation/fixtures/storage-blocked.fixture.tsnew file mode 100644index 000000000..4ef777d25--- /dev/null+++ b/packages/app/tests/foundation/fixtures/storage-blocked.fixture.ts@@ -0,0 +1,17 @@+import { expect, test } from 'vitest';++const HOLD_CONNECTION_OPEN = `+ const request = indexedDB.open('held-by-worker', 1);+ request.onupgradeneeded = () => request.result.createObjectStore('entries');+ request.onsuccess = () => postMessage('opened');+`;++test('a database a worker keeps open cannot be deleted after the test', async () => {+ const source = URL.createObjectURL(new Blob([HOLD_CONNECTION_OPEN], { type: 'text/javascript' }));+ const worker = new Worker(source);+ const opened = await new Promise((resolve) => {+ worker.onmessage = (event) => resolve(event.data);+ });++ expect(opened).toBe('opened');+});diff --git a/packages/app/tests/foundation/fixtures/storage-poison.fixture.ts b/packages/app/tests/foundation/fixtures/storage-poison.fixture.tsnew file mode 100644index 000000000..2854c9cfc--- /dev/null+++ b/packages/app/tests/foundation/fixtures/storage-poison.fixture.ts@@ -0,0 +1,23 @@+import { afterAll, expect, test } from 'vitest';+import { openDatabase, putEntry } from './idb-fixture.test-helper';++test('a file writes web storage and leaves an IndexedDB connection open', async () => {+ localStorage.setItem('poison', 'local');+ sessionStorage.setItem('poison', 'session');+ const database = await openDatabase('poison-in-test');+ await putEntry(database, 'poison', 'indexeddb');++ expect([localStorage.getItem('poison'), sessionStorage.getItem('poison')]).toEqual([+ 'local',+ 'session',+ ]);+ expect((await indexedDB.databases()).map(({ name }) => name)).toEqual(['poison-in-test']);+});++afterAll(async () => {+ localStorage.setItem('poison-after-all', 'local');+ sessionStorage.setItem('poison-after-all', 'session');+ const database = await openDatabase('poison-after-all');+ await putEntry(database, 'poison', 'indexeddb');+ database.close();+});diff --git a/packages/app/tests/foundation/fixtures/storage-witness.fixture.ts b/packages/app/tests/foundation/fixtures/storage-witness.fixture.tsnew file mode 100644index 000000000..efd14d43c--- /dev/null+++ b/packages/app/tests/foundation/fixtures/storage-witness.fixture.ts@@ -0,0 +1,7 @@+import { expect, test } from 'vitest';++test('a file starts with empty web storage and no IndexedDB databases', async () => {+ expect(localStorage.length).toBe(0);+ expect(sessionStorage.length).toBe(0);+ expect(await indexedDB.databases()).toEqual([]);+});diff --git a/packages/app/tests/foundation/fixtures/unrelated-neighbor.fixture.ts b/packages/app/tests/foundation/fixtures/unrelated-neighbor.fixture.tsnew file mode 100644index 000000000..e77586824--- /dev/null+++ b/packages/app/tests/foundation/fixtures/unrelated-neighbor.fixture.ts@@ -0,0 +1,6 @@+import { expect, test } from 'vitest';+import { describeBoth } from './mock-consumer';++test('an unrelated file imports the real module', () => {+ expect(describeBoth()).toBe('real-alpha+real-beta');+});diff --git a/packages/app/tests/foundation/fixtures/unsupported-node-export.fixture.ts b/packages/app/tests/foundation/fixtures/unsupported-node-export.fixture.tsnew file mode 100644index 000000000..6b16e9321--- /dev/null+++ b/packages/app/tests/foundation/fixtures/unsupported-node-export.fixture.ts@@ -0,0 +1,6 @@+import { watch } from 'node:fs';+import { expect, test } from 'vitest';++test('a file importing a node:fs export the browser tier does not provide never runs', () => {+ expect(watch).toBeUndefined();+});diff --git a/packages/app/tests/foundation/fixtures/vitest.browser-fixture.config.ts b/packages/app/tests/foundation/fixtures/vitest.browser-fixture.config.tsnew file mode 100644index 000000000..dd6c3fbc9--- /dev/null+++ b/packages/app/tests/foundation/fixtures/vitest.browser-fixture.config.ts@@ -0,0 +1,40 @@+import { basename, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { defineConfig, type ViteUserConfig } from 'vitest/config';+import { BaseSequencer, type TestSpecification } from 'vitest/node';+import { appBrowserVitestConfig } from '../../../vitest.browser.config';+import { BROWSER_FIXTURE_CACHE_DIR_ENV, BROWSER_FIXTURE_ORDER_ENV } from '../browser-fixture-run';++const APP_ROOT = fileURLToPath(new URL('../../../', import.meta.url));++class DeclaredOrderSequencer extends BaseSequencer {+ override async sort(files: TestSpecification[]): Promise<TestSpecification[]> {+ const order = (process.env[BROWSER_FIXTURE_ORDER_ENV] ?? '').split(',').filter(Boolean);+ const position = (file: TestSpecification): number => {+ const index = order.indexOf(basename(file.moduleId));+ if (index === -1) {+ throw new Error(+ `${basename(file.moduleId)} was selected but is not named in ${BROWSER_FIXTURE_ORDER_ENV}=${order.join(',')}`,+ );+ }+ return index;+ };+ return [...files].sort((left, right) => position(left) - position(right));+ }+}++export const appBrowserFixtureVitestConfig = {+ ...appBrowserVitestConfig,+ root: APP_ROOT,+ cacheDir:+ process.env[BROWSER_FIXTURE_CACHE_DIR_ENV] ??+ join(APP_ROOT, 'node_modules/.vite/browser-fixture'),+ test: {+ ...appBrowserVitestConfig.test,+ include: ['tests/foundation/fixtures/*.fixture.ts?(x)'],+ fileParallelism: false,+ sequence: { sequencer: DeclaredOrderSequencer },+ },+} satisfies ViteUserConfig;++export default defineConfig(appBrowserFixtureVitestConfig);diff --git a/packages/app/tests/foundation/fixtures/vitest.node-fixture.config.ts b/packages/app/tests/foundation/fixtures/vitest.node-fixture.config.tsnew file mode 100644index 000000000..7df473d37--- /dev/null+++ b/packages/app/tests/foundation/fixtures/vitest.node-fixture.config.ts@@ -0,0 +1,12 @@+import { fileURLToPath } from 'node:url';+import { defineConfig } from 'vitest/config';+import { appNodeVitestConfig } from '../../../vitest.node.config';++export default defineConfig({+ ...appNodeVitestConfig,+ root: fileURLToPath(new URL('../../../', import.meta.url)),+ test: {+ ...appNodeVitestConfig.test,+ include: ['tests/foundation/fixtures/*.node-fixture.ts'],+ },+});diff --git a/packages/app/tests/foundation/known-bug-helper.browser.test.ts b/packages/app/tests/foundation/known-bug-helper.browser.test.tsnew file mode 100644index 000000000..d415924f7--- /dev/null+++ b/packages/app/tests/foundation/known-bug-helper.browser.test.ts@@ -0,0 +1,70 @@+import { beforeAll, describe, expect, test } from 'vitest';+import { commands } from 'vitest/browser';+import type { BrowserFixtureRun } from './browser-fixture-run';+import { NESTED_RUN_TIMEOUT_MS } from './nested-run-budget';++const VARIANTS = [+ 'known-bug-present.fixture.ts',+ 'known-bug-fixed.fixture.ts',+ 'known-bug-unrelated-inside.fixture.ts',+ 'known-bug-unrelated-outside.fixture.ts',+ 'known-bug-ansi.fixture.ts',+] as const;++type Variant = (typeof VARIANTS)[number];++let run: BrowserFixtureRun;++function outcome(variant: Variant) {+ const file = run.files?.find((entry) => entry.file === variant);+ return {+ status: file?.status,+ tests: file?.tests.map(({ status, failureMessages }) => ({+ status,+ failure: failureMessages.join('\n'),+ })),+ };+}++describe('expectKnownBug in browser mode, each variant a nested controlled run', () => {+ beforeAll(async () => {+ run = await commands.runBrowserFixture({ files: [...VARIANTS] });+ }, NESTED_RUN_TIMEOUT_MS);++ test('a pin passes while its bug is still present', () => {+ expect(outcome('known-bug-present.fixture.ts')).toEqual({+ status: 'passed',+ tests: [{ status: 'passed', failure: '' }],+ });+ });++ test('a pin fails once its bug is fixed, saying the known bug appears fixed', () => {+ const { status, tests } = outcome('known-bug-fixed.fixture.ts');+ expect(status).toBe('failed');+ expect(tests?.map((entry) => entry.status)).toEqual(['failed']);+ expect(tests?.[0]?.failure).toContain(+ 'known bug appears fixed: the correct assertion passed, so /expected 41 to be 42/ no longer describes a failure.',+ );+ });++ test('an unrelated error inside the pinned assertion fails with that error', () => {+ const { status, tests } = outcome('known-bug-unrelated-inside.fixture.ts');+ expect(status).toBe('failed');+ expect(tests?.map((entry) => entry.status)).toEqual(['failed']);+ expect(tests?.[0]?.failure).toContain('TypeError: the subject could not be read');+ });++ test('an unrelated error before the pinned assertion fails with that error', () => {+ const { status, tests } = outcome('known-bug-unrelated-outside.fixture.ts');+ expect(status).toBe('failed');+ expect(tests?.map((entry) => entry.status)).toEqual(['failed']);+ expect(tests?.[0]?.failure).toContain('RangeError: the fixture setup failed');+ });++ test('a signature matches the wrong outcome once its ANSI colour codes are stripped', () => {+ expect(outcome('known-bug-ansi.fixture.ts')).toEqual({+ status: 'passed',+ tests: [{ status: 'passed', failure: '' }],+ });+ });+});diff --git a/packages/app/tests/foundation/nested-run-budget.ts b/packages/app/tests/foundation/nested-run-budget.tsnew file mode 100644index 000000000..9bcf32944--- /dev/null+++ b/packages/app/tests/foundation/nested-run-budget.ts@@ -0,0 +1,6 @@+export const NESTED_RUN_DEADLINE_MS = 35_000;+export const NESTED_RUN_STOP_GRACE_MS = 5_000;+const NESTED_RUN_RESULT_MARGIN_MS = 5_000;++export const NESTED_RUN_TIMEOUT_MS =+ NESTED_RUN_DEADLINE_MS + NESTED_RUN_STOP_GRACE_MS + NESTED_RUN_RESULT_MARGIN_MS;diff --git a/packages/app/tests/foundation/network-guard.browser.test.ts b/packages/app/tests/foundation/network-guard.browser.test.tsnew file mode 100644index 000000000..25d8c5776--- /dev/null+++ b/packages/app/tests/foundation/network-guard.browser.test.ts@@ -0,0 +1,46 @@+import { beforeAll, describe, expect, test } from 'vitest';+import { commands } from 'vitest/browser';+import type { BrowserFixtureRun } from './browser-fixture-run';+import { NESTED_RUN_TIMEOUT_MS } from './nested-run-budget';++const OUTSIDE = 'network-outside.fixture.ts';+const LOOPBACK = 'network-loopback.fixture.ts';++let run: BrowserFixtureRun;++function outcome(fixture: string) {+ const file = run.files?.find((entry) => entry.file === fixture);+ return {+ status: file?.status,+ tests: file?.tests.map(({ status, failureMessages }) => ({+ status,+ failure: failureMessages.join('\n').split('\n')[0],+ })),+ };+}++describe('the browser tier network guard, each side a nested controlled run', () => {+ beforeAll(async () => {+ run = await commands.runBrowserFixture({ files: [OUTSIDE, LOOPBACK] });+ }, NESTED_RUN_TIMEOUT_MS);++ test('a request to a host outside loopback fails the test that made it, naming the URL, even when the test caught the error', () => {+ expect(outcome(OUTSIDE)).toEqual({+ status: 'failed',+ tests: [+ {+ status: 'failed',+ failure:+ 'Error: The browser tier reaches only loopback hosts, and this test requested https://network-guard.example/data.json. Fake the dependency at its seam, or serve it from the test server.',+ },+ ],+ });+ });++ test('requests to the test server, another loopback address, a stubbed API route and a mocked module pass the guard', () => {+ expect(outcome(LOOPBACK)).toEqual({+ status: 'passed',+ tests: [{ status: 'passed', failure: '' }],+ });+ });+});diff --git a/packages/app/tests/foundation/node-destination-setup.ts b/packages/app/tests/foundation/node-destination-setup.tsnew file mode 100644index 000000000..5df60c199--- /dev/null+++ b/packages/app/tests/foundation/node-destination-setup.ts@@ -0,0 +1,6 @@+import { afterEach, beforeEach } from 'vitest';+import { refuseDomGlobals } from './node-dom-globals';++beforeEach(() => refuseDomGlobals('before this test runs'));++afterEach(() => refuseDomGlobals('after this test ran'));diff --git a/packages/app/tests/foundation/node-destination.node.test.ts b/packages/app/tests/foundation/node-destination.node.test.tsnew file mode 100644index 000000000..bca69ad49--- /dev/null+++ b/packages/app/tests/foundation/node-destination.node.test.ts@@ -0,0 +1,25 @@+import { describe, expect, test } from 'vitest';+import { installedDomGlobals } from './node-dom-globals';++const definedAtModuleLoad = installedDomGlobals();++describe('the Node destination', () => {+ test('window, document and Storage are undefined while a test runs', () => {+ expect([typeof window, typeof document, typeof Storage]).toEqual([+ 'undefined',+ 'undefined',+ 'undefined',+ ]);+ });++ test('no DOM global is defined when the test module loads or while its test runs', () => {+ expect(definedAtModuleLoad).toEqual([]);+ expect(installedDomGlobals()).toEqual([]);+ });++ test('the DOM check names every DOM global a scope defines', () => {+ expect(+ installedDomGlobals({ window: {}, document: {}, localStorage: {}, navigator: {} }),+ ).toEqual(['window', 'document', 'localStorage']);+ });+});diff --git a/packages/app/tests/foundation/node-dom-globals.ts b/packages/app/tests/foundation/node-dom-globals.tsnew file mode 100644index 000000000..99ba2d672--- /dev/null+++ b/packages/app/tests/foundation/node-dom-globals.ts@@ -0,0 +1,24 @@+export const DOM_GLOBALS = [+ 'window',+ 'document',+ 'Storage',+ 'localStorage',+ 'sessionStorage',+ 'indexedDB',+ 'HTMLElement',+] as const;++export type DomGlobal = (typeof DOM_GLOBALS)[number];++export function installedDomGlobals(scope: object = globalThis): DomGlobal[] {+ return DOM_GLOBALS.filter((name) => name in scope);+}++export function refuseDomGlobals(moment: string, scope: object = globalThis): void {+ const installed = installedDomGlobals(scope);+ if (installed.length === 0) return;+ throw new Error(+ `The Node destination runs without a DOM, but ${installed.join(', ')} ${installed.length === 1 ? 'is' : 'are'} defined ${moment}. ` ++ 'A test that needs a DOM belongs in the browser destination (*.browser.test.ts?(x)); otherwise remove what installs it.',+ );+}diff --git a/packages/app/tests/foundation/node-substitutes.browser.test.ts b/packages/app/tests/foundation/node-substitutes.browser.test.tsnew file mode 100644index 000000000..748a40d94--- /dev/null+++ b/packages/app/tests/foundation/node-substitutes.browser.test.ts@@ -0,0 +1,62 @@+import { randomUUID } from 'node:crypto';+import { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, isAbsolute, join, resolve } from 'node:path';+import process from 'node:process';+import { fileURLToPath } from 'node:url';+import { describe, expect, test } from 'vitest';++const HERE = dirname(fileURLToPath(import.meta.url));+const FIXTURES = join(HERE, 'fixtures');+const READABLE = join(FIXTURES, 'bridge-readable.txt');++describe('test-side node: imports in the browser tier', () => {+ test('a test reads a fixture beside it through node:fs, node:path and node:url', () => {+ expect(readFileSync(READABLE, 'utf8')).toBe('readable through the file bridge\n');+ expect(+ readFileSync(new URL('./fixtures/bridge-readable.txt', import.meta.url), {+ encoding: 'utf8',+ }),+ ).toBe('readable through the file bridge\n');+ expect(existsSync(READABLE)).toBe(true);+ expect(existsSync(join(FIXTURES, 'absent.txt'))).toBe(false);+ expect(readdirSync(FIXTURES)).toContain('bridge-readable.txt');+ });++ test('a read outside the declared test and source roots is refused', () => {+ expect(() =>+ readFileSync(resolve(HERE, '..', '..', '..', '..', 'package.json'), 'utf8'),+ ).toThrow(/EACCES: .* is outside the declared roots/);+ expect(() => readFileSync(`${HERE}/../../../../package.json`, 'utf8')).toThrow(+ /EACCES: .* path traversal is refused/,+ );+ });++ test('a missing file reads as ENOENT', () => {+ expect(() => readFileSync(join(FIXTURES, 'absent.txt'), 'utf8')).toThrow(/^ENOENT: /);+ });++ test('writes are refused, because the file bridge is read-only', () => {+ expect(() => writeFileSync(join(FIXTURES, 'written.txt'), 'x')).toThrow(+ 'node:fs.writeFileSync is not available in the browser tier: the file bridge is read-only',+ );+ expect(() => mkdtempSync(join(tmpdir(), 'ok-'))).toThrow(+ 'node:fs.mkdtempSync is not available in the browser tier: the file bridge is read-only',+ );+ });++ test('a read without a utf8 encoding fails instead of returning a different type', () => {+ expect(() => readFileSync(READABLE)).toThrow(+ 'node:fs.readFileSync in the browser tier reads utf8 text only; pass "utf8"',+ );+ });++ test('node:crypto, node:os and node:process answer from the engine and the host', () => {+ expect(randomUUID()).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,+ );+ expect(isAbsolute(tmpdir())).toBe(true);+ expect(process.cwd()).toBe(resolve(HERE, '..', '..'));+ expect(() => process.exit(1)).toThrow('process.exit(1) was called in the browser tier');+ });+});diff --git a/packages/app/tests/foundation/node-substitutes/crypto.ts b/packages/app/tests/foundation/node-substitutes/crypto.tsnew file mode 100644index 000000000..ebaca6c26--- /dev/null+++ b/packages/app/tests/foundation/node-substitutes/crypto.ts@@ -0,0 +1,7 @@+export function randomUUID(): string {+ return globalThis.crypto.randomUUID();+}++export const webcrypto = globalThis.crypto;++export default { randomUUID, webcrypto };diff --git a/packages/app/tests/foundation/node-substitutes/file-bridge-contract.ts b/packages/app/tests/foundation/node-substitutes/file-bridge-contract.tsnew file mode 100644index 000000000..c9b6d0cda--- /dev/null+++ b/packages/app/tests/foundation/node-substitutes/file-bridge-contract.ts@@ -0,0 +1,11 @@+export const FILE_BRIDGE_ROUTE = '/__ok-browser-file-bridge';++export type FileBridgeOperation = 'read' | 'exists' | 'readdir' | 'host';++export type BridgeHostFacts = {+ readonly cwd: string;+ readonly platform: string;+ readonly tmpdir: string;+ readonly eol: string;+ readonly ci: string | null;+};diff --git a/packages/app/tests/foundation/node-substitutes/file-bridge.ts b/packages/app/tests/foundation/node-substitutes/file-bridge.tsnew file mode 100644index 000000000..84e8c6c25--- /dev/null+++ b/packages/app/tests/foundation/node-substitutes/file-bridge.ts@@ -0,0 +1,39 @@+import {+ type BridgeHostFacts,+ FILE_BRIDGE_ROUTE,+ type FileBridgeOperation,+} from './file-bridge-contract';++const ERRNO_PREFIX = /^(E[A-Z]+):/;++type BridgeError = Error & { code: string; path: string };++export function bridgeCall(operation: FileBridgeOperation, path = ''): string {+ const request = new XMLHttpRequest();+ request.open(+ 'GET',+ `${FILE_BRIDGE_ROUTE}?op=${operation}&path=${encodeURIComponent(path)}`,+ false,+ );+ request.send();+ if (request.status === 200) return request.responseText;+ const error = new Error(request.responseText) as BridgeError;+ error.code = ERRNO_PREFIX.exec(request.responseText)?.[1] ?? 'EIO';+ error.path = path;+ throw error;+}++let facts: BridgeHostFacts | undefined;++export function hostFacts(): BridgeHostFacts {+ facts ??= JSON.parse(bridgeCall('host')) as BridgeHostFacts;+ return facts;+}++export function readOnly(operation: string): () => never {+ return () => {+ throw new Error(+ `node:fs.${operation} is not available in the browser tier: the file bridge is read-only`,+ );+ };+}diff --git a/packages/app/tests/foundation/node-substitutes/fs.ts b/packages/app/tests/foundation/node-substitutes/fs.tsnew file mode 100644index 000000000..2ba7d70d4--- /dev/null+++ b/packages/app/tests/foundation/node-substitutes/fs.ts@@ -0,0 +1,52 @@+import { bridgeCall, readOnly } from './file-bridge';+import { fileURLToPath } from './url';++type PathLike = string | URL;+type ReadOptions = string | { readonly encoding?: string | null };++const UTF8 = new Set(['utf8', 'utf-8']);++function toPath(path: PathLike): string {+ return path instanceof URL ? fileURLToPath(path) : path;+}++export function readFileSync(path: PathLike, options?: ReadOptions): string {+ const encoding = typeof options === 'string' ? options : options?.encoding;+ if (typeof encoding !== 'string' || !UTF8.has(encoding.toLowerCase())) {+ throw new TypeError(+ 'node:fs.readFileSync in the browser tier reads utf8 text only; pass "utf8"',+ );+ }+ return bridgeCall('read', toPath(path));+}++export function existsSync(path: PathLike): boolean {+ return bridgeCall('exists', toPath(path)) === 'true';+}++export function readdirSync(path: PathLike): string[] {+ return JSON.parse(bridgeCall('readdir', toPath(path))) as string[];+}++export const appendFileSync = readOnly('appendFileSync');+export const copyFileSync = readOnly('copyFileSync');+export const mkdirSync = readOnly('mkdirSync');+export const mkdtempSync = readOnly('mkdtempSync');+export const renameSync = readOnly('renameSync');+export const rmSync = readOnly('rmSync');+export const unlinkSync = readOnly('unlinkSync');+export const writeFileSync = readOnly('writeFileSync');++export default {+ readFileSync,+ existsSync,+ readdirSync,+ appendFileSync,+ copyFileSync,+ mkdirSync,+ mkdtempSync,+ renameSync,+ rmSync,+ unlinkSync,+ writeFileSync,+};diff --git a/packages/app/tests/foundation/node-substitutes/os.ts b/packages/app/tests/foundation/node-substitutes/os.tsnew file mode 100644index 000000000..3b03592a7--- /dev/null+++ b/packages/app/tests/foundation/node-substitutes/os.ts@@ -0,0 +1,13 @@+import { hostFacts } from './file-bridge';++export function tmpdir(): string {+ return hostFacts().tmpdir;+}++export function platform(): string {+ return hostFacts().platform;+}++export const EOL = hostFacts().eol;++export default { tmpdir, platform, EOL };diff --git a/packages/app/tests/foundation/node-substitutes/path.ts b/packages/app/tests/foundation/node-substitutes/path.tsnew file mode 100644index 000000000..77fbca532--- /dev/null+++ b/packages/app/tests/foundation/node-substitutes/path.ts@@ -0,0 +1,85 @@+import { hostFacts } from './file-bridge';++export const sep = '/';+export const delimiter = ':';++export function isAbsolute(path: string): boolean {+ return path.startsWith('/');+}++export function normalize(path: string): string {+ const absolute = isAbsolute(path);+ const segments: string[] = [];+ for (const segment of path.split('/')) {+ if (segment === '' || segment === '.') continue;+ if (segment !== '..') segments.push(segment);+ else if (segments.length > 0 && segments.at(-1) !== '..') segments.pop();+ else if (!absolute) segments.push('..');+ }+ const joined = segments.join('/');+ if (absolute) return `/${joined}`;+ return joined === '' ? '.' : joined;+}++export function join(...paths: string[]): string {+ return normalize(paths.filter((path) => path !== '').join('/'));+}++export function resolve(...paths: string[]): string {+ let resolved = '';+ for (const path of [...paths].reverse()) {+ if (path === '') continue;+ resolved = resolved === '' ? path : `${path}/${resolved}`;+ if (isAbsolute(path)) break;+ }+ return normalize(isAbsolute(resolved) ? resolved : `${hostFacts().cwd}/${resolved}`);+}++export function dirname(path: string): string {+ const normalized = normalize(path);+ const index = normalized.lastIndexOf('/');+ if (index === -1) return '.';+ return index === 0 ? '/' : normalized.slice(0, index);+}++export function basename(path: string, suffix?: string): string {+ const base = normalize(path).split('/').at(-1) ?? '';+ return suffix !== undefined && base.endsWith(suffix) && base !== suffix+ ? base.slice(0, -suffix.length)+ : base;+}++export function extname(path: string): string {+ const base = basename(path);+ const index = base.lastIndexOf('.');+ return index <= 0 ? '' : base.slice(index);+}++export function relative(from: string, to: string): string {+ const fromSegments = resolve(from).split('/').filter(Boolean);+ const toSegments = resolve(to).split('/').filter(Boolean);+ let shared = 0;+ while (+ shared < fromSegments.length &&+ shared < toSegments.length &&+ fromSegments[shared] === toSegments[shared]+ ) {+ shared += 1;+ }+ return [...fromSegments.slice(shared).map(() => '..'), ...toSegments.slice(shared)].join('/');+}++export const posix = {+ sep,+ delimiter,+ isAbsolute,+ normalize,+ join,+ resolve,+ dirname,+ basename,+ extname,+ relative,+};++export default posix;diff --git a/packages/app/tests/foundation/node-substitutes/process.ts b/packages/app/tests/foundation/node-substitutes/process.tsnew file mode 100644index 000000000..bb7c9fbf6--- /dev/null+++ b/packages/app/tests/foundation/node-substitutes/process.ts@@ -0,0 +1,17 @@+import { hostFacts } from './file-bridge';++export const env: Readonly<Record<string, string | undefined>> = {+ CI: hostFacts().ci ?? undefined,+};++export function cwd(): string {+ return hostFacts().cwd;+}++export const platform = hostFacts().platform;++export function exit(code?: number): never {+ throw new Error(`process.exit(${code ?? ''}) was called in the browser tier`);+}++export default { env, cwd, platform, exit };diff --git a/packages/app/tests/foundation/node-substitutes/url.ts b/packages/app/tests/foundation/node-substitutes/url.tsnew file mode 100644index 000000000..daf030ee6--- /dev/null+++ b/packages/app/tests/foundation/node-substitutes/url.ts@@ -0,0 +1,35 @@+import { hostFacts } from './file-bridge';++const SERVED_FILESYSTEM_PREFIX = '/@fs/';++export function fileURLToPath(url: string | URL): string {+ const parsed = typeof url === 'string' ? new URL(url) : url;+ const pathname = decodeURIComponent(parsed.pathname);+ if (parsed.protocol === 'file:') return pathname;+ if (parsed.origin !== location.origin) {+ throw new TypeError(+ `The URL must be of scheme file or served by this test server: ${parsed.href}`,+ );+ }+ if (pathname.startsWith(SERVED_FILESYSTEM_PREFIX)) {+ return pathname.slice(SERVED_FILESYSTEM_PREFIX.length - 1);+ }+ const { cwd } = hostFacts();+ return pathname.startsWith(`${cwd}/`) ? pathname : `${cwd}${pathname}`;+}++export function pathToFileURL(path: string): URL {+ return new URL(`file://${encodeURI(path)}`);+}++const EngineURL = globalThis.URL;+const EngineURLSearchParams = globalThis.URLSearchParams;++export { EngineURL as URL, EngineURLSearchParams as URLSearchParams };++export default {+ fileURLToPath,+ pathToFileURL,+ URL: EngineURL,+ URLSearchParams: EngineURLSearchParams,+};diff --git a/packages/app/tests/foundation/outline-panel.browser.test.tsx b/packages/app/tests/foundation/outline-panel.browser.test.tsxnew file mode 100644index 000000000..c45945662--- /dev/null+++ b/packages/app/tests/foundation/outline-panel.browser.test.tsx@@ -0,0 +1,109 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { type RenderResult, within } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { OutlinePanel } from '@/components/OutlinePanel';+import { PageListProvider } from '@/components/PageListContext';+import { __resetPageListCacheForTests, getPageListCache } from '@/editor/page-list-cache';+import { emitDocumentsChanged } from '@/lib/documents-events';+import { expectKnownBug } from '../../../../test-support/known-bug.vitest.test-helper';+import { stubApiRoutes } from './api-routes.test-helper';+import { renderWithI18n } from './render-with-i18n.test-helper';++const DOC_NAME = 'offsite/liveblocks/liveblocks';+const HEADINGS = [+ { level: 1, text: 'Liveblocks', slug: 'liveblocks' },+ { level: 2, text: 'What is it', slug: 'what-is-it' },+ { level: 2, text: 'Comments', slug: 'comments' },+];++vi.mock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({ activeProvider: null, activeDocName: DOC_NAME }),+}));++let listedPages: string[] = [];++function renderOutline(): RenderResult {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return renderWithI18n(+ <QueryClientProvider client={client}>+ <PageListProvider>+ <OutlinePanel docName={DOC_NAME} isSourceMode={false} />+ </PageListProvider>+ </QueryClientProvider>,+ );+}++function outlineHeadings(view: RenderResult): (string | null)[] {+ const outline = view.queryByRole('navigation', { name: 'Document outline' });+ if (outline === null) return [];+ return within(outline)+ .queryAllByRole('button')+ .map((button) => button.textContent);+}++function headingCount(view: RenderResult): string | null | undefined {+ return view.container.querySelector('[data-slot="panel-count"]')?.textContent;+}++describe('OutlinePanel under the production compiler', () => {+ beforeEach(() => {+ listedPages = [DOC_NAME];+ __resetPageListCacheForTests();+ stubApiRoutes({+ '/api/pages': () =>+ Response.json({+ pages: listedPages.map((docName) => ({+ docName,+ title: 'Liveblocks',+ size: 1,+ modified: '2026-10-05T00:00:00.000Z',+ })),+ }),+ '/api/documents': () => Response.json({ documents: [] }),+ '/api/page-headings': () => Response.json({ docName: DOC_NAME, headings: HEADINGS }),+ });+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ test('after a successful load the outline lists the three returned headings and counts them', async () => {+ const view = renderOutline();+ await view.findByRole('button', { name: 'Liveblocks' });++ expect(outlineHeadings(view)).toEqual(['Liveblocks', 'What is it', 'Comments']);+ expect(headingCount(view)).toBe('3');+ });++ test('a document that leaves the page list after a successful load stops serving its headings and says it moved', {+ tags: ['known-bug'],+ meta: {+ issue: 'https://github.com/inkeep/agents-private/issues/5611',+ owner: 'get-main-green',+ until: '2026-12-31',+ },+ }, async () => {+ const view = renderOutline();+ await view.findByRole('button', { name: 'Liveblocks' });++ listedPages = [];+ emitDocumentsChanged(['files']);+ await vi.waitFor(+ () => {+ expect(getPageListCache()?.pages.has(DOC_NAME)).toBe(false);+ },+ { timeout: 5_000 },+ );++ await expectKnownBug(/expected undefined to be 'This page is no longer at this path\.'/, () => {+ expect(view.queryByRole('status')?.textContent).toBe('This page is no longer at this path.');+ });+ await expectKnownBug(+ /expected \[ 'Liveblocks', 'What is it', …\(1\) \] to deeply equal \[\]/,+ () => {+ expect(outlineHeadings(view)).toEqual([]);+ },+ );+ });+});diff --git a/packages/app/tests/foundation/partial-mock.browser.test.ts b/packages/app/tests/foundation/partial-mock.browser.test.tsnew file mode 100644index 000000000..7db16a259--- /dev/null+++ b/packages/app/tests/foundation/partial-mock.browser.test.ts@@ -0,0 +1,14 @@+import { expect, test, vi } from 'vitest';+import { describeBoth } from './fixtures/mock-consumer';+import * as subject from './fixtures/mock-subject';++vi.mock('./fixtures/mock-subject', () => ({ alpha: 'mocked-alpha' }));++test('a partial vi.mock factory links, and the importer reads its mocked binding', () => {+ expect(describeBoth()).toBe('mocked-alpha+undefined');+});++test('a binding the partial factory omits reads undefined in the browser, where the Node mock runner throws', () => {+ expect(Object.keys(subject).sort()).toEqual(['alpha', 'beta']);+ expect(subject.beta).toBeUndefined();+});diff --git a/packages/app/tests/foundation/render-with-i18n.test-helper.tsx b/packages/app/tests/foundation/render-with-i18n.test-helper.tsxnew file mode 100644index 000000000..5f9ca5cd4--- /dev/null+++ b/packages/app/tests/foundation/render-with-i18n.test-helper.tsx@@ -0,0 +1,15 @@+import { I18nProvider } from '@lingui/react';+import { type RenderOptions, type RenderResult, render } from '@testing-library/react';+import type { ReactElement, ReactNode } from 'react';+import { i18n } from '@/lib/i18n';++function WithRealI18n({ children }: { children: ReactNode }) {+ return <I18nProvider i18n={i18n}>{children}</I18nProvider>;+}++export function renderWithI18n(+ ui: ReactElement,+ options?: Omit<RenderOptions, 'wrapper'>,+): RenderResult {+ return render(ui, { ...options, wrapper: WithRealI18n });+}diff --git a/packages/app/tests/foundation/test-server-inputs.node.test.ts b/packages/app/tests/foundation/test-server-inputs.node.test.tsnew file mode 100644index 000000000..db13f7fde--- /dev/null+++ b/packages/app/tests/foundation/test-server-inputs.node.test.ts@@ -0,0 +1,215 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import {+ prebuiltManifest,+ prebuiltServingDecision,+ reuseDecision,+ serverFingerprint,+} from './test-server-inputs';++const OK_TREE: Readonly<Record<string, string>> = {+ 'package.json': '{"name":"open-knowledge"}\n',+ 'pnpm-lock.yaml': "lockfileVersion: '9.0'\n",+ 'packages/app/package.json': '{"name":"@inkeep/open-knowledge-app"}\n',+ 'packages/app/vite.config.ts': 'export default {};\n',+ 'packages/app/src/App.tsx': 'export const App = () => null;\n',+ 'packages/app/src/server/hocuspocus-plugin.ts': 'export const hocuspocusPlugin = () => ({});\n',+ 'packages/core/src/index.ts': 'export const core = 1;\n',+ 'packages/server/src/index.ts': 'export const server = 1;\n',+};++const WORKER_ENV = { OK_TEST_GIT_ENABLED: '1' };++const roots: string[] = [];++function okTree(): string {+ const root = mkdtempSync(join(tmpdir(), 'ok-server-inputs-'));+ roots.push(root);+ for (const [path, content] of Object.entries(OK_TREE)) write(root, path, content);+ return root;+}++function write(root: string, path: string, content: string): void {+ mkdirSync(dirname(join(root, path)), { recursive: true });+ writeFileSync(join(root, path), content);+}++afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});++describe('server reuse eligibility', () => {+ test('an edit to the server source makes the admitted server ineligible and names the file', () => {+ const root = okTree();+ const admitted = serverFingerprint(root, WORKER_ENV);++ write(root, 'packages/server/src/index.ts', 'export const server = 2;\n');++ expect(reuseDecision(admitted, serverFingerprint(root, WORKER_ENV))).toEqual({+ reuse: false,+ changedInputs: ['packages/server/src/index.ts'],+ changedEnv: [],+ });+ });++ test('edits to app source the dev server transforms on request leave the admitted server reusable', () => {+ const root = okTree();+ const admitted = serverFingerprint(root, WORKER_ENV);++ write(root, 'packages/app/src/App.tsx', 'export const App = () => "edited";\n');+ write(+ root,+ 'packages/app/src/components/NewPanel.tsx',+ 'export const NewPanel = () => null;\n',+ );+ write(root, 'packages/app/src/locales/en/messages.po', 'msgid "Save"\nmsgstr "Save"\n');++ expect(reuseDecision(admitted, serverFingerprint(root, WORKER_ENV))).toEqual({ reuse: true });+ });++ test('core source, the lockfile, shared configuration and the Node-side dev server plugin each make the admitted server ineligible', () => {+ const edits = [+ ['packages/core/src/index.ts', 'export const core = 2;\n'],+ ['pnpm-lock.yaml', "lockfileVersion: '9.0'\nimporters: {}\n"],+ ['package.json', '{"name":"open-knowledge","private":true}\n'],+ ['packages/app/vite.config.ts', 'export default { server: {} };\n'],+ [+ 'packages/app/src/server/hocuspocus-plugin.ts',+ 'export const hocuspocusPlugin = () => null;\n',+ ],+ ] as const;++ const decisions = edits.map(([path, content]) => {+ const root = okTree();+ const admitted = serverFingerprint(root, WORKER_ENV);+ write(root, path, content);+ return reuseDecision(admitted, serverFingerprint(root, WORKER_ENV));+ });++ expect(decisions).toEqual(+ edits.map(([path]) => ({ reuse: false, changedInputs: [path], changedEnv: [] })),+ );+ });++ test('a server source file added or removed after admission makes the server ineligible', () => {+ const root = okTree();+ const admitted = serverFingerprint(root, WORKER_ENV);++ write(root, 'packages/server/src/routes/new-route.ts', 'export const route = 1;\n');+ rmSync(join(root, 'packages/core/src/index.ts'));++ expect(reuseDecision(admitted, serverFingerprint(root, WORKER_ENV))).toEqual({+ reuse: false,+ changedInputs: ['packages/core/src/index.ts', 'packages/server/src/routes/new-route.ts'],+ changedEnv: [],+ });+ });++ test('the core and server build output the dev server writes at startup leaves the admitted server reusable', () => {+ const root = okTree();+ const admitted = serverFingerprint(root, WORKER_ENV);++ write(root, 'packages/core/dist/index.mjs', 'export const core = 1;\n');+ write(root, 'packages/server/dist/index.mjs', 'export const server = 1;\n');+ write(root, 'packages/server/.turbo/turbo-build.log', 'built\n');+ write(root, 'packages/server/node_modules/.vite/deps.json', '{}\n');++ expect(reuseDecision(admitted, serverFingerprint(root, WORKER_ENV))).toEqual({ reuse: true });+ });++ test('a changed worker environment makes the admitted server ineligible without recording the values', () => {+ const root = okTree();+ const admitted = serverFingerprint(root, { ...WORKER_ENV, OK_TEST_TOKEN: 'secret-before' });+ const current = serverFingerprint(root, {+ OK_TEST_TOKEN: 'secret-after',+ OK_TEST_EXTRA: 'on',+ });++ expect(reuseDecision(admitted, current)).toEqual({+ reuse: false,+ changedInputs: [],+ changedEnv: ['OK_TEST_EXTRA', 'OK_TEST_GIT_ENABLED', 'OK_TEST_TOKEN'],+ });+ expect(JSON.stringify([admitted, current])).not.toMatch(/secret-(?:before|after)/);+ });+});++const BUILD_OPTIONS = { mode: 'development', devHooks: true };++describe('prebuilt DEV output freshness', () => {+ test('an app source edit after the build refuses the recorded output and names the file', () => {+ const root = okTree();+ const recorded = prebuiltManifest(root, BUILD_OPTIONS);++ write(root, 'packages/app/src/App.tsx', 'export const App = () => "edited";\n');++ expect(prebuiltServingDecision(recorded, prebuiltManifest(root, BUILD_OPTIONS))).toEqual({+ serve: false,+ reason: 'stale',+ changedInputs: ['packages/app/src/App.tsx'],+ changedOptions: [],+ });+ });++ test('core, server, dependency pins, locale catalogs and HTML entries are all inputs of the recorded output', () => {+ const edits = [+ ['packages/core/src/index.ts', 'export const core = 2;\n'],+ ['packages/server/src/index.ts', 'export const server = 2;\n'],+ ['pnpm-lock.yaml', "lockfileVersion: '9.0'\nimporters: {}\n"],+ ['packages/app/src/locales/es/messages.po', 'msgid "Save"\nmsgstr "Guardar"\n'],+ ['packages/app/index.html', '<!doctype html><div id="root"></div>\n'],+ ] as const;++ const decisions = edits.map(([path, content]) => {+ const root = okTree();+ const recorded = prebuiltManifest(root, BUILD_OPTIONS);+ write(root, path, content);+ return prebuiltServingDecision(recorded, prebuiltManifest(root, BUILD_OPTIONS));+ });++ expect(decisions).toEqual(+ edits.map(([path]) => ({+ serve: false,+ reason: 'stale',+ changedInputs: [path],+ changedOptions: [],+ })),+ );+ });++ test('a changed build option refuses the recorded output and names the option', () => {+ const root = okTree();+ const recorded = prebuiltManifest(root, BUILD_OPTIONS);++ expect(+ prebuiltServingDecision(+ recorded,+ prebuiltManifest(root, { ...BUILD_OPTIONS, devHooks: false }),+ ),+ ).toEqual({ serve: false, reason: 'stale', changedInputs: [], changedOptions: ['devHooks'] });+ });++ test('the output the build itself writes leaves the recorded manifest fresh', () => {+ const root = okTree();+ const recorded = prebuiltManifest(root, BUILD_OPTIONS);++ write(root, 'packages/app/dist/index.html', '<!doctype html>\n');+ write(root, 'packages/app/public/excalidraw-assets/fonts/Virgil.woff2', 'font\n');+ write(root, 'packages/core/dist/index.mjs', 'export const core = 1;\n');++ expect(prebuiltServingDecision(recorded, prebuiltManifest(root, BUILD_OPTIONS))).toEqual({+ serve: true,+ });+ });++ test('without a recorded manifest the prebuilt output is refused as missing', () => {+ const root = okTree();++ expect(prebuiltServingDecision(undefined, prebuiltManifest(root, BUILD_OPTIONS))).toEqual({+ serve: false,+ reason: 'missing',+ });+ });+});diff --git a/packages/app/tests/foundation/test-server-inputs.ts b/packages/app/tests/foundation/test-server-inputs.tsnew file mode 100644index 000000000..243226415--- /dev/null+++ b/packages/app/tests/foundation/test-server-inputs.ts@@ -0,0 +1,137 @@+import { createHash } from 'node:crypto';+import { globSync, readFileSync, statSync } from 'node:fs';+import { join, sep } from 'node:path';++export type InputDigests = Readonly<Record<string, string>>;++export const SERVER_RESTART_INPUTS = [+ 'package.json',+ 'pnpm-lock.yaml',+ 'pnpm-workspace.yaml',+ '.node-version',+ 'tsconfig.json',+ 'turbo.json',+ 'patches/**',+ 'packages/core/**',+ 'packages/server/**',+ 'packages/app/package.json',+ 'packages/app/tsconfig.json',+ 'packages/app/vite.*.ts',+ 'packages/app/postcss.config.ts',+ 'packages/app/lingui.config.ts',+ 'packages/app/scripts/**',+ 'packages/app/src/build/**',+ 'packages/app/src/server/**',+] as const;++export const PREBUILT_BUILD_INPUTS = [+ ...SERVER_RESTART_INPUTS,+ 'packages/app/*.html',+ 'packages/app/public/**',+ 'packages/app/src/**',+] as const;++const GENERATED_OUTPUTS = [+ '**/node_modules',+ '**/node_modules/**',+ '**/dist/**',+ '**/.turbo/**',+ 'packages/app/public/excalidraw-assets/**',+ 'packages/app/.excalidraw-assets-staging-*/**',+];++export type ServerFingerprint = {+ readonly digest: string;+ readonly inputs: InputDigests;+ readonly env: InputDigests;+};++export type ReuseDecision =+ | { readonly reuse: true }+ | {+ readonly reuse: false;+ readonly changedInputs: readonly string[];+ readonly changedEnv: readonly string[];+ };++const sha256 = (bytes: string | Buffer): string => createHash('sha256').update(bytes).digest('hex');++function sorted(entries: Iterable<readonly [string, string]>): InputDigests {+ return Object.fromEntries([...entries].sort(([left], [right]) => (left < right ? -1 : 1)));+}++export function digestInputs(okRoot: string, patterns: readonly string[]): InputDigests {+ const files = globSync([...patterns], { cwd: okRoot, exclude: GENERATED_OUTPUTS }).filter(+ (path) => statSync(join(okRoot, path)).isFile(),+ );+ return sorted(+ files.map((path) => [path.split(sep).join('/'), sha256(readFileSync(join(okRoot, path)))]),+ );+}++function digestValues(values: Readonly<Record<string, string>>): InputDigests {+ return sorted(Object.entries(values).map(([key, value]) => [key, sha256(value)]));+}++function changedKeys(before: InputDigests, after: InputDigests): string[] {+ const keys = new Set([...Object.keys(before), ...Object.keys(after)]);+ return [...keys].filter((key) => before[key] !== after[key]).sort();+}++export function serverFingerprint(+ okRoot: string,+ workerEnv: Readonly<Record<string, string>>,+): ServerFingerprint {+ const inputs = digestInputs(okRoot, SERVER_RESTART_INPUTS);+ const env = digestValues(workerEnv);+ return { digest: sha256(JSON.stringify({ inputs, env })), inputs, env };+}++export function reuseDecision(+ admitted: ServerFingerprint,+ current: ServerFingerprint,+): ReuseDecision {+ const changedInputs = changedKeys(admitted.inputs, current.inputs);+ const changedEnv = changedKeys(admitted.env, current.env);+ return changedInputs.length === 0 && changedEnv.length === 0+ ? { reuse: true }+ : { reuse: false, changedInputs, changedEnv };+}++export type BuildOptions = Readonly<Record<string, string | number | boolean>>;++export type PrebuiltManifest = {+ readonly digest: string;+ readonly inputs: InputDigests;+ readonly options: Readonly<Record<string, string>>;+};++export type PrebuiltServingDecision =+ | { readonly serve: true }+ | { readonly serve: false; readonly reason: 'missing' }+ | {+ readonly serve: false;+ readonly reason: 'stale';+ readonly changedInputs: readonly string[];+ readonly changedOptions: readonly string[];+ };++export function prebuiltManifest(okRoot: string, buildOptions: BuildOptions): PrebuiltManifest {+ const inputs = digestInputs(okRoot, PREBUILT_BUILD_INPUTS);+ const options = sorted(+ Object.entries(buildOptions).map(([key, value]) => [key, JSON.stringify(value)]),+ );+ return { digest: sha256(JSON.stringify({ inputs, options })), inputs, options };+}++export function prebuiltServingDecision(+ recorded: PrebuiltManifest | undefined,+ current: PrebuiltManifest,+): PrebuiltServingDecision {+ if (recorded === undefined) return { serve: false, reason: 'missing' };+ const changedInputs = changedKeys(recorded.inputs, current.inputs);+ const changedOptions = changedKeys(recorded.options, current.options);+ return changedInputs.length === 0 && changedOptions.length === 0+ ? { serve: true }+ : { serve: false, reason: 'stale', changedInputs, changedOptions };+}diff --git a/packages/app/tests/foundation/vitest.browser-reverse.config.ts b/packages/app/tests/foundation/vitest.browser-reverse.config.tsnew file mode 100644index 000000000..52b42819d--- /dev/null+++ b/packages/app/tests/foundation/vitest.browser-reverse.config.ts@@ -0,0 +1,27 @@+import { fileURLToPath } from 'node:url';+import { defineConfig, type ViteUserConfig } from 'vitest/config';+import { BaseSequencer, type TestSpecification } from 'vitest/node';+import { appBrowserVitestConfig } from '../../vitest.browser.config';++const APP_ROOT = fileURLToPath(new URL('../../', import.meta.url));++class DescendingPathSequencer extends BaseSequencer {+ override async sort(files: TestSpecification[]): Promise<TestSpecification[]> {+ return [...files].sort((left, right) => {+ if (left.moduleId < right.moduleId) return 1;+ return left.moduleId > right.moduleId ? -1 : 0;+ });+ }+}++export const appBrowserReverseVitestConfig = {+ ...appBrowserVitestConfig,+ root: APP_ROOT,+ test: {+ ...appBrowserVitestConfig.test,+ fileParallelism: false,+ sequence: { sequencer: DescendingPathSequencer },+ },+} satisfies ViteUserConfig;++export default defineConfig(appBrowserReverseVitestConfig);diff --git a/packages/app/tests/integration/dom-test-filename-stop-rule.test.ts b/packages/app/tests/integration/dom-test-filename-stop-rule.test.tsindex b2dc732e9..f45123197 100644--- a/packages/app/tests/integration/dom-test-filename-stop-rule.test.ts+++ b/packages/app/tests/integration/dom-test-filename-stop-rule.test.ts@@ -7,6 +7,32 @@ const SCAN_ROOTS = ['src', 'tests'] as const;const VALUE_RTL_IMPORT_PATTERN =/\bimport\s+(?!type\s)[\s\S]*?from\s+['"]@testing-library\/react['"]|\bimport\s+['"]@testing-library\/react['"]/;+const RTL_TIER_SUFFIXES = ['.dom.test.tsx', '.browser.test.tsx'] as const;++interface TestSource {+ path: string;+ source: string;+}++function isRtlTierFile(path: string): boolean {+ return RTL_TIER_SUFFIXES.some((suffix) => path.endsWith(suffix));+}++function rtlImportsOutsideRtlTiers(files: readonly TestSource[]): string[] {+ return files+ .filter((file) => !isRtlTierFile(file.path) && VALUE_RTL_IMPORT_PATTERN.test(file.source))+ .map((file) => file.path);+}++function rtlImportViolationMessage(violations: readonly string[]): string {+ return `Tier-3 filename contract violation — *.test.tsx (non-dom) files MUST NOT import a value from @testing-library/react:\n${violations+ .map((p) => ` - ${p}`)+ .join(+ '\n',+ )}\n\nFix: rename to *.dom.test.tsx (NG6 escape hatch — per-file migration allowed when the file is a natural Tier-3 candidate), or to *.browser.test.tsx when it belongs in the production-compiled browser tier, OR remove the @testing-library/react value import. Type-only imports (\`import type { X } from '@testing-library/react'\`) are exempt — they erase at compile time and don't trigger module evaluation.`;+}++const PLANTED_RTL_IMPORT = "import { render, screen } from '@testing-library/react';";function listTestTsxFiles(): string[] {const results: string[] = [];@@ -43,22 +69,40 @@ describe('Tier-3 filename contract — *.dom.test.tsx ↔ @testing-library/reactexpect(violations).toEqual([]);});- test('no non-dom *.test.tsx imports @testing-library/react (type-only imports exempt)', () => {- const nonDomTsxTests = listTestTsxFiles().filter((p) => !p.endsWith('.dom.test.tsx'));- expect(nonDomTsxTests.length).toBeGreaterThan(0);- const violations = nonDomTsxTests.filter((path) => {- const src = readFileSync(path, 'utf-8');- return VALUE_RTL_IMPORT_PATTERN.test(src);- });+ test('no *.test.tsx outside the dom and browser tiers imports @testing-library/react (type-only imports exempt)', () => {+ const outsideRtlTiers = listTestTsxFiles().filter((p) => !isRtlTierFile(p));+ expect(outsideRtlTiers.length).toBeGreaterThan(0);+ const violations = rtlImportsOutsideRtlTiers(+ outsideRtlTiers.map((path) => ({ path, source: readFileSync(path, 'utf-8') })),+ );if (violations.length > 0) {- throw new Error(- `Tier-3 filename contract violation — *.test.tsx (non-dom) files MUST NOT import a value from @testing-library/react:\n${violations- .map((p) => ` - ${p}`)- .join(- '\n',- )}\n\nFix: rename to *.dom.test.tsx (NG6 escape hatch — per-file migration allowed when the file is a natural Tier-3 candidate), OR remove the @testing-library/react value import. Type-only imports (\`import type { X } from '@testing-library/react'\`) are exempt — they erase at compile time and don't trigger module evaluation.`,- );+ throw new Error(rtlImportViolationMessage(violations));}expect(violations).toEqual([]);});++ test('a value import of @testing-library/react in a Node-tier *.test.tsx is reported', () => {+ const violations = rtlImportsOutsideRtlTiers([+ { path: 'src/components/Planted.test.tsx', source: PLANTED_RTL_IMPORT },+ ]);++ expect(violations).toEqual(['src/components/Planted.test.tsx']);+ expect(rtlImportViolationMessage(violations)).toMatch(+ /^Tier-3 filename contract violation — \*\.test\.tsx \(non-dom\) files MUST NOT import a value from @testing-library\/react:\n {2}- src\/components\/Planted\.test\.tsx\n\nFix: /,+ );+ });++ test('a *.browser.test.tsx importing @testing-library/react is admitted beside the dom tier and type-only imports', () => {+ const violations = rtlImportsOutsideRtlTiers([+ { path: 'tests/foundation/planted.browser.test.tsx', source: PLANTED_RTL_IMPORT },+ { path: 'src/components/Planted.dom.test.tsx', source: PLANTED_RTL_IMPORT },+ {+ path: 'src/components/TypeOnly.test.tsx',+ source: "import type { RenderResult } from '@testing-library/react';",+ },+ { path: 'src/components/Planted.test.tsx', source: PLANTED_RTL_IMPORT },+ ]);++ expect(violations).toEqual(['src/components/Planted.test.tsx']);+ });});diff --git a/packages/app/tests/meta/browser-destination-launch.test.ts b/packages/app/tests/meta/browser-destination-launch.test.tsnew file mode 100644index 000000000..62008dfc2--- /dev/null+++ b/packages/app/tests/meta/browser-destination-launch.test.ts@@ -0,0 +1,183 @@+import { execFile } from 'node:child_process';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { afterEach, describe, expect, test } from 'vitest';+import {+ BROWSER_TIER_COMMAND,+ CHROMIUM_GC_FORCE_ENV,+ CHROMIUM_GC_THRESHOLD_ENV,+ readChromiumGcLaunchEnv,+} from '../foundation/chromium-gc-launch-env';++const APP_ROOT = fileURLToPath(new URL('../../', import.meta.url));+const VITEST_CLI = resolve(+ dirname(fileURLToPath(import.meta.resolve('vitest/package.json'))),+ 'vitest.mjs',+);+const RUN_TIMEOUT_MS = 20_000;+const GB = 1024 ** 3;+const FREE_TEMP_BYTES = 80 * GB;+const LAUNCH_SETTINGS = { [CHROMIUM_GC_THRESHOLD_ENV]: '100000', [CHROMIUM_GC_FORCE_ENV]: '1' };++type CliRun = { exitCode: number | string | null; killed: boolean; output: string };++const scratch: string[] = [];++function scratchConfig(source: string): string {+ const dir = mkdtempSync(join(tmpdir(), 'ok-browser-tier-'));+ scratch.push(dir);+ const config = join(dir, 'vitest.browser.config.mts');+ writeFileSync(config, source);+ return config;+}++afterEach(() => {+ for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function runBrowserTier(+ args: string[],+ gcEnv: Record<string, string>,+ config = 'vitest.browser.config.ts',+): Promise<CliRun> {+ const env: NodeJS.ProcessEnv = { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1', ...gcEnv };+ if (!(CHROMIUM_GC_THRESHOLD_ENV in gcEnv)) delete env[CHROMIUM_GC_THRESHOLD_ENV];+ if (!(CHROMIUM_GC_FORCE_ENV in gcEnv)) delete env[CHROMIUM_GC_FORCE_ENV];+ return new Promise((resolveRun) => {+ execFile(+ process.execPath,+ [VITEST_CLI, 'run', '--config', config, ...args],+ { cwd: APP_ROOT, env, timeout: RUN_TIMEOUT_MS },+ (error, stdout, stderr) => {+ resolveRun({+ exitCode: error?.code ?? 0,+ killed: error?.killed ?? false,+ output: `${stdout}\n${stderr}`,+ });+ },+ );+ });+}++describe('the browser tier launch environment', () => {+ test('the documented threshold and force settings are accepted', () => {+ expect(+ readChromiumGcLaunchEnv(+ { [CHROMIUM_GC_THRESHOLD_ENV]: '100000', [CHROMIUM_GC_FORCE_ENV]: '1' },+ FREE_TEMP_BYTES,+ ),+ ).toEqual({ ok: true, thresholdBytes: 100000 * GB });+ });++ test('an environment missing both settings names each one', () => {+ expect(readChromiumGcLaunchEnv({}, FREE_TEMP_BYTES)).toEqual({+ ok: false,+ problems: [+ 'VITEST_CHROMIUM_GC_DISK_THRESHOLD_GB is not set',+ 'VITEST_CHROMIUM_GC_FORCE is not set',+ ],+ });+ });++ test.each(['', ' ', 'abc', '0', '-5', 'Infinity'])(+ 'a threshold of %j is refused as not a positive number of GB',+ (threshold) => {+ expect(+ readChromiumGcLaunchEnv(+ { [CHROMIUM_GC_THRESHOLD_ENV]: threshold, [CHROMIUM_GC_FORCE_ENV]: '1' },+ FREE_TEMP_BYTES,+ ),+ ).toEqual({+ ok: false,+ problems: [+ `VITEST_CHROMIUM_GC_DISK_THRESHOLD_GB=${threshold} is not a positive number of GB`,+ ],+ });+ },+ );++ test('a threshold at the free temp space is refused, because Vitest would then skip the collection, and one just above it is accepted', () => {+ const atFreeSpace = readChromiumGcLaunchEnv(+ { [CHROMIUM_GC_THRESHOLD_ENV]: '80', [CHROMIUM_GC_FORCE_ENV]: '1' },+ FREE_TEMP_BYTES,+ );+ expect(atFreeSpace.ok).toBe(false);+ expect(atFreeSpace.ok ? [] : atFreeSpace.problems).toEqual([+ 'VITEST_CHROMIUM_GC_DISK_THRESHOLD_GB=80 does not exceed the 80.0 GB free in the temp directory, so Vitest would skip the collection after each file',+ ]);+ expect(+ readChromiumGcLaunchEnv(+ { [CHROMIUM_GC_THRESHOLD_ENV]: '80.5', [CHROMIUM_GC_FORCE_ENV]: '1' },+ FREE_TEMP_BYTES,+ ).ok,+ ).toBe(true);+ });++ test.each(['', '0', 'true'])('a force setting of %j is refused as not 1', (force) => {+ expect(+ readChromiumGcLaunchEnv(+ { [CHROMIUM_GC_THRESHOLD_ENV]: '100000', [CHROMIUM_GC_FORCE_ENV]: force },+ FREE_TEMP_BYTES,+ ),+ ).toEqual({ ok: false, problems: [`VITEST_CHROMIUM_GC_FORCE=${force} is not 1`] });+ });++ test('the browser tier invocation refuses to start without the launch settings and names the documented command', async () => {+ const run = await runBrowserTier(+ ['tests/foundation/compiled-destination.browser.test.tsx'],+ {},+ );++ expect(run.killed).toBe(false);+ expect(run.exitCode).toBe(1);+ expect(run.output).toContain('The browser tier refuses to start');+ expect(run.output).toContain(`Run it as: ${BROWSER_TIER_COMMAND}`);+ expect(run.output).not.toContain('Test Files');+ });++ test('a browser tier invocation that selects no test file fails instead of passing', async () => {+ const run = await runBrowserTier(['tests/foundation/no-such-browser-test'], LAUNCH_SETTINGS);++ expect(run.killed).toBe(false);+ expect(run.exitCode).toBe(1);+ expect(run.output).toContain('No test files found');+ expect(run.output).not.toContain('passed');+ });++ test('a malformed browser tier config fails the invocation instead of passing', async () => {+ const config = scratchConfig(+ "export default { test: { browser: { enabled: true, instances: [{ browser: 'chromium' }] }\n",+ );++ const run = await runBrowserTier([], LAUNCH_SETTINGS, config);++ expect(run.killed).toBe(false);+ expect(run.exitCode).toBe(1);+ expect(run.output).toContain(`failed to load config from ${config}`);+ expect(run.output).not.toContain('Test Files');+ });++ test('a browser tier config that names no browser instance fails instead of running nothing', async () => {+ const config = scratchConfig(+ [+ `import { appBrowserVitestConfig } from ${JSON.stringify(join(APP_ROOT, 'vitest.browser.config.ts'))};`,+ 'const { test } = appBrowserVitestConfig;',+ 'export default { ...appBrowserVitestConfig, test: { ...test, browser: { ...test.browser, instances: [] } } };',+ '',+ ].join('\n'),+ );++ const run = await runBrowserTier(+ ['tests/foundation/compiled-destination.browser.test.tsx'],+ LAUNCH_SETTINGS,+ config,+ );++ expect(run.killed).toBe(false);+ expect(run.exitCode).toBe(1);+ expect(run.output).toContain("Vitest wasn't able to resolve any project");+ expect(run.output).not.toContain('Test Files');+ });+});diff --git a/packages/app/tests/meta/browser-node-compat.test.ts b/packages/app/tests/meta/browser-node-compat.test.tsnew file mode 100644index 000000000..5e916558e--- /dev/null+++ b/packages/app/tests/meta/browser-node-compat.test.ts@@ -0,0 +1,98 @@+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { nodeSubstituteFor, resolveBridgePath } from '../foundation/browser-node-compat';++describe('the browser file bridge confines reads to its declared roots', () => {+ let scratch: string;+ let root: string;++ beforeEach(() => {+ scratch = realpathSync(mkdtempSync(join(tmpdir(), 'ok-file-bridge-')));+ root = join(scratch, 'root');+ mkdirSync(root);+ writeFileSync(join(root, 'inside.txt'), 'inside');+ writeFileSync(join(scratch, 'outside.txt'), 'outside');+ symlinkSync(join(scratch, 'outside.txt'), join(root, 'escape.txt'));+ symlinkSync(join(root, 'inside.txt'), join(root, 'alias.txt'));+ });++ afterEach(() => {+ rmSync(scratch, { recursive: true, force: true });+ });++ test('a file inside a root resolves to its real path', () => {+ expect(resolveBridgePath(join(root, 'inside.txt'), [root])).toEqual({+ ok: true,+ path: join(root, 'inside.txt'),+ });+ });++ test('a symlink inside a root that points at a file inside it resolves to the target', () => {+ expect(resolveBridgePath(join(root, 'alias.txt'), [root])).toEqual({+ ok: true,+ path: join(root, 'inside.txt'),+ });+ });++ test('a symlink inside a root that points outside every root is refused', () => {+ expect(resolveBridgePath(join(root, 'escape.txt'), [root])).toEqual({+ ok: false,+ status: 403,+ reason: `EACCES: ${join(root, 'escape.txt')} resolves through a symlink outside the declared roots`,+ });+ });++ test('a path outside every root is refused, and so is a dot-dot segment even when it lands inside', () => {+ expect(resolveBridgePath(join(scratch, 'outside.txt'), [root])).toMatchObject({+ ok: false,+ status: 403,+ });+ expect(resolveBridgePath(`${root}/../root/inside.txt`, [root])).toEqual({+ ok: false,+ status: 403,+ reason: `EACCES: ${root}/../root/inside.txt: path traversal is refused`,+ });+ });++ test('a missing file inside a root resolves, so the read reports it as missing', () => {+ expect(resolveBridgePath(join(root, 'absent.txt'), [root])).toEqual({+ ok: true,+ path: join(root, 'absent.txt'),+ });+ });++ test('a relative path is refused as not absolute', () => {+ expect(resolveBridgePath('inside.txt', [root])).toMatchObject({ ok: false, status: 400 });+ });+});++describe('node: imports are substituted for test modules only', () => {+ const APP = '/repo/public/open-knowledge/packages/app';++ test('a test file, a test helper and a test-support module get the substitute', () => {+ for (const importer of [+ `${APP}/src/lib/thing.dom.test.ts`,+ `${APP}/src/test-utils/helper.ts`,+ `${APP}/tests/foundation/case.browser.test.ts`,+ '/repo/public/open-knowledge/test-support/known-bug.test-helper.ts',+ ]) {+ expect(nodeSubstituteFor('node:fs', importer)).toMatch(+ /tests\/foundation\/node-substitutes\/fs\.ts$/,+ );+ }+ });++ test('product source and dependencies keep the unsubstituted builtin', () => {+ expect(nodeSubstituteFor('node:fs', `${APP}/src/lib/thing.ts`)).toBeNull();+ expect(nodeSubstituteFor('node:fs', `${APP}/node_modules/dep/index.test.js`)).toBeNull();+ });++ test('only the six declared modules are substituted', () => {+ expect(+ nodeSubstituteFor('node:child_process', `${APP}/tests/foundation/case.browser.test.ts`),+ ).toBeNull();+ expect(nodeSubstituteFor('fs', `${APP}/tests/foundation/case.browser.test.ts`)).toBeNull();+ });+});diff --git a/packages/app/tests/meta/node-destination-launch.test.ts b/packages/app/tests/meta/node-destination-launch.test.tsnew file mode 100644index 000000000..5d9fd22fb--- /dev/null+++ b/packages/app/tests/meta/node-destination-launch.test.ts@@ -0,0 +1,121 @@+import { execFile } from 'node:child_process';+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { afterEach, describe, expect, test } from 'vitest';++const APP_ROOT = fileURLToPath(new URL('../../', import.meta.url));+const VITEST_CLI = resolve(+ dirname(fileURLToPath(import.meta.resolve('vitest/package.json'))),+ 'vitest.mjs',+);+const FIXTURE_CONFIG = 'tests/foundation/fixtures/vitest.node-fixture.config.ts';+const RUN_TIMEOUT_MS = 20_000;++type CliRun = { exitCode: number | string | null; killed: boolean; output: string };++type ReportedTest = { title: string; status: string; failureMessages: string[] };+type ReportedFile = { name: string; status: string; assertionResults: ReportedTest[] };++const scratch: string[] = [];++function scratchDir(): string {+ const dir = mkdtempSync(join(tmpdir(), 'ok-node-tier-'));+ scratch.push(dir);+ return dir;+}++afterEach(() => {+ for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function runVitest(args: string[]): Promise<CliRun> {+ return new Promise((resolveRun) => {+ execFile(+ process.execPath,+ [VITEST_CLI, 'run', ...args],+ {+ cwd: APP_ROOT,+ env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' },+ timeout: RUN_TIMEOUT_MS,+ },+ (error, stdout, stderr) => {+ resolveRun({+ exitCode: error?.code ?? 0,+ killed: error?.killed ?? false,+ output: `${stdout}\n${stderr}`,+ });+ },+ );+ });+}++describe('the Node tier invocation', () => {+ test('a Node tier invocation that selects no test file fails instead of passing', async () => {+ const run = await runVitest([+ '--config',+ 'vitest.node.config.ts',+ 'tests/foundation/no-such-node-test',+ ]);++ expect(run.killed).toBe(false);+ expect(run.exitCode).toBe(1);+ expect(run.output).toContain('No test files found');+ expect(run.output).not.toContain('passed');+ });++ test('a malformed Node tier config fails the invocation instead of passing', async () => {+ const config = join(scratchDir(), 'vitest.node.config.ts');+ writeFileSync(config, "export default { test: { include: ['**/*.node.test.ts'] }\n");++ const run = await runVitest(['--config', config]);++ expect(run.killed).toBe(false);+ expect(run.exitCode).toBe(1);+ expect(run.output).toContain(`failed to load config from ${config}`);+ expect(run.output).not.toContain('Test Files');+ });++ test('a Node test that defines a DOM global fails, at module load or while it runs, and a DOM-free neighbour still passes', async () => {+ const report = join(scratchDir(), 'report.json');++ const run = await runVitest([+ '--config',+ FIXTURE_CONFIG,+ '--reporter=json',+ `--outputFile=${report}`,+ ]);++ expect(run.killed).toBe(false);+ expect(run.exitCode).toBe(1);+ const files = (JSON.parse(readFileSync(report, 'utf8')) as { testResults: ReportedFile[] })+ .testResults;+ const verdicts = Object.fromEntries(+ files.map((file) => [+ basename(file.name),+ file.assertionResults.map((result) => ({+ status: result.status,+ message: result.failureMessages.join('\n').split('\n')[0],+ })),+ ]),+ );+ expect(verdicts).toEqual({+ 'dom-free.node-fixture.ts': [{ status: 'passed', message: '' }],+ 'dom-defined-at-load.node-fixture.ts': [+ {+ status: 'failed',+ message:+ 'Error: The Node destination runs without a DOM, but window is defined before this test runs. A test that needs a DOM belongs in the browser destination (*.browser.test.ts?(x)); otherwise remove what installs it.',+ },+ ],+ 'dom-defined-in-test.node-fixture.ts': [+ {+ status: 'failed',+ message:+ 'Error: The Node destination runs without a DOM, but localStorage is defined after this test ran. A test that needs a DOM belongs in the browser destination (*.browser.test.ts?(x)); otherwise remove what installs it.',+ },+ ],+ });+ });+});diff --git a/packages/app/tsconfig.json b/packages/app/tsconfig.jsonindex 87c76b29a..097b0bc1e 100644--- a/packages/app/tsconfig.json+++ b/packages/app/tsconfig.json@@ -84,6 +84,7 @@"include": ["src","*.ts",+ "tests/foundation","tests/stress/fixtures","tests/half-open-forced-close.test-helper.ts","tests/integration/audit-barrier.test-helper.ts",diff --git a/packages/app/vitest.browser.config.ts b/packages/app/vitest.browser.config.tsnew file mode 100644index 000000000..c35e95eac--- /dev/null+++ b/packages/app/vitest.browser.config.ts@@ -0,0 +1,86 @@+import { fileURLToPath } from 'node:url';+import babel from '@rolldown/plugin-babel';+import react from '@vitejs/plugin-react';+import { playwright } from '@vitest/browser-playwright';+import { configDefaults, defineConfig, type ViteUserConfig } from 'vitest/config';+import { okVitestBase } from '../../test-support/vitest.base';+import { runBrowserFixture } from './tests/foundation/browser-fixture-command';+import { withMockContracts } from './tests/foundation/browser-mock-provider';+import {+ installNetworkGuard,+ takeBlockedNetworkRequests,+} from './tests/foundation/browser-network-guard';+import {+ BROWSER_PRODUCT_MODULE_EXCLUDES,+ BROWSER_TEST_MODULES,+ browserCiValue,+ browserNodeSubstitutes,+ NODE_MODULES,+} from './tests/foundation/browser-node-compat';+import { chromiumGcLaunchEnvGuard } from './tests/foundation/chromium-gc-launch-env';+import { RENDERER_DEDUPE } from './vite.dedupe';+import { RENDERER_BABEL_OPTIONS } from './vite.react-babel';++const srcDir = fileURLToPath(new URL('./src/', import.meta.url));++const BROWSER_FILE_BRIDGE_ROOTS = [+ srcDir,+ fileURLToPath(new URL('./tests/', import.meta.url)),+ fileURLToPath(new URL('../../test-support/', import.meta.url)),+];++export const APP_BROWSER_SETUP_FILES = [+ fileURLToPath(new URL('./tests/foundation/browser-setup.ts', import.meta.url)),+];++const BROWSER_TEST_FILES = '**/*.browser.test.ts?(x)';++export const appBrowserVitestConfig = {+ plugins: [+ ...okVitestBase.plugins,+ chromiumGcLaunchEnvGuard(),+ browserCiValue(process.env),+ browserNodeSubstitutes(BROWSER_FILE_BRIDGE_ROOTS),+ react(),+ babel({ ...RENDERER_BABEL_OPTIONS, exclude: [...BROWSER_PRODUCT_MODULE_EXCLUDES] }),+ babel({+ plugins: RENDERER_BABEL_OPTIONS.plugins,+ include: [...BROWSER_TEST_MODULES],+ exclude: [NODE_MODULES],+ }),+ ],+ resolve: {+ conditions: ['module', 'browser', 'development'],+ alias: [{ find: /^@\//, replacement: srcDir }],+ dedupe: [...RENDERER_DEDUPE],+ },+ optimizeDeps: { force: true },+ test: {+ testTimeout: okVitestBase.test.testTimeout,+ hookTimeout: okVitestBase.test.hookTimeout,+ env: okVitestBase.test.env,+ clearMocks: okVitestBase.test.clearMocks,+ expect: okVitestBase.test.expect,+ tags: okVitestBase.test.tags,+ include: [BROWSER_TEST_FILES],+ exclude: [+ ...okVitestBase.test.exclude.filter((pattern) => pattern !== BROWSER_TEST_FILES),+ 'public/excalidraw-assets/**',+ '.excalidraw-assets-staging-*',+ ],+ setupFiles: APP_BROWSER_SETUP_FILES,+ reporters: [...configDefaults.reporters, 'json'],+ outputFile: { json: 'test-results/vitest-browser.json' },+ isolate: true,+ browser: {+ enabled: true,+ provider: withMockContracts(playwright()),+ headless: true,+ screenshotFailures: false,+ instances: [{ browser: 'chromium' }],+ commands: { runBrowserFixture, installNetworkGuard, takeBlockedNetworkRequests },+ },+ },+} satisfies ViteUserConfig;++export default defineConfig(appBrowserVitestConfig);diff --git a/packages/app/vitest.node.config.ts b/packages/app/vitest.node.config.tsnew file mode 100644index 000000000..dd28c8773--- /dev/null+++ b/packages/app/vitest.node.config.ts@@ -0,0 +1,28 @@+import { fileURLToPath } from 'node:url';+import { configDefaults, defineConfig, type ViteUserConfig } from 'vitest/config';+import { okVitestBase } from '../../test-support/vitest.base';++export const APP_NODE_SETUP_FILES = [+ ...okVitestBase.test.setupFiles,+ fileURLToPath(new URL('./tests/foundation/node-destination-setup.ts', import.meta.url)),+];++const NODE_TEST_FILES = '**/*.node.test.ts?(x)';++export const appNodeVitestConfig = {+ ...okVitestBase,+ test: {+ ...okVitestBase.test,+ include: [NODE_TEST_FILES],+ exclude: [+ ...okVitestBase.test.exclude.filter((pattern) => pattern !== NODE_TEST_FILES),+ 'public/excalidraw-assets/**',+ '.excalidraw-assets-staging-*',+ ],+ setupFiles: APP_NODE_SETUP_FILES,+ reporters: [...configDefaults.reporters, 'json'],+ outputFile: { json: 'test-results/vitest-node.json' },+ },+} satisfies ViteUserConfig;++export default defineConfig(appNodeVitestConfig);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d0e3c8c94..28e0cd350 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -216,7 +216,7 @@ importers:version: 7.29.0vitest:specifier: ^5.0.3- version: 5.0.3(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.3(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))yaml:specifier: ^2.8.3version: 2.9.0@@ -753,6 +753,9 @@ importers:'@vitejs/plugin-react':specifier: ^6.0.1version: 6.0.1(@rolldown/[email protected](@babel/[email protected]([email protected]))(@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ '@vitest/browser-playwright':+ specifier: ^5.0.3+ version: 5.0.3([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])axe-core:specifier: ~4.12.1version: 4.12.1@@ -1157,7 +1160,7 @@ importers:version: 7.0.2vitest:specifier: ^5.0.3- version: 5.0.3(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.3(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))y-prosemirror:specifier: 1.3.7version: 1.3.7(patch_hash=b77fc38bdf246f08f73b6bc5d12ec24d29408b663f0a4224758d3f776ef124e7)([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])@@ -1686,6 +1689,9 @@ packages:cpu: [x64]os: [win32]+ '@blazediff/[email protected]':+ resolution: {integrity: sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==}+'@borewit/[email protected]':resolution: {integrity: sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ==}@@ -6433,6 +6439,17 @@ packages:babel-plugin-react-compiler:optional: true+ '@vitest/[email protected]':+ resolution: {integrity: sha512-rYBHwIFL/ZtI6dl0rbrAatScXCrvX+TL2BX2AGOigkC1Y6u3rIWw8KMQJJMS4drSa1ksMCmZU2wpgwdE7kqu3g==}+ peerDependencies:+ playwright: '*'+ vitest: 5.0.3++ '@vitest/[email protected]':+ resolution: {integrity: sha512-7KHIkVA/gTRxQV9qPa9qLK+g5INZG6iRrlwXSFG5EKsOomW3UzzW7wsdt1Yp5PufzQ43lniuONlb4lUVCC2qSg==}+ peerDependencies:+ vitest: 5.0.3+'@vitest/[email protected]':resolution: {integrity: sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==}peerDependencies:@@ -6444,9 +6461,20 @@ packages:vite:optional: true+ '@vitest/[email protected]':+ resolution: {integrity: sha512-3hr5eV5z2ff0l2Q1vaKQbB4j3M3tElw8stDokEOTqXJB3Es5VrT8gBRIMY59gGuFp8Y61sWlWFK1aNUH5dHDYw==}+'@vitest/[email protected]':resolution: {integrity: sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-9dfvqDBvSbHM6y9YVXxAypkl2z7mrWozK/JFo237qI0cj/3M/kzDKiVZqzi3TE54Ler7Jditud7OMBZCyUvRHA==}+ peerDependencies:+ vitest: 5.0.3++ '@vitest/[email protected]':+ resolution: {integrity: sha512-77fDTZv8eu1CzlIfgPU2yrl5MXSUaUAOvgdZEeVm3X3WIxUubIX2SforqS6176lT32HCF6uBVMYVqfHxw7o6eg==}+'@xmldom/[email protected]':resolution: {integrity: sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==}engines: {node: '>=10.0.0'}@@ -8156,6 +8184,9 @@ packages:resolution: {integrity: sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==}+ resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}+resolution: {integrity: sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==}engines: {node: '>=18'}@@ -8191,6 +8222,9 @@ packages:resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==}engines: {node: '>=8'}+ resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==}+resolution: {integrity: sha512-/kXzuDnnBqyyWyhDMH7+PfP8J/oXiAavGzcRxASOMRHFuReDtofizLLJsf7nnDLAfEaMW4pVWaXrAjtnglpEkg==}engines: {node: '>=12'}@@ -10235,6 +10269,9 @@ packages:resolution: {integrity: sha512-aXXC6s+1w7otVF9UletFkFcDsJeO7lSZBPUQhtb5O0xJe8LtYhj/GxldoL09bBj9+ZmE2hNoHqQSFMN5fikh4Q==}+ resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}+resolution: {integrity: sha512-YxFb+SQcodN2rnX9Tn3dHYlqfb7NjlzzfONPpJd+AKoKtUjEdevTfbC07d5TcczzOK6261auRkP/M8OBHs9vFQ==}engines: {node: '>=22.13.0 || >=24'}@@ -10320,6 +10357,10 @@ packages:resolution: {integrity: sha512-ZiVwF5EJ0DNZyzAqld8BP1qyJBaGOFaq9zl579qfbkcmOwWLLO4I9L8i2O4j3HkI6/35i0nKG2n+dZplxiT89Q==}+ resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==}+ engines: {node: '>=14.19.0'}+resolution: {integrity: sha512-sz1pnjgEfPyZ+QvaeX3NtCmbYnEvG01LZRLoN/uXoLtPZtxCIH5IctL7yXXc0fFyk/fqV6K8g3hlNfr6IJwupA==}engines: {node: '>=20'}@@ -11514,6 +11555,10 @@ packages:resolution: {integrity: sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw==}engines: {node: ^20.0.0 || >=22.0.0}+ resolution: {integrity: sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==}+ engines: {node: '>=14.0.0'}+resolution: {integrity: sha512-c1P7u0EhACHj7lPy4MJm8iTFEU8+nB0LCtddH0fhP7noaVoXAqafMtOOeX+ulpuPBqnrRgRhw494RICT3mbhnw==}@@ -12107,6 +12152,18 @@ packages:utf-8-validate:optional: true+ resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==}+ engines: {node: '>=10.0.0'}+ peerDependencies:+ bufferutil: ^4.0.1+ utf-8-validate: '>=5.0.2'+ peerDependenciesMeta:+ bufferutil:+ optional: true+ utf-8-validate:+ optional: true+resolution: {integrity: sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg==}engines: {node: '>=20'}@@ -12545,6 +12602,8 @@ snapshots:'@biomejs/[email protected]':optional: true+ '@blazediff/[email protected]': {}+'@borewit/[email protected]': {}'@braintree/[email protected]': {}@@ -17199,6 +17258,37 @@ snapshots:'@rolldown/plugin-babel': 0.2.2(@babel/[email protected]([email protected]))(@babel/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))babel-plugin-react-compiler: 0.0.0-experimental-a8e64ef-20260402+ '@vitest/[email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':+ dependencies:+ '@vitest/browser': 5.0.3([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ '@vitest/mocker': 5.0.3([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ playwright: 1.63.0+ tinyrainbow: 3.2.0+ vitest: 5.0.3(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ transitivePeerDependencies:+ - bufferutil+ - msw+ - utf-8-validate+ - vite++ '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':+ dependencies:+ '@blazediff/core': 1.10.0+ '@vitest/mocker': 5.0.3([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ '@vitest/ui': 5.0.3([email protected])+ '@vitest/utils': 5.0.3+ magic-string: 1.4.2+ pngjs: 7.0.0+ sirv: 3.0.2+ tinyrainbow: 3.2.0+ vitest: 5.0.3(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ ws: 8.22.0+ transitivePeerDependencies:+ - bufferutil+ - msw+ - utf-8-validate+ - vite+'@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@jridgewell/trace-mapping': 0.3.31@@ -17208,8 +17298,28 @@ snapshots:optionalDependencies:vite: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ '@vitest/[email protected]':+ dependencies:+ tinyrainbow: 3.2.0+'@vitest/[email protected]': {}+ '@vitest/[email protected]([email protected])':+ dependencies:+ '@vitest/utils': 5.0.3+ fflate: 0.8.3+ flatted: 3.4.4+ pathe: 2.0.3+ sirv: 3.0.2+ tinyrainbow: 3.2.0+ vitest: 5.0.3(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))++ '@vitest/[email protected]':+ dependencies:+ '@vitest/pretty-format': 5.0.3+ convert-source-map: 2.0.0+ tinyrainbow: 3.2.0+'@xmldom/[email protected]': {}'@xterm/[email protected]': {}@@ -19046,6 +19156,8 @@ snapshots:+ [email protected]: {}+dependencies:is-unicode-supported: 2.1.0@@ -19105,6 +19217,8 @@ snapshots:locate-path: 5.0.0path-exists: 4.0.0+ [email protected]: {}+dependencies:d3-selection: 3.0.0@@ -21531,6 +21645,8 @@ snapshots:process: 0.11.10util: 0.10.4+ [email protected]: {}+optionalDependencies:'@napi-rs/canvas': 1.0.3@@ -21633,6 +21749,8 @@ snapshots:dependencies:crc-32: 0.3.0+ [email protected]: {}+@@ -23336,6 +23454,8 @@ snapshots:+ [email protected]: {}+@@ -23751,7 +23871,7 @@ snapshots:tsx: 4.23.0yaml: 2.9.0- [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@types/chai': 5.2.3'@vitest/mocker': 5.0.3([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))@@ -23770,6 +23890,8 @@ snapshots:optionalDependencies:'@opentelemetry/api': 1.9.1'@types/node': 24.13.3+ '@vitest/browser-playwright': 5.0.3([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ '@vitest/ui': 5.0.3([email protected])happy-dom: 20.10.6jsdom: 29.1.1(@noble/[email protected])transitivePeerDependencies:@@ -23920,6 +24042,8 @@ snapshots:+ [email protected]: {}+dependencies:is-wsl: 3.1.1diff --git a/test-support/no-net-connect-loopback.ts b/test-support/no-net-connect-loopback.tsnew file mode 100644index 000000000..10e9a7c29--- /dev/null+++ b/test-support/no-net-connect-loopback.ts@@ -0,0 +1,13 @@+const IPV4_OCTET = '(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)';+const LOOPBACK_V4_RE = new RegExp(`^127\\.${IPV4_OCTET}\\.${IPV4_OCTET}\\.${IPV4_OCTET}$`);++const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1']);++export function isLoopbackHostname(hostname: string): boolean {+ const bare =+ hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;+ const lower = bare.toLowerCase();+ if (LOOPBACK_HOSTNAMES.has(lower)) return true;+ if (lower.endsWith('.localhost')) return true;+ return LOOPBACK_V4_RE.test(lower);+}diff --git a/test-support/no-net-connect.ts b/test-support/no-net-connect.tsindex 8b16a3873..daa9e1d5c 100644--- a/test-support/no-net-connect.ts+++ b/test-support/no-net-connect.ts@@ -1,6 +1,9 @@import { AsyncLocalStorage } from 'node:async_hooks';import { type Dispatcher, getGlobalDispatcher } from 'undici';import { aroundAll, aroundEach, type RunnerTask } from 'vitest';+import { isLoopbackHostname } from './no-net-connect-loopback';++export { isLoopbackHostname };const INSTALLED = Symbol.for('ok.test.noNetConnect.installed');@@ -83,7 +86,10 @@ function checkTarget(target: URL, scope: BlockScope): void {blockHost(target.hostname, scope);}-function checkDispatchOrigin(origin: Dispatcher.DispatchOptions['origin'], scope: BlockScope): void {+function checkDispatchOrigin(+ origin: Dispatcher.DispatchOptions['origin'],+ scope: BlockScope,+): void {if (origin instanceof URL) {checkTarget(origin, scope);return;@@ -99,20 +105,6 @@ function checkDispatchOrigin(origin: Dispatcher.DispatchOptions['origin'], scopeblockHost(UNVERIFIABLE_ORIGIN, scope);}-const IPV4_OCTET = '(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)';-const LOOPBACK_V4_RE = new RegExp(`^127\\.${IPV4_OCTET}\\.${IPV4_OCTET}\\.${IPV4_OCTET}$`);--const LOOPBACK_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1']);--export function isLoopbackHostname(hostname: string): boolean {- const bare =- hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;- const lower = bare.toLowerCase();- if (LOOPBACK_HOSTNAMES.has(lower)) return true;- if (lower.endsWith('.localhost')) return true;- return LOOPBACK_V4_RE.test(lower);-}-function resolveTarget(input: unknown): URL | null {const base = typeof globalThis.location?.href === 'string' ? globalThis.location.href : undefined;const raw =diff --git a/test-support/setup-files-contract.test.ts b/test-support/setup-files-contract.test.tsindex aa416352c..16edeac32 100644--- a/test-support/setup-files-contract.test.ts+++ b/test-support/setup-files-contract.test.ts@@ -14,10 +14,15 @@ const TEST_CONFIG_FILENAME = /(?:^|\.)vitest[\w.-]*\.config\.m?[jt]s$/;const KNOWN_TEST_PROJECTS = ['docs/vitest.config.ts','docs/vitest.real-source.config.mts',+ 'packages/app/tests/foundation/fixtures/vitest.browser-fixture.config.ts',+ 'packages/app/tests/foundation/fixtures/vitest.node-fixture.config.ts',+ 'packages/app/tests/foundation/vitest.browser-reverse.config.ts',+ 'packages/app/vitest.browser.config.ts','packages/app/vitest.config.ts','packages/app/vitest.dom.config.ts','packages/app/vitest.fidelity.config.ts','packages/app/vitest.integration.config.ts',+ 'packages/app/vitest.node.config.ts','packages/cli/vitest.config.ts','packages/cli/vitest.e2e.config.ts','packages/core/vitest.config.ts',@@ -39,6 +44,15 @@ const KNOWN_BUILD_CONFIGS = [const REQUIRED_BASE_SETUP_FILES = ['bun-global-shim.ts', 'no-net-connect.ts'];+const BROWSER_PROJECT_SETUP_FILES: Readonly<Record<string, readonly string[]>> = {+ 'packages/app/tests/foundation/fixtures/vitest.browser-fixture.config.ts': ['browser-setup.ts'],+ 'packages/app/tests/foundation/vitest.browser-reverse.config.ts': ['browser-setup.ts'],+ 'packages/app/vitest.browser.config.ts': ['browser-setup.ts'],+};++const isBrowserProject = (relPath: string): boolean =>+ Object.hasOwn(BROWSER_PROJECT_SETUP_FILES, relPath);+const isTestConfig = (relPath: string): boolean => TEST_CONFIG_FILENAME.test(basename(relPath));function findConfigs(): string[] {@@ -120,7 +134,13 @@ describe('vitest setupFiles contract', () => {);});- test.each(configs.filter(isTestConfig))(+ test('every browser project is a tracked vitest project', () => {+ expect(+ Object.keys(BROWSER_PROJECT_SETUP_FILES).filter((relPath) => !configs.includes(relPath)),+ ).toEqual([]);+ });++ test.each(configs.filter((relPath) => isTestConfig(relPath) && !isBrowserProject(relPath)))('%s resolves setupFiles containing every entry the shared base installs',async (relPath) => {for (const { project, setupFiles } of await resolveSetupFiles(relPath)) {@@ -134,4 +154,21 @@ describe('vitest setupFiles contract', () => {}},);++ test.each(Object.entries(BROWSER_PROJECT_SETUP_FILES))(+ '%s resolves its browser setup files and none of the Node-only setup files the shared base installs',+ async (relPath, required) => {+ for (const { project, setupFiles } of await resolveSetupFiles(relPath)) {+ const names = setupFiles.map((entry) => basename(entry));+ expect(+ required.filter((name) => !names.includes(name)),+ `${project} resolves [${setupFiles.join(', ')}] without its browser setup.`,+ ).toEqual([]);+ expect(+ setupFiles.filter((entry) => okVitestBase.test.setupFiles.includes(entry)),+ `${project} loads a Node-only shared setup file into the browser.`,+ ).toEqual([]);+ }+ },+ );});diff --git a/test-support/vitest.base.ts b/test-support/vitest.base.tsindex fb9a77f3b..0474a3f6c 100644--- a/test-support/vitest.base.ts+++ b/test-support/vitest.base.ts@@ -61,6 +61,8 @@ export const okVitestBase = {'**/*.spec.*','**/*.e2e.*','**/*.dom.test.ts?(x)',+ '**/*.browser.test.ts?(x)',+ '**/*.node.test.ts?(x)',...UNCACHED_TEST_GLOBS,'**/dist/**','**/.next/**',diff --git a/turbo.json b/turbo.jsonindex 4c0a1fd11..9e3d0f515 100644--- a/turbo.json+++ b/turbo.json@@ -184,6 +184,19 @@"../md-conformance/corpora/typed-view-scripts.json"]},+ "test:browser": {+ "dependsOn": ["^build"],+ "cache": false,+ "passThroughEnv": [+ "VITEST_CHROMIUM_GC_DISK_THRESHOLD_GB",+ "VITEST_CHROMIUM_GC_FORCE",+ "DEBUG"+ ]+ },+ "test:node": {+ "dependsOn": ["^build"],+ "cache": false+ },"test:integration": {"dependsOn": ["^build"],"cache": true,