diff --git a/.github/workflows/compiler-platforms.yml b/.github/workflows/compiler-platforms.yml index ebb0f1f2e8..6185a2edf4 100644 --- a/.github/workflows/compiler-platforms.yml +++ b/.github/workflows/compiler-platforms.yml @@ -16,6 +16,7 @@ on: - 'packages/router-plugin/**' - 'packages/start-plugin-core/**' - 'packages/compiler-test-utils/**' + - 'packages/react-start-rsc/**' - 'pnpm-lock.yaml' - '.github/workflows/compiler-platforms.yml' schedule: @@ -92,6 +93,7 @@ jobs: --filter "@tanstack/router-generator..." --filter "@tanstack/router-plugin..." --filter "@tanstack/start-plugin-core..." + --filter "@tanstack/react-start-rsc..." --filter "tanstack-react-start-e2e-basic..." - name: Unit tests (fast tier) run: >- @@ -103,6 +105,11 @@ jobs: pnpm nx run-many --targets=test:implementation:unit --projects=@tanstack/router-generator,@tanstack/router-plugin,@tanstack/start-plugin-core --skip-nx-cache --outputStyle=static + - name: Noncompiler tests (runtime and build plumbing) + run: >- + pnpm nx run-many --targets=test:noncompiler + --projects=@tanstack/start-plugin-core,@tanstack/react-start-rsc + --skip-nx-cache --outputStyle=static - name: Integration smoke (no browser) run: >- pnpm nx run-many --targets=test:integration:smoke diff --git a/nx.json b/nx.json index 46ebd07538..d37700fe1d 100644 --- a/nx.json +++ b/nx.json @@ -193,6 +193,18 @@ }, "test:e2e*": { "parallelism": false + }, + "test:noncompiler": { + "cache": true, + "dependsOn": ["^build"], + "inputs": [ + "default", + "!{projectRoot}/tests/integration/**/*", + "^production", + "{workspaceRoot}/eslint.config.js", + "dependentTaskOutputs" + ], + "outputs": ["{projectRoot}/coverage"] } }, "plugins": [ diff --git a/package.json b/package.json index d012463531..7c3ad2aab4 100644 --- a/package.json +++ b/package.json @@ -14,8 +14,8 @@ "cleanNodeModules": "pnpm -r exec rm -rf node_modules", "clean": "pnpm --filter \"./packages/**\" run clean", "test": "pnpm run test:ci", - "test:pr": "nx affected --targets=test:eslint,test:unit,test:integration,test:implementation,test:e2e,test:types,test:build,build", - "test:ci": "nx run-many --targets=test:eslint,test:unit,test:integration,test:implementation,test:e2e,test:types,test:build,build", + "test:pr": "nx affected --targets=test:eslint,test:unit,test:integration,test:implementation,test:noncompiler,test:e2e,test:types,test:build,build", + "test:ci": "nx run-many --targets=test:eslint,test:unit,test:integration,test:implementation,test:noncompiler,test:e2e,test:types,test:build,build", "test:eslint": "nx affected --target=test:eslint --exclude=examples/**,e2e/**", "test:unit": "nx affected --target=test:unit --exclude=examples/**,e2e/**", "test:integration": "nx affected --target=test:integration --exclude=examples/**,e2e/**", @@ -57,7 +57,8 @@ "ts:symbol-references": "node scripts/ts-symbol-references.mjs", "vite-ecosystem-ci:build": "nx run-many --targets=build --projects=@tanstack/router-plugin,@tanstack/start-plugin-core,@tanstack/react-start,@tanstack/react-start-client,@tanstack/react-start-server --skipRemoteCache", "vite-ecosystem-ci:before-test": "pnpm exec playwright install chromium", - "vite-ecosystem-ci:test": "nx run-many --targets=test:unit,test:integration,test:implementation --projects=@tanstack/router-plugin,@tanstack/start-plugin-core,@tanstack/react-start-client --skipRemoteCache && nx run-many --target=test:e2e --projects=tanstack-router-e2e-react-basic-file-based,tanstack-router-e2e-react-basic-file-based-code-splitting,tanstack-react-start-e2e-basic,tanstack-vue-start-e2e-basic,tanstack-solid-start-e2e-basic --skipRemoteCache" + "vite-ecosystem-ci:test": "nx run-many --targets=test:unit,test:integration,test:implementation,test:noncompiler --projects=@tanstack/router-plugin,@tanstack/start-plugin-core,@tanstack/react-start-client --skipRemoteCache && nx run-many --target=test:e2e --projects=tanstack-router-e2e-react-basic-file-based,tanstack-router-e2e-react-basic-file-based-code-splitting,tanstack-react-start-e2e-basic,tanstack-vue-start-e2e-basic,tanstack-solid-start-e2e-basic --skipRemoteCache", + "test:noncompiler": "nx affected --target=test:noncompiler --exclude=examples/**,e2e/**" }, "nx": { "includedScripts": [ diff --git a/packages/compiler-test-utils/AGENTS.md b/packages/compiler-test-utils/AGENTS.md index 26b3700879..e79d6c6154 100644 --- a/packages/compiler-test-utils/AGENTS.md +++ b/packages/compiler-test-utils/AGENTS.md @@ -40,8 +40,9 @@ The compiler test corpus is meant to be an oracle: a compiler that passes every - `test:implementation` (projects `implementation` and `implementation-integration`) selects the implementation tests of both tiers; `test:implementation:unit` the fast ones only. - The root `test:pr`/`test:ci` scripts and the compiler platform workflow run the implementation targets too, so no implementation test is lost; acceptance of a rewrite reads only `test:unit` and `test:integration`. - **Harness controls** of a compiler package (tests of its own test helpers that drive the real compiler, e.g. router-plugin's `regression-helpers.test.ts` in both tiers) are outside the corpus too: they check the oracle, not the compiler, and a correct rewrite may differ in the incidental details they lean on. Controls on fixed inputs may stay where they are. -- A package that gets its first implementation test adds the two projects and the two scripts the same way. react-start-rsc has none yet. This package's own tests are harness controls, not compiler tests; none of them is an implementation test of a compiler. -- Budgets (`test-budgets.json`) cover the corpus tiers; the implementation projects have none. +- A package that gets its first implementation test adds the two projects and the two scripts the same way. react-start-rsc selects its runtime tests in `test:noncompiler`. This package's own tests are harness controls, not compiler tests; none of them is an implementation test of a compiler. +- **Noncompiler coverage:** start-plugin-core build plumbing and react-start-rsc runtime tests live under `tests/outside-compiler-corpus/noncompiler/` and run in `test:noncompiler`, excluded from the implementation projects too. Root `test:pr`/`test:ci` and compiler-platform CI run the lane. RSC compiler acceptance currently lives entirely in integration. +- Budgets (`test-budgets.json`) cover the corpus tiers; the implementation and noncompiler projects have none. - What does not belong outside the corpus: a goal pin (`.fails`) of a real bug, a test of supported behaviour that is merely slow, or a test that decides a user-visible outcome through an internal entry point (e.g. the emitted `handleRouteUpdate` driven by a live router: label it in its header, keep it in the corpus, and reroute it through a public entry point: the import gate below flags it until then). Before moving a test out, make sure no wrong compiler is caught only by it (e.g. a known mutant of the compiler). ## Import gate diff --git a/packages/compiler-test-utils/src/budget-reporter.ts b/packages/compiler-test-utils/src/budget-reporter.ts index c8f9f2cfbd..0735204129 100644 --- a/packages/compiler-test-utils/src/budget-reporter.ts +++ b/packages/compiler-test-utils/src/budget-reporter.ts @@ -10,7 +10,7 @@ * (Nx adds its own startup), against the edit-to-result hard limit. * * The tier is the Vitest project: `integration` is the slow tier, the - * implementation projects (`implementation*`, outside the corpus) have no + * implementation/noncompiler projects (outside the corpus) have no * budget, any other project is the fast tier. Runs at another worker count (CI, one worker) are * reported only. * @@ -81,7 +81,7 @@ function moduleSeconds(testModule: TestModule) { const tierOf = (projectName: string): Tier | undefined => projectName === 'integration' ? 'integration' - : projectName.startsWith('implementation') + : projectName.startsWith('implementation') || projectName === 'noncompiler' ? undefined : 'unit' diff --git a/packages/compiler-test-utils/src/build-harness.ts b/packages/compiler-test-utils/src/build-harness.ts index 5bc899b6a1..cd0dfffc1d 100644 --- a/packages/compiler-test-utils/src/build-harness.ts +++ b/packages/compiler-test-utils/src/build-harness.ts @@ -25,11 +25,13 @@ import { createServer } from 'node:http' import { SourceMap as NodeSourceMap } from 'node:module' import path from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' -import { format } from 'node:util' +import { openDiagnosticChannel } from './diagnostic-channel' import { runNodeProgram } from './run-node' import { savingDirectory } from './save-file' import type { AddressInfo } from 'node:net' import type { BrowserPage } from './browser' +import type { DiagnosticChannel } from './diagnostic-channel' +import type { Rspack } from '@rsbuild/core' export type Bundler = 'vite' | 'rspack' | 'webpack' | 'esbuild' @@ -362,6 +364,7 @@ export async function bundleApp( } interface BundlerConfig { + diagnosticChannel?: DiagnosticChannel root: string outDir: string entry: string @@ -436,7 +439,8 @@ async function bundle( const output = await withBuildEnvironment( target.nodeEnv === undefined ? mode : target.nodeEnv, consoleMessages, - () => builders[bundler](config, warnings), + (channel) => + builders[bundler]({ ...config, diagnosticChannel: channel }, warnings), ) const duration = performance.now() - started return describeBuild({ @@ -753,6 +757,7 @@ async function buildWithWebpackApi( config.root, config.rebuildAfter, warnings, + config.diagnosticChannel, ) const json = stats.toJson(statsOptions) warnings.push(...statsMessages(json.warnings)) @@ -775,7 +780,11 @@ async function buildWithWebpackApi( }) if (bundler === 'rspack') { import('@rsbuild/core') - .then(({ rspack }) => run(rspack(options as never) as never)) + .then(({ rspack }) => { + const compiler = rspack(options as unknown as Rspack.Configuration) + config.diagnosticChannel?.scopeRspack(compiler) + return run(compiler as never) + }) .catch(reject) } else { import('webpack') @@ -804,6 +813,7 @@ async function watchAndRebuild( root: string, files: Record, warnings: Array, + diagnosticChannel?: DiagnosticChannel, ): Promise { const compiler = (bundler === 'rspack' ? (await import('@rsbuild/core')).rspack(options as never) @@ -815,6 +825,9 @@ async function watchAndRebuild( callback: (error: Error | null, stats?: WebpackStats) => void, ) => { close: (callback: () => void) => void } } + if (bundler === 'rspack') { + diagnosticChannel?.scopeRspack(compiler as unknown as Rspack.Compiler) + } let builds = 0 let last: { error: Error | null; stats?: WebpackStats } | undefined const watching = compiler.watch({ aggregateTimeout: 50 }, (error, stats) => { @@ -1471,60 +1484,6 @@ export function parsedModules(): ParsedModules { return { resourceById: new Map(), modules: new Set(), transformed: new Map() } } -/** - * The segments of a source map that carry a name (`names`), with the - * original position each maps to: `source` as the map names it, `line` - * 1-based, `column` 0-based (source map columns). - */ -export function namedSegments( - map: SourceMap, -): Array<{ name: string; source: string; line: number; column: number }> { - const base64 = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - const segments: Array<{ - name: string - source: string - line: number - column: number - }> = [] - // Running values of the source index, line, column and name index. - const state = [0, 0, 0, 0] - for (const line of map.mappings.split(';')) { - for (const segment of line.split(',')) { - if (!segment) { - continue - } - const fields: Array = [] - let value = 0 - let shift = 0 - for (const char of segment) { - const digit = base64.indexOf(char) - value += (digit & 31) << shift - if (digit & 32) { - shift += 5 - } else { - fields.push(value & 1 ? -(value >>> 1) : value >>> 1) - value = 0 - shift = 0 - } - } - // fields[0] is the generated column. - for (let index = 1; index < fields.length; index++) { - state[index - 1]! += fields[index]! - } - if (fields.length === 5) { - segments.push({ - name: map.names[state[3]!]!, - source: map.sources[state[0]!]!, - line: state[1]! + 1, - column: state[2]!, - }) - } - } - } - return segments -} - /** A position in an original source file, according to a source map. */ export interface OriginalPosition { /** The source as the source map names it. */ @@ -1786,8 +1745,8 @@ function swcOptions( /** * Runs a build the way a build command does (`NODE_ENV` set to the mode by * default, which decides e.g. the JSX runtime and the `development` export - * condition; `null` unsets it) and records `console.warn`/`console.error` - * output. An error no one handles while the build runs fails the build: a + * condition; `null` unsets it) and records warnings/errors from the merged + * console/stream channel for this build’s async work. An error no one handles while the build runs fails the build: a * bundler that loses a plugin's error (e.g. a throw in a hook Rspack calls * without catching it) would otherwise never finish the build, and the test * would wait for its timeout. @@ -1795,7 +1754,7 @@ function swcOptions( export async function withBuildEnvironment( buildNodeEnv: string | null, messages: Array, - run: () => Promise, + run: (channel: DiagnosticChannel) => Promise, ): Promise { const nodeEnv = process.env.NODE_ENV if (buildNodeEnv === null) { @@ -1803,15 +1762,12 @@ export async function withBuildEnvironment( } else { process.env.NODE_ENV = buildNodeEnv } - const original = { warn: console.warn, error: console.error } - console.warn = (...args: Array) => { - messages.push(format(...args)) - original.warn.apply(console, args) - } - console.error = (...args: Array) => { - messages.push(format(...args)) - original.error.apply(console, args) - } + const channel = openDiagnosticChannel() + channel.onDiagnostic(({ severity, text }) => { + if (severity === 'warning' || severity === 'error') { + messages.push(text) + } + }) let onUnhandled!: (error: unknown) => void const unhandled = new Promise((_, reject) => { onUnhandled = (error) => { @@ -1826,12 +1782,11 @@ export async function withBuildEnvironment( process.on('unhandledRejection', onUnhandled) process.on('uncaughtException', onUnhandled) try { - return await Promise.race([run(), unhandled]) + return await channel.run(() => Promise.race([run(channel), unhandled])) } finally { process.off('unhandledRejection', onUnhandled) process.off('uncaughtException', onUnhandled) - console.warn = original.warn - console.error = original.error + channel.close() if (nodeEnv === undefined) { delete process.env.NODE_ENV } else { diff --git a/packages/compiler-test-utils/src/console-hook.ts b/packages/compiler-test-utils/src/console-hook.ts index a08df5d315..704ca0c9b8 100644 --- a/packages/compiler-test-utils/src/console-hook.ts +++ b/packages/compiler-test-utils/src/console-hook.ts @@ -5,11 +5,17 @@ * the dev-server and build harnesses) reads through it, so captures nest and * overlap in any order without one restoring the console under another. * - * While at least one sink listens, what it listens to is silenced (recorded - * only); with none, the hook is removed and the originals are back. A hook a + * Only sinks in the current async scope receive output. Nested scopes + * inherit their parent captures; concurrent scopes stay separate. Captured + * output is silenced (recorded only); with none, the hook is removed and + * the originals are back. A hook a * later patch wrapped (e.g. a test's own `vi.spyOn`) is left in place and * forwards to the originals once no sink listens. */ +import { AsyncLocalStorage } from 'node:async_hooks' + +const activeSinks = new AsyncLocalStorage>() + export type ConsoleMethod = 'error' | 'warn' | 'log' | 'info' | 'debug' export const consoleMethods: ReadonlyArray = [ @@ -76,7 +82,9 @@ function install() { consoleMethods.map((method) => [ method, (...args: Array) => { - const listening = [...sinks].filter((sink) => sink.console) + const listening = [...(activeSinks.getStore() ?? [])].filter( + (sink) => sinks.has(sink) && sink.console, + ) if (listening.length === 0) { saved.console[method].apply(console, args) return @@ -89,7 +97,9 @@ function install() { ) as Record const streamHook = (stream: 'stdout' | 'stderr'): Write => function (this: unknown, chunk: unknown, ...rest: Array) { - const listening = [...sinks].filter((sink) => sink.streams) + const listening = [...(activeSinks.getStore() ?? [])].filter( + (sink) => sinks.has(sink) && sink.streams, + ) if (listening.length === 0) { return (saved[stream] as (...args: Array) => boolean).call( process[stream], @@ -142,16 +152,46 @@ function uninstall() { } /** - * Starts delivering what is printed to `sink`; returns the function that - * stops it (the hook goes once no sink listens). + * Installs a sink. Only its run() work and async descendants are captured; + * the returned function stops it. enter() restores ownership at a native + * bundler callback boundary, where Node async context is not propagated. */ -export function listen(sink: Sink): () => void { +export function listen( + sink: Sink, +): (() => void) & { run: (run: () => T) => T; enter: () => void } { sinks.add(sink) install() - return () => { + const stop = () => { sinks.delete(sink) if (sinks.size === 0) { uninstall() } } + const parents = activeSinks.getStore() ?? [] + return Object.assign(stop, { + enter: () => activeSinks.enterWith(new Set([...parents, sink])), + run: (run: () => T): T => + activeSinks.run(new Set([...(activeSinks.getStore() ?? []), sink]), run), + }) +} + +/** Keep later API calls in the same async scope as server creation/watchers. */ +export function scopeMethods( + run: (fn: () => TResult) => TResult, + methods: T, +): T { + for (const [key, descriptor] of Object.entries( + Object.getOwnPropertyDescriptors(methods), + )) { + if (typeof descriptor.value === 'function') { + const method = descriptor.value + Object.defineProperty(methods, key, { + ...descriptor, + value: function (this: T, ...args: Array) { + return run(() => method.apply(this, args)) + }, + }) + } + } + return methods } diff --git a/packages/compiler-test-utils/src/dev-server.ts b/packages/compiler-test-utils/src/dev-server.ts index aec3a83f3d..f81cac0e27 100644 --- a/packages/compiler-test-utils/src/dev-server.ts +++ b/packages/compiler-test-utils/src/dev-server.ts @@ -64,11 +64,12 @@ import { } from 'vite' import { createApp } from './build-harness' import { createModuleGraph } from './module-linker' +import { scopeMethods } from './console-hook' import { openDiagnosticChannel } from './diagnostic-channel' import { saveAppFile } from './save-file' import { makeRunnerStrict } from './strict-runner' import type { AppOptions } from './build-harness' -import type { ChannelDiagnostic } from './diagnostic-channel' +import type { ChannelDiagnostic, DiagnosticChannel } from './diagnostic-channel' import type { ModuleGraphOptions, ModuleStub } from './module-linker' import type { DevEnvironment, @@ -297,6 +298,19 @@ interface ReportedEvent { */ export async function createDevServer( options: DevServerOptions, +): Promise { + const channel = openDiagnosticChannel() + try { + return await channel.run(() => startServer(options, channel)) + } catch (error) { + channel.close() + throw error + } +} + +async function startServer( + options: DevServerOptions, + channel: DiagnosticChannel, ): Promise { const { plugins = [], config = {}, bundledDev, browser = false } = options const listen = options.listen ?? browser @@ -321,7 +335,6 @@ export async function createDevServer( const file = (relative: string) => path.join(root, relative) const logs: Array = [] /** Every channel the server's work may report on (see the module comment). */ - const channel = openDiagnosticChannel() channel.onDiagnostic((diagnostic) => { // Vite's logger writes its own lines (below) if (diagnostic.source !== 'vite' && diagnostic.severity !== 'info') { @@ -771,7 +784,7 @@ export async function createDevServer( })() return closed } - options.registerCleanup?.(close) + options.registerCleanup?.(() => channel.run(close)) /** * Waits until `check` holds, checking again whenever something happened @@ -1149,7 +1162,7 @@ export async function createDevServer( throw error } - return { + return scopeMethods(channel.run, { root, vite, file, @@ -1221,7 +1234,7 @@ export async function createDevServer( diagnostics: channel.diagnostics, stop, close, - } + }) } /** Dependencies and the HMR clients, which no test inspects. */ @@ -1287,8 +1300,7 @@ const viteClientStub = { * Use `runClient` of `./plugin-host` (or `runInPage` of `./browser`: the * served module in the shared Chromium page) or `createDevServer({ browser: * true })` with `openPage`. - * Kept until its remaining callers move (listed in - * validation/REPAIR/A2.md): start-plugin-core + * Kept until its remaining callers move: start-plugin-core * integration/start-compiler-dev-server.test.ts and * integration/known-bugs-dev-server.test.ts, router-plugin * plugin-options.test.ts, and this package's dev-server.test.ts. diff --git a/packages/compiler-test-utils/src/diagnostic-channel.ts b/packages/compiler-test-utils/src/diagnostic-channel.ts index 9c1c2b4ebc..b968cefcbe 100644 --- a/packages/compiler-test-utils/src/diagnostic-channel.ts +++ b/packages/compiler-test-utils/src/diagnostic-channel.ts @@ -17,11 +17,12 @@ * reported" is `expectNoProblems(channel.diagnostics)` (no `warning` and no * `error`; `info` is not a problem, N15). * - * Scoping: a channel records from `openDiagnosticChannel()` until `close()`; + * Scoping: a channel records its `run()` work and async descendants until + * `close()`; * `mark()` / `since(mark)` slice what a step (an edit, a build) reported, and * `scope(run)` records exactly what `run` reported. Channels may overlap * (nested captures, or concurrent tests in one file): each receives what is - * printed while it is open. + * printed by their own async work; concurrent scopes do not share output. * * Every entry is a `Diagnostic` of `./diagnostics` with its `source`, so the * content matchers (`expectDiagnostic`, `findDiagnostics`) read it as they @@ -33,6 +34,7 @@ import { describeError, diagnosticsOf } from './diagnostics' import type { ConsoleMethod, PrintedEntry } from './console-hook' import type { Diagnostic, DiagnosticSource, Severity } from './diagnostics' import type { LogErrorOptions, Logger } from 'vite' +import type { Rspack } from '@rsbuild/core' export type { DiagnosticSource } from './diagnostics' @@ -68,6 +70,10 @@ export interface DiagnosticChannel { report: (value: unknown, severity: Severity, source: DiagnosticSource) => void /** Called with each diagnostic as it is recorded. */ onDiagnostic: (listener: (diagnostic: ChannelDiagnostic) => void) => void + /** Runs work in this channel; descendants (watchers, requests) inherit it. */ + run: (run: () => T) => T + /** Restore this app’s scope at Rspack’s native-to-JS loader boundary. */ + scopeRspack: (compiler: Rspack.Compiler) => void /** Stops recording (idempotent). */ close: () => void } @@ -120,7 +126,7 @@ export function printedDiagnostic(entry: PrintedEntry): ChannelDiagnostic { } } -/** Opens a channel; it records until `close()`. */ +/** Opens a channel for run()/scope() work, recording until close(). */ export function openDiagnosticChannel( options: DiagnosticChannelOptions = {}, ): DiagnosticChannel { @@ -145,7 +151,10 @@ export function openDiagnosticChannel( streams: recordsStreams, receive: (entry) => push(printedDiagnostic(entry)), }) - : () => {} + : Object.assign(() => {}, { + run: (run: () => T) => run(), + enter: () => {}, + }) const report = ( value: unknown, @@ -159,11 +168,20 @@ export function openDiagnosticChannel( const channel: DiagnosticChannel = { diagnostics, + run: stop.run, + scopeRspack: (compiler) => { + const name = 'diagnostic-channel:loader-scope' + compiler.hooks.compilation.tap(name, (compilation) => { + compiler.webpack.NormalModule.getCompilationHooks( + compilation, + ).loader.tap(name, stop.enter) + }) + }, mark: () => diagnostics.length, since: (mark) => diagnostics.slice(mark), scope: async (run) => { const from = diagnostics.length - const result = await run() + const result = await stop.run(run) return { result, diagnostics: diagnostics.slice(from) } }, viteLogger: () => { @@ -226,7 +244,7 @@ export async function captureDiagnostics( ): Promise<{ result: T; diagnostics: Array }> { const channel = openDiagnosticChannel(options) try { - const result = await run(channel) + const result = await channel.run(() => run(channel)) return { result, diagnostics: [...channel.diagnostics] } } finally { channel.close() diff --git a/packages/compiler-test-utils/src/diagnostics.ts b/packages/compiler-test-utils/src/diagnostics.ts index 64e170d98f..43665c2bbf 100644 --- a/packages/compiler-test-utils/src/diagnostics.ts +++ b/packages/compiler-test-utils/src/diagnostics.ts @@ -328,8 +328,8 @@ export async function captureThrow( * diagnostics (`error`; `warn` is `warning`; `log`/`info`/`debug` are * `info`). The console is restored afterwards, also when `run` throws. * Captures may overlap and nest with every other capture of the harness - * (the shared hook of `./console-hook`): each one gets what is logged while - * it runs, and the console is restored when the last one ends. + * (the shared hook of `./console-hook`): each gets its own async work, + * including nested captures. The console is restored when the last one ends. * * This reads the console only. A check that a compiler reports something, * or that nothing is reported, reads every channel instead @@ -349,7 +349,7 @@ export async function captureConsole( }, }) try { - return { result: await run(), diagnostics } + return { result: await stop.run(run), diagnostics } } finally { stop() } @@ -975,8 +975,7 @@ function frameReportsPosition( const start = lines[index]!.indexOf(sourceLine, gutter + 1) // The caret, or one column left of it: a compiler handing a 0-based // AST column to a 1-based code-frame API (Babel's `codeFrameColumns`) - // draws it there. Start's `codeFrameError` does today (finding of - // validation/REPAIR/A2.md, for a ruling); this keeps the old tolerance + // draws it there. Start's `codeFrameError` does today; keep the tolerance // for the caret only. if (start >= 0 && columnMatches(caret - start + 1, column, 'either')) { return true diff --git a/packages/compiler-test-utils/src/import-gate.ts b/packages/compiler-test-utils/src/import-gate.ts index 5da1ec18fc..6a92421408 100644 --- a/packages/compiler-test-utils/src/import-gate.ts +++ b/packages/compiler-test-utils/src/import-gate.ts @@ -23,7 +23,8 @@ * * The acceptance files are the files `test:unit` and `test:integration` * select (router-generator: also its `types` project's `*.test-d.ts`), outside - * `outside-compiler-corpus/`. Their helpers are the modules they reach + * `outside-compiler-corpus/` (implementation and noncompiler lanes). Their + * helpers are the modules they reach * through relative paths into a package's `tests/`, or into this package's * `src/` (also through `@tanstack/compiler-test-utils/*`), transitively. * Paths computed at run time (a `path.join` passed to `import()`) are out of @@ -55,7 +56,8 @@ export const acceptancePackages = [ { dir: 'packages/router-generator', typeTests: true }, { dir: 'packages/router-plugin', typeTests: false }, { dir: 'packages/start-plugin-core', typeTests: false }, - // `*.test-d.tsx` here run with `test:types`, not an acceptance target. + // RSC runtime tests live in outside-compiler-corpus/noncompiler. + // Its test-d files run with test:types, not a compiler acceptance target. { dir: 'packages/react-start-rsc', typeTests: false }, ] as const diff --git a/packages/compiler-test-utils/src/lazy-probe.ts b/packages/compiler-test-utils/src/lazy-probe.ts index 632b2e1b21..a83454a26f 100644 --- a/packages/compiler-test-utils/src/lazy-probe.ts +++ b/packages/compiler-test-utils/src/lazy-probe.ts @@ -2,8 +2,7 @@ * @deprecated Observes laziness in the Node module graph of * `./module-linker` (RULES-AUDIT §2.D #8): laziness is the bundler's and * the browser's (`./build-harness` chunk placement, the page's requests in - * `./browser`). Kept for the callers that have not moved yet - * (validation/REPAIR/A2.md). + * `./browser`). Kept for the callers that have not moved yet. * * Observes lazy loading in a module graph (`module-linker.ts`) by the modules * actually evaluated when a value's real trigger completes, never by diff --git a/packages/compiler-test-utils/src/module-linker.ts b/packages/compiler-test-utils/src/module-linker.ts index f9cd63a571..4fb41a6ab2 100644 --- a/packages/compiler-test-utils/src/module-linker.ts +++ b/packages/compiler-test-utils/src/module-linker.ts @@ -2,8 +2,8 @@ * @deprecated A re-implementation of module resolution and evaluation * (RULES-AUDIT §2.D #4; N9, N24): stubs keyed by the emitted specifier, * and `fallbackStub` turns a missing import into `undefined`. Kept only - * for the callers that have not moved yet (validation/REPAIR/A2.md lists - * them). New tests evaluate server code through Vite's module runner + * for callers that have not moved yet. New tests evaluate server code + * through Vite's module runner * (`./plugin-host` `importServer`, `./dev-server` `import`: real * resolution by target, a missing import throws, `./strict-runner`) and * client code in a real browser (`./plugin-host` `runClient`, diff --git a/packages/compiler-test-utils/src/plugin-host.ts b/packages/compiler-test-utils/src/plugin-host.ts index ef1b7c8de6..4728876e42 100644 --- a/packages/compiler-test-utils/src/plugin-host.ts +++ b/packages/compiler-test-utils/src/plugin-host.ts @@ -332,85 +332,87 @@ export async function createPluginHost( const outputs: Record = {} const clientModules = parsedModules() const channel = openDiagnosticChannel() - try { - const builder = await createBuilder( - mergeConfig( + return channel.run(async () => { + try { + const builder = await createBuilder( mergeConfig( - { - root: buildRoot, - configFile: false, - envDir: false, - publicDir: false, - mode, - clearScreen: false, - customLogger: channel.viteLogger(), - plugins: [ - ...pluginsFor('build', buildRoot), - outputRecorder(outputs), - // The evidence of the client's dangling-name check - recordViteModules(clientModules, { environment: 'client' }), - ], - } satisfies InlineConfig, - config, + mergeConfig( + { + root: buildRoot, + configFile: false, + envDir: false, + publicDir: false, + mode, + clearScreen: false, + customLogger: channel.viteLogger(), + plugins: [ + ...pluginsFor('build', buildRoot), + outputRecorder(outputs), + // The evidence of the client's dangling-name check + recordViteModules(clientModules, { environment: 'client' }), + ], + } satisfies InlineConfig, + config, + ), + buildOptions.config ?? {}, ), - buildOptions.config ?? {}, - ), - // As the CLI: every environment when a plugin configures the app - // builder, else the client - null, - ) - await builder.buildApp() - } catch (error) { - channel.close() - throw new HostBuildError(error, [...channel.diagnostics]) - } - channel.close() - const diagnostics = [...channel.diagnostics] - return { - environments: outputs, - diagnostics, - describe: async (name, describeOptions = {}) => { - const environment = outputs[name] - if (!environment) { - throw new Error( - `no "${name}" environment was built (built: ${Object.keys(outputs).join(', ') || 'none'})`, - ) - } - const env = - describeOptions.env ?? (name === 'client' ? 'client' : 'ssr') - // An app's own entry: the one emitted entry, unless named - const chunks = environment.chunks.filter( - (chunk) => - describeOptions.entry === undefined || - !chunk.isEntry || - chunk.fileName === describeOptions.entry, + // As the CLI: every environment when a plugin configures the app + // builder, else the client + null, ) - return describeBuild({ - bundler: 'vite', - env, - mode, - minify: true, - root: buildRoot, - outDir: environment.outDir, - chunks: chunks.map( - ({ fileName, isEntry, imports, dynamicImports }) => ({ - fileName, - isEntry, - imports, - dynamicImports, - }), - ), - sourcemap: chunks.every((chunk) => chunk.map !== undefined), - ...(name === 'client' && { parsedModules: clientModules }), - warnings: diagnostics - .filter((diagnostic) => diagnostic.severity === 'warning') - .map((diagnostic) => diagnostic.text), - consoleMessages: [], - duration: 0, - dispose: async () => {}, - }) - }, - } + await builder.buildApp() + } catch (error) { + channel.close() + throw new HostBuildError(error, [...channel.diagnostics]) + } + channel.close() + const diagnostics = [...channel.diagnostics] + return { + environments: outputs, + diagnostics, + describe: async (name, describeOptions = {}) => { + const environment = outputs[name] + if (!environment) { + throw new Error( + `no "${name}" environment was built (built: ${Object.keys(outputs).join(', ') || 'none'})`, + ) + } + const env = + describeOptions.env ?? (name === 'client' ? 'client' : 'ssr') + // An app's own entry: the one emitted entry, unless named + const chunks = environment.chunks.filter( + (chunk) => + describeOptions.entry === undefined || + !chunk.isEntry || + chunk.fileName === describeOptions.entry, + ) + return describeBuild({ + bundler: 'vite', + env, + mode, + minify: true, + root: buildRoot, + outDir: environment.outDir, + chunks: chunks.map( + ({ fileName, isEntry, imports, dynamicImports }) => ({ + fileName, + isEntry, + imports, + dynamicImports, + }), + ), + sourcemap: chunks.every((chunk) => chunk.map !== undefined), + ...(name === 'client' && { parsedModules: clientModules }), + warnings: diagnostics + .filter((diagnostic) => diagnostic.severity === 'warning') + .map((diagnostic) => diagnostic.text), + consoleMessages: [], + duration: 0, + dispose: async () => {}, + }) + }, + } + }) }, close, } diff --git a/packages/compiler-test-utils/src/render.ts b/packages/compiler-test-utils/src/render.ts index e74fc8fd57..831ae5635a 100644 --- a/packages/compiler-test-utils/src/render.ts +++ b/packages/compiler-test-utils/src/render.ts @@ -3,7 +3,7 @@ * renderer and a hand-assembled plugin pipeline (RULES-AUDIT §2.D #5, R24): * client semantics belong in a real browser (`./plugin-host` `runClient` * on the served module with the real framework plugins). Kept for the - * callers that have not moved yet (validation/REPAIR/A2.md). + * callers that have not moved yet. * * Real framework rendering of module graphs (`module-linker.ts`): compile the * graph's JSX with the framework's real transform and render what its diff --git a/packages/compiler-test-utils/src/rsbuild-dev-server.ts b/packages/compiler-test-utils/src/rsbuild-dev-server.ts index de288b9864..254b9df08a 100644 --- a/packages/compiler-test-utils/src/rsbuild-dev-server.ts +++ b/packages/compiler-test-utils/src/rsbuild-dev-server.ts @@ -30,10 +30,11 @@ import { createServer } from 'node:http' import path from 'node:path' import { createRsbuild, mergeRsbuildConfig } from '@rsbuild/core' import { createApp } from './build-harness' +import { scopeMethods } from './console-hook' import { openDiagnosticChannel } from './diagnostic-channel' import { saveAppFile } from './save-file' import type { AppOptions } from './build-harness' -import type { ChannelDiagnostic } from './diagnostic-channel' +import type { ChannelDiagnostic, DiagnosticChannel } from './diagnostic-channel' import type { AddressInfo, Socket } from 'node:net' import type { RsbuildConfig, @@ -194,6 +195,19 @@ export interface RsbuildDevServer { */ export async function createRsbuildDevServer( options: RsbuildDevServerOptions, +): Promise { + const channel = openDiagnosticChannel() + try { + return await channel.run(() => startServer(options, channel)) + } catch (error) { + channel.close() + throw error + } +} + +async function startServer( + options: RsbuildDevServerOptions, + channel: DiagnosticChannel, ): Promise { const { plugins = [], @@ -218,7 +232,6 @@ export async function createRsbuildDevServer( const errors: Array = [] const warnings: Array = [] /** Every channel the server's work may report on (see the module comment). */ - const channel = openDiagnosticChannel() const diagnostics = channel.diagnostics const compiles = trackCompiles() @@ -289,6 +302,7 @@ export async function createRsbuildDevServer( for (const environmentCompiler of 'compilers' in compiler ? compiler.compilers : [compiler]) { + channel.scopeRspack(environmentCompiler) const name = 'rsbuild-dev-server-harness:settle' // Before the plugins' own `watchRun` taps: what they write then is // read by the next compile, not this one @@ -420,7 +434,7 @@ export async function createRsbuildDevServer( { root, mode: 'development', - logLevel: 'silent', + logLevel: 'warn', source: { entry: { index: `./${entry}` } }, // Without a browser page, live reload would do nothing dev: { @@ -499,7 +513,7 @@ export async function createRsbuildDevServer( })() return closed } - options.registerCleanup?.(close) + options.registerCleanup?.(() => channel.run(close)) const distPathOf = (environment: string | undefined) => { const name = environment ?? Object.keys(distPaths)[0]! @@ -592,7 +606,7 @@ export async function createRsbuildDevServer( } } - return { + return scopeMethods(channel.run, { root, rsbuild, url, @@ -633,7 +647,7 @@ export async function createRsbuildDevServer( devServer: server, stop, close, - } + }) } export interface CompileTracker { diff --git a/packages/compiler-test-utils/src/rsbuild-plugin-host.ts b/packages/compiler-test-utils/src/rsbuild-plugin-host.ts index 3da4f5dd41..d8c45c253b 100644 --- a/packages/compiler-test-utils/src/rsbuild-plugin-host.ts +++ b/packages/compiler-test-utils/src/rsbuild-plugin-host.ts @@ -206,91 +206,100 @@ export async function createRsbuildPluginHost( build: async (buildOptions = {}) => { const mode = buildOptions.mode ?? 'production' const channel = openDiagnosticChannel() - const environments: Record = {} - const evidence: Record = {} - /** Each environment's output directory and emitted scripts. */ - const emitted: Record< - string, - { distPath: string; files: Array } - > = {} - const recorder: RsbuildPlugin = { - name: 'rsbuild-plugin-host:build', - setup(api) { - api.modifyRspackConfig((rspackConfig, { environment }) => { - if ( - mode === 'production' && - environment.config.output.target === 'web' - ) { - const parsed = emptyParsedModules() - evidence[environment.name] = parsed - rspackConfig.plugins.push( - recordParsedModules( - parsed, - ) as unknown as Rspack.RspackPluginInstance, - ) - } - }) - api.onAfterBuild(({ stats, environments: built }) => { - const all = stats && 'stats' in stats ? stats.stats : [stats] - const names = Object.keys(built) - all.forEach((environmentStats, index) => { - if (!environmentStats) { - return - } - channel.reportCompilation(environmentStats.compilation) - const name = environmentStats.compilation.name ?? names[index]! - const { assets = [] } = environmentStats.toJson({ - all: false, - assets: true, - }) - emitted[name] = { - distPath: built[name]!.distPath, - files: assets - .map((asset) => asset.name) - .filter((file) => /\.[cm]?js$/.test(file)), + return channel.run(async () => { + const environments: Record = {} + const evidence: Record = {} + /** Each environment's output directory and emitted scripts. */ + const emitted: Record< + string, + { distPath: string; files: Array } + > = {} + const recorder: RsbuildPlugin = { + name: 'rsbuild-plugin-host:build', + setup(api) { + api.onAfterCreateCompiler(({ compiler }) => { + for (const child of 'compilers' in compiler + ? compiler.compilers + : [compiler]) { + channel.scopeRspack(child) } }) + api.modifyRspackConfig((rspackConfig, { environment }) => { + if ( + mode === 'production' && + environment.config.output.target === 'web' + ) { + const parsed = emptyParsedModules() + evidence[environment.name] = parsed + rspackConfig.plugins.push( + recordParsedModules( + parsed, + ) as unknown as Rspack.RspackPluginInstance, + ) + } + }) + api.onAfterBuild(({ stats, environments: built }) => { + const all = stats && 'stats' in stats ? stats.stats : [stats] + const names = Object.keys(built) + all.forEach((environmentStats, index) => { + if (!environmentStats) { + return + } + channel.reportCompilation(environmentStats.compilation) + const name = environmentStats.compilation.name ?? names[index]! + const { assets = [] } = environmentStats.toJson({ + all: false, + assets: true, + }) + emitted[name] = { + distPath: built[name]!.distPath, + files: assets + .map((asset) => asset.name) + .filter((file) => /\.[cm]?js$/.test(file)), + } + }) + }) + }, + } + let built: { close: () => Promise } | undefined + try { + const rsbuild = await createRsbuild({ + cwd: root, + rsbuildConfig: mergeRsbuildConfig( + mergeRsbuildConfig( + { + root, + mode, + logLevel: 'warn', + source: { entry: { index: `./${entry}` } }, + plugins: [...pluginsFor('build', root), recorder], + }, + config, + ), + buildOptions.config ?? {}, + ), }) - }, - } - let built: { close: () => Promise } | undefined - try { - const rsbuild = await createRsbuild({ - cwd: root, - rsbuildConfig: mergeRsbuildConfig( - mergeRsbuildConfig( - { - root, - mode, - logLevel: 'silent', - source: { entry: { index: `./${entry}` } }, - plugins: [...pluginsFor('build', root), recorder], - }, - config, - ), - buildOptions.config ?? {}, - ), - }) - built = await rsbuild.build() - for (const [name, { distPath, files }] of Object.entries(emitted)) { - const code: Record = {} - for (const file of files) { - code[file] = await readFile(path.join(distPath, file), 'utf8') + built = await rsbuild.build() + for (const [name, { distPath, files }] of Object.entries(emitted)) { + const code: Record = {} + for (const file of files) { + code[file] = await readFile(path.join(distPath, file), 'utf8') + } + environments[name] = { distPath, files: code } } - environments[name] = { distPath, files: code } + } catch (error) { + channel.close() + throw new RsbuildHostBuildError(error, [...channel.diagnostics]) + } finally { + await built?.close() } - } catch (error) { channel.close() - throw new RsbuildHostBuildError(error, [...channel.diagnostics]) - } finally { - await built?.close() - } - channel.close() - return { - environments, - diagnostics: [...channel.diagnostics], - parsedModules: evidence, - } + return { + environments, + diagnostics: [...channel.diagnostics], + parsedModules: evidence, + } + }) }, close, } diff --git a/packages/compiler-test-utils/tests/diagnostic-channel.test.ts b/packages/compiler-test-utils/tests/diagnostic-channel.test.ts index 6322fe4265..9c28596bb5 100644 --- a/packages/compiler-test-utils/tests/diagnostic-channel.test.ts +++ b/packages/compiler-test-utils/tests/diagnostic-channel.test.ts @@ -12,6 +12,7 @@ import { openDiagnosticChannel, problems, } from '../src/diagnostic-channel' +import { withBuildEnvironment } from '../src/build-harness' import { captureConsole, expectDiagnostic } from '../src/diagnostics' describe('diagnostic channel', () => { @@ -61,7 +62,7 @@ describe('diagnostic channel', () => { test('scope() and since() give what a step reported; close() stops recording', async () => { const channel = openDiagnosticChannel() try { - console.warn('before') + channel.run(() => console.warn('before')) const mark = channel.mark() const { result, diagnostics } = await channel.scope(async () => { await Promise.resolve() @@ -93,9 +94,11 @@ describe('diagnostic channel', () => { stderr: process.stderr.write, } const outer = openDiagnosticChannel() - const inner = await captureConsole(() => { - console.warn('both') - }) + const inner = await outer.run(() => + captureConsole(() => { + console.warn('both') + }), + ) outer.close() expect(console.warn).toBe(original.warn) expect(process.stderr.write).toBe(original.stderr) @@ -149,3 +152,57 @@ describe('diagnostic channel', () => { expectNoProblems(diagnostics) }) }) + +// Overlapping async work must keep each capture's output, including streams. +test('concurrent captures do not receive each other’s output', async () => { + let release!: () => void + const ready = new Promise((resolve) => { + release = resolve + }) + const [first, second] = await Promise.all([ + captureDiagnostics(async () => { + await ready + console.warn('first console') + process.stderr.write('first stream\n') + }), + captureDiagnostics(async () => { + console.warn('second console') + release() + await ready + process.stderr.write('second stream\n') + }), + ]) + expect(first.diagnostics.map(({ text }) => text)).toEqual([ + 'first console', + 'first stream', + ]) + expect(second.diagnostics.map(({ text }) => text)).toEqual([ + 'second console', + 'second stream', + ]) +}) + +test('overlapping build-environment captures keep only their own console output', async () => { + const first: Array = [] + const second: Array = [] + let release!: () => void + const ready = new Promise((resolve) => { + release = resolve + }) + const nodeEnv = process.env.NODE_ENV ?? null + await Promise.all([ + withBuildEnvironment(nodeEnv, first, async () => { + await ready + console.warn('first build') + process.stderr.write('first build stream\n') + }), + withBuildEnvironment(nodeEnv, second, async () => { + console.warn('second build') + process.stderr.write('second build stream\n') + release() + await ready + }), + ]) + expect(first).toEqual(['first build', 'first build stream']) + expect(second).toEqual(['second build', 'second build stream']) +}) diff --git a/packages/compiler-test-utils/tests/diagnostics.test.ts b/packages/compiler-test-utils/tests/diagnostics.test.ts index f7b5cec39c..d5fdea3558 100644 --- a/packages/compiler-test-utils/tests/diagnostics.test.ts +++ b/packages/compiler-test-utils/tests/diagnostics.test.ts @@ -96,7 +96,7 @@ describe('real channels', () => { }) }) - test('overlapping captureConsole calls each get what is logged while they run, and the last one restores the console', async () => { + test('overlapping captureConsole calls keep their own output and restore the console', async () => { const before = console.warn let releaseFirst!: () => void const first = captureConsole(async () => { @@ -107,18 +107,17 @@ describe('real channels', () => { console.warn('after the second ended') }) const second = await captureConsole(() => { - console.warn('both') + console.warn('second only') }) expect(console.warn).not.toBe(before) releaseFirst() const { diagnostics } = await first expect(console.warn).toBe(before) expect(second.diagnostics.map((diagnostic) => diagnostic.text)).toEqual([ - 'both', + 'second only', ]) expect(diagnostics.map((diagnostic) => diagnostic.text)).toEqual([ 'first only', - 'both', 'after the second ended', ]) }) @@ -449,6 +448,12 @@ describe('position strictness', () => { // failure, quoted code alone, or a message missing what tells the cause // apart fails. describe("explains: a cause in the diagnostic's own words", () => { + test('accepts an actionable client-access refusal without a wording whitelist', () => { + expectDiagnostic( + diagnosticsOf('Server function not accessible from client', 'error'), + { severity: 'error', explains: true }, + ) + }) const source = `import { createServerFn } from '@tanstack/react-start' export const value = wrap(createServerFn().handler(() => 1)) ` diff --git a/packages/compiler-test-utils/tests/import-gate.test.ts b/packages/compiler-test-utils/tests/import-gate.test.ts index ecd1317d82..982b9e510c 100644 --- a/packages/compiler-test-utils/tests/import-gate.test.ts +++ b/packages/compiler-test-utils/tests/import-gate.test.ts @@ -101,3 +101,29 @@ describe('the import gate', () => { ).toBe(false) }) }) + +test('the noncompiler lanes are excluded while fast and integration acceptance stay gated', () => { + const paths = [ + 'react-start-rsc/tests/compiler-planted.test.ts', + 'react-start-rsc/tests/integration/compiler-planted.test.ts', + 'react-start-rsc/tests/outside-compiler-corpus/noncompiler/runtime-planted.test.tsx', + 'start-plugin-core/tests/outside-compiler-corpus/noncompiler/plumbing-planted.test.ts', + ].map((file) => path.join(root, 'packages', file)) + const result = findImportViolations({ + root, + files: Object.fromEntries( + paths.map((file) => [ + file, + `import { StartCompiler } from '@tanstack/start-plugin-core/src/start-compiler/compiler'`, + ]), + ), + }) + expect( + result.acceptanceFiles.filter((file) => file.includes('-planted.test.')), + ).toEqual(paths.slice(0, 2).map(relative)) + expect( + result.violations + .filter(({ file }) => file.includes('-planted.test.')) + .map(({ file }) => file), + ).toEqual(paths.slice(0, 2).map(relative)) +}) diff --git a/packages/compiler-test-utils/tests/integration/budget-reporter.test.ts b/packages/compiler-test-utils/tests/integration/budget-reporter.test.ts index 852df8f092..8c0eb36b9a 100644 --- a/packages/compiler-test-utils/tests/integration/budget-reporter.test.ts +++ b/packages/compiler-test-utils/tests/integration/budget-reporter.test.ts @@ -34,6 +34,7 @@ const brokenFile = `import './missing-helper.js'\n\ntest('never runs', () => {}) async function runTier( files: Record, budgets: 'strict' | 'report-only', + projectName = 'unit', ) { const root = await mkdtemp(path.join(tmpdir(), 'budget-reporter-')) onTestFinished(() => rm(root, { recursive: true, force: true })) @@ -43,7 +44,7 @@ async function runTier( ) await writeFile( path.join(root, 'vitest.config.mjs'), - `export default { test: { globals: true, watch: false, reporters: ['default', ${JSON.stringify(reporter)}] } }\n`, + `export default { test: { name: ${JSON.stringify(projectName)}, globals: true, watch: false, reporters: ['default', ${JSON.stringify(reporter)}] } }\n`, ) for (const [name, code] of Object.entries(files)) { await writeFile(path.join(root, name), code) @@ -120,3 +121,13 @@ test.concurrent( }, 30_000, ) + +test('noncompiler coverage does not consume compiler acceptance budgets', async () => { + const { exitCode, output } = await runTier( + { 'runtime.test.js': passingFile }, + 'strict', + 'noncompiler', + ) + expect(exitCode).toBe(0) + expect(output).not.toContain('Test budget (strict') +}, 30_000) diff --git a/packages/compiler-test-utils/tests/integration/build-harness.test.ts b/packages/compiler-test-utils/tests/integration/build-harness.test.ts index 9c8eb9381c..1e4b700c5a 100644 --- a/packages/compiler-test-utils/tests/integration/build-harness.test.ts +++ b/packages/compiler-test-utils/tests/integration/build-harness.test.ts @@ -14,7 +14,6 @@ import { bundlers, createApp, describeBuild, - namedSegments, originalFrameOf, } from '../../src/build-harness' import { unboundNames } from '../../src/validate-module' @@ -237,22 +236,6 @@ test.each(['webpack', 'rspack'] as const)( timeout, ) -// Two named segments: `a` at line 1 column 0 of `x.ts`, `b` at line 2 -// column 4 of `y.ts`; one segment without a name. -test('namedSegments decodes the named segments of a source map', () => { - expect( - namedSegments({ - version: 3, - sources: ['x.ts', 'y.ts'], - names: ['a', 'b'], - mappings: 'AAAAA,EAAA;ACCIC', - }), - ).toEqual([ - { name: 'a', source: 'x.ts', line: 1, column: 0 }, - { name: 'b', source: 'y.ts', line: 2, column: 4 }, - ]) -}) - describe('side-effect hints', () => { /** `./effects` is imported for an export the entry never uses. */ const unusedModuleApp = { @@ -1002,3 +985,42 @@ describe('registerCleanup', () => { expect(existsSync(app.root)).toBe(false) }) }) + +test.each(['webpack', 'rspack'] as const)( + '%s: concurrent native loaders keep console messages in their own builds', + async (bundler) => { + const build = () => + bundleApp({ + files: { + 'entry.js': 'export const value = 1', + 'warning-loader.cjs': `module.exports = function(code) { console.warn(this.resourcePath + ' MARK_LOADER_WARNING'); return code }`, + }, + bundler, + env: 'ssr', + entry: 'entry.js', + configure(options) { + const rules = (options.module as { rules: Array }).rules + rules.push({ + test: /\.js$/, + loader: path.join(String(options.context), 'warning-loader.cjs'), + }) + }, + }) + const [first, second] = await Promise.all([build(), build()]) + for (const [app, other] of [ + [first, second], + [second, first], + ] as const) { + expect( + app.consoleMessages.some( + (text) => + text.includes(app.root) && text.includes('MARK_LOADER_WARNING'), + ), + ).toBe(true) + expect( + app.consoleMessages.some((text) => text.includes(other.root)), + ).toBe(false) + } + }, + timeout, +) diff --git a/packages/compiler-test-utils/tests/integration/rsbuild-plugin-host.test.ts b/packages/compiler-test-utils/tests/integration/rsbuild-plugin-host.test.ts index c570a97dec..2d07089dab 100644 --- a/packages/compiler-test-utils/tests/integration/rsbuild-plugin-host.test.ts +++ b/packages/compiler-test-utils/tests/integration/rsbuild-plugin-host.test.ts @@ -136,3 +136,65 @@ test( }, timeout, ) + +test.each(['dev', 'build'] as const)( + 'the %s host records warnings through Rsbuild’s logger', + async (mode) => { + const host = await createRsbuildPluginHost({ + dir: testsDir, + registerCleanup: onTestFinished, + files: { 'src/entry.ts': 'export const value = 1' }, + serve: mode === 'dev', + plugins: [ + { + name: 'logger-control', + setup(api) { + api.onBeforeEnvironmentCompile(() => { + api.logger.warn('src/entry.ts: logger control warning') + }) + }, + }, + ], + }) + const diagnostics = + mode === 'dev' ? host.diagnostics : (await host.build()).diagnostics + expectDiagnostic(diagnostics, { + severity: 'warning', + file: 'src/entry.ts', + explains: { mentions: ['logger control'] }, + }) + }, + timeout, +) + +test( + 'concurrent Rsbuild apps retain their own native-loader diagnostics', + async () => { + const start = () => + createRsbuildPluginHost({ + dir: testsDir, + registerCleanup: onTestFinished, + files: { 'src/entry.ts': "export const value = '__MARK__'" }, + plugins: [userPlugin()], + }) + const [first, second] = await Promise.all([start(), start()]) + await Promise.all([ + first.edit({ 'src/entry.ts': "export const value = '__MARK__ edited'" }), + second.edit({ 'src/entry.ts': "export const value = '__MARK__ edited'" }), + ]) + for (const [app, other] of [ + [first, second], + [second, first], + ] as const) { + expectDiagnostic(app.diagnostics, { + severity: 'warning', + file: 'src/entry.ts', + root: app.root, + }) + expect( + app.diagnostics.some(({ text }) => text.includes(other.root)), + ).toBe(false) + } + }, + timeout, +) diff --git a/packages/compiler-test-utils/tests/plugin-host.test.ts b/packages/compiler-test-utils/tests/plugin-host.test.ts index 88eb01f066..4989a89a1e 100644 --- a/packages/compiler-test-utils/tests/plugin-host.test.ts +++ b/packages/compiler-test-utils/tests/plugin-host.test.ts @@ -132,3 +132,25 @@ test('nothing reported: a quiet plugin leaves no problem on any channel', async await app.importServer('/src/server.ts') expectNoProblems(app.diagnostics) }) + +test('two live apps keep console diagnostics scoped to their own work', async () => { + const [first, second] = await Promise.all([host('console'), host('console')]) + await Promise.all([ + first.importServer('/src/server.ts'), + second.importServer('/src/server.ts'), + ]) + for (const [app, other] of [ + [first, second], + [second, first], + ]) { + expectDiagnostic(app!.diagnostics, { + severity: 'warning', + file: 'src/server.ts', + root: app!.root, + times: 1, + }) + expect( + app!.diagnostics.some(({ text }) => text.includes(other!.root)), + ).toBe(false) + } +}) diff --git a/packages/react-start-rsc/AGENTS.md b/packages/react-start-rsc/AGENTS.md index 9d6185d7d7..cd015065e6 100644 --- a/packages/react-start-rsc/AGENTS.md +++ b/packages/react-start-rsc/AGENTS.md @@ -1,5 +1,5 @@ # React Start RSC -- Tests run in two tiers. `test:unit` (fast tier) runs the runtime's unit tests in jsdom. `test:integration` (slow tier) runs `tests/integration/**`: real Start apps with RSC on Vite and Rsbuild dev servers and builds, and real browser pages; its Nx target builds `@tanstack/react-start` first. Run both tiers before handing back. +- Tests run in two tiers. `test:unit` is reserved for fast compiler acceptance (currently empty). `test:noncompiler` runs the 49 RSC runtime tests in jsdom under `tests/outside-compiler-corpus/noncompiler/`. `test:integration` (slow tier) runs `tests/integration/**`: real Start apps with RSC on Vite and Rsbuild dev servers and builds, and real browser pages; its Nx target builds `@tanstack/react-start` first. Run integration, noncompiler, types and eslint before handing back. - To run one test file or `-t` filter quickly, the slow-tier load gate and the test budgets: [compiler-test-utils/AGENTS.md](../compiler-test-utils/AGENTS.md). - The spec these tests cite (clause ids such as `J4.12`, `G3`, `§5.7`), the rulings and the known bugs: [compiler-test-utils/oracle/README.md](../compiler-test-utils/oracle/README.md). diff --git a/packages/react-start-rsc/package.json b/packages/react-start-rsc/package.json index 07ffc4d94e..048a54b1e9 100644 --- a/packages/react-start-rsc/package.json +++ b/packages/react-start-rsc/package.json @@ -24,8 +24,8 @@ ], "scripts": { "clean": "rimraf ./dist && rimraf ./coverage", - "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit && pnpm test:integration", - "test:unit": "vitest --project unit", + "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit && pnpm test:integration && pnpm test:noncompiler", + "test:unit": "vitest --project unit --passWithNoTests", "test:unit:dev": "vitest --project unit --watch", "test:integration": "vitest --project integration", "test:eslint": "eslint ./src ./tests", @@ -37,7 +37,8 @@ "test:types:ts60": "tsc6 && tsc6 -p tests", "test:types:ts70": "tsc && tsc -p tests", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", - "build": "vite build" + "build": "vite build", + "test:noncompiler": "vitest --project noncompiler" }, "nx": { "targets": { @@ -62,6 +63,17 @@ "target": "build" } ] + }, + "test:noncompiler": { + "dependsOn": [ + "^build", + { + "projects": [ + "@tanstack/react-start-client" + ], + "target": "build" + } + ] } } }, diff --git a/packages/react-start-rsc/tests/integration/rsc-app.ts b/packages/react-start-rsc/tests/integration/rsc-app.ts index 7303c35d5a..e66fa68d38 100644 --- a/packages/react-start-rsc/tests/integration/rsc-app.ts +++ b/packages/react-start-rsc/tests/integration/rsc-app.ts @@ -29,10 +29,7 @@ import { withBuildEnvironment, } from '@tanstack/compiler-test-utils/build-harness' import { createBuilder, mergeConfig, preview } from 'vite' -import { - workspacePackage, - workspacePackageLinks, -} from '@tanstack/compiler-test-utils/workspace-packages' +import { workspacePackageLinks } from '@tanstack/compiler-test-utils/workspace-packages' import { onTestFinished } from 'vitest' import type { BrowserPage } from '@tanstack/compiler-test-utils/browser' import type { @@ -46,39 +43,27 @@ import type { const harnessDir = path.dirname(fileURLToPath(import.meta.url)) -/** The built workspace package `@tanstack/react-start`. */ -export const reactStartPackage = workspacePackage('@tanstack/react-start') - -/** - * `tanstackStart` of the built `@tanstack/react-start/plugin/vite`, what an - * app's `vite.config.ts` imports. - */ -async function tanstackStartVitePlugin(): Promise< - (options?: Record) => unknown -> { - const entry = pathToFileURL( - path.join(reactStartPackage, 'dist/esm/plugin/vite.js'), - ).href - const { tanstackStart } = (await import(/* @vite-ignore */ entry)) as { - tanstackStart: (options?: Record) => unknown +/** Resolve the installed public export with Node, independent of dist layout. */ +async function tanstackStartPlugin( + bundler: 'vite' | 'rsbuild', +): Promise<(options?: Record) => unknown> { + const app = await createApp({ + dir: harnessDir, + prefix: '.rsc-plugin-import-', + files: { + 'plugin.mjs': `export { tanstackStart } from '@tanstack/react-start/plugin/${bundler}'`, + }, + symlinks: workspacePackageLinks(['@tanstack/react-start']), + }) + try { + return ( + await import( + /* @vite-ignore */ pathToFileURL(path.join(app.root, 'plugin.mjs')).href + ) + ).tanstackStart + } finally { + await app.dispose() } - return tanstackStart -} - -/** - * `tanstackStart` of the built `@tanstack/react-start/plugin/rsbuild`, what - * an app's `rsbuild.config.ts` imports. - */ -async function tanstackStartRsbuildPlugin(): Promise< - (options?: Record) => unknown -> { - const entry = pathToFileURL( - path.join(reactStartPackage, 'dist/esm/plugin/rsbuild.js'), - ).href - const { tanstackStart } = (await import(/* @vite-ignore */ entry)) as { - tanstackStart: (options?: Record) => unknown - } - return tanstackStart } /** @@ -133,7 +118,7 @@ export async function startRscDevServer( options: RscDevServerOptions, ): Promise { const { files, start, config, ...devServerOptions } = options - const tanstackStart = await tanstackStartVitePlugin() + const tanstackStart = await tanstackStartPlugin('vite') return createDevServer({ dir: harnessDir, prefix: '.rsc-dev-server-', @@ -201,7 +186,7 @@ export async function startRscPreviewServer(options: { registerCleanup?: (cleanup: () => Promise) => void }): Promise { const registerCleanup = options.registerCleanup ?? onTestFinished - const tanstackStart = await tanstackStartVitePlugin() + const tanstackStart = await tanstackStartPlugin('vite') const app = await createApp({ dir: harnessDir, prefix: '.rsc-preview-server-', @@ -284,7 +269,7 @@ export async function startRscRsbuildDevServer( inAppDirectory = true, ...devServerOptions } = options - const tanstackStart = await tanstackStartRsbuildPlugin() + const tanstackStart = await tanstackStartPlugin('rsbuild') const cwd = process.cwd() try { return await createRsbuildDevServer({ diff --git a/packages/react-start-rsc/tests/integration/rsc-css-app.ts b/packages/react-start-rsc/tests/integration/rsc-css-app.ts index a47ee690e4..e1fb9d8618 100644 --- a/packages/react-start-rsc/tests/integration/rsc-css-app.ts +++ b/packages/react-start-rsc/tests/integration/rsc-css-app.ts @@ -336,7 +336,7 @@ export function rscCssApp(options: { `/src/rows/${row.key}.${row.jsx ? 'jsx' : 'tsx'}`, { environment: 'client', - skip: /\/node_modules\/|^\/@(vite|react-refresh|fs|id)\b/, + skip: /\/node_modules\/|^\/@(vite|react-refresh)\b/, }, ), ), diff --git a/packages/react-start-rsc/tests/integration/rsc-css-diagnostics.test.ts b/packages/react-start-rsc/tests/integration/rsc-css-diagnostics.test.ts new file mode 100644 index 0000000000..718caf533f --- /dev/null +++ b/packages/react-start-rsc/tests/integration/rsc-css-diagnostics.test.ts @@ -0,0 +1,53 @@ +import { expect, test } from 'vitest' +import { expectDiagnostic } from '@tanstack/compiler-test-utils/diagnostics' +import { startRscDevServer, startRscRsbuildDevServer } from './rsc-app' + +const files = { + 'src/stream.tsx': `import { createServerFn } from '@tanstack/react-start' +import { renderToReadableStream } from '@tanstack/react-start/rsc' +import styles from './stream.module.css' +function Card() { return
MARK_STREAM
} +export const render = createServerFn().handler(async () => { + const node = + const args = [node] as const + const first = renderToReadableStream(node) + const second = renderToReadableStream(...args) + await Promise.all([new Response(first).text(), new Response(second).text()]) + return 'MARK_STREAMS_RENDERED' +}) +`, + 'src/stream.module.css': '.card { color: red }', + 'src/routes/index.tsx': `import { createFileRoute } from '@tanstack/react-router' +import { render } from '../stream' +export const Route = createFileRoute('/')({ + loader: () => render(), + component: () =>
{Route.useLoaderData()}
, +}) +`, +} + +// J7.3 / D8(c), G5: the real RSC integration currently skips identifier and +// spread arguments silently. Two calls in one file require one useful warning. +// G5 requires positions on errors, not on this warning; wording/channel are free. +test.fails.each(['vite', 'rsbuild'] as const)( + '%s dev explains the CSS limitation once per source file', + async (bundler) => { + const server = await ( + bundler === 'vite' ? startRscDevServer : startRscRsbuildDevServer + )({ + files, + browser: true, + }) + const response = await fetch(server.url!) + expect(response.ok).toBe(true) + expect(await response.text()).toContain('MARK_STREAMS_RENDERED') + expectDiagnostic(server.diagnostics, { + severity: 'warning', + file: 'src/stream.tsx', + root: server.root, + names: ['renderToReadableStream'], + explains: true, + times: 1, + }) + }, +) diff --git a/packages/react-start-rsc/tests/integration/rsc-css.test.ts b/packages/react-start-rsc/tests/integration/rsc-css.test.ts index 2e39a67220..a51f6d97fd 100644 --- a/packages/react-start-rsc/tests/integration/rsc-css.test.ts +++ b/packages/react-start-rsc/tests/integration/rsc-css.test.ts @@ -8,10 +8,7 @@ */ import path from 'node:path' import { describe, expect, test } from 'vitest' -import { - diagnosticsOf, - expectDiagnostic, -} from '@tanstack/compiler-test-utils/diagnostics' +import { expectDiagnostic } from '@tanstack/compiler-test-utils/diagnostics' import { BADGE_BACKGROUND, CARD_BACKGROUND, @@ -492,8 +489,11 @@ export const wrap = (node: React.ReactNode) => renderServerComponent(node) 'dev: renderToReadableStream with $name warns, naming the file', ({ row }) => { const server = app.server() - expectDiagnostic(diagnosticsOf(server.logs, 'warning'), { + expectDiagnostic(server.diagnostics, { + severity: 'warning', names: ['renderToReadableStream'], + explains: true, + times: 1, file: path.join('src/rows', `${row.key}.tsx`), root: server.root, }) diff --git a/packages/react-start-rsc/tests/integration/rsc-start-private.test.ts b/packages/react-start-rsc/tests/integration/rsc-start-private.test.ts index 8a2c6708e9..69d8af5edd 100644 --- a/packages/react-start-rsc/tests/integration/rsc-start-private.test.ts +++ b/packages/react-start-rsc/tests/integration/rsc-start-private.test.ts @@ -1,3 +1,7 @@ +import { + diagnosticsOf, + expectDiagnostic, +} from '@tanstack/compiler-test-utils/diagnostics' import { describe, expect, test } from 'vitest' import { openRscPage, startRscDevServer, waitForHydration } from './rsc-app' import { callFromPage, page } from './rsc-start-page' @@ -28,23 +32,24 @@ export const internal = createServerFn().handler(() => 'MARK_INTERNAL') import { internal } from './internal' export const greet = createServerFn().handler(async () => 'MARK_GREET:' + (await internal())) `, - 'src/routes/index.tsx': - page(`import { createClientRpc } from '@tanstack/react-start/client-rpc' -if (typeof window !== 'undefined') { + 'src/routes/index.tsx': page(`if (typeof window !== 'undefined') { ;(window as any).callUrl = async (url: string) => { - const id = decodeURIComponent(new URL(url, location.href).pathname.split('/').at(-1)!) - let ok: boolean | undefined + let outcome: { ok: boolean; value: string } | undefined + let refusal: string | undefined + // The public caller supplies the real request envelope. Only its URL + // changes; fetch uses the public .url unchanged, with no id parsing. try { - const value = await createClientRpc(id)({ method: 'GET', fetch: async (request: RequestInfo | URL, init?: RequestInit) => { - const response = await fetch(request, init) - ok = response.ok + const value: unknown = await greet({ fetch: async (_input, init) => { + const response = await fetch(url, init) + outcome = { ok: response.ok, value: await response.clone().text() } return response } }) - const error = value instanceof Error ? value : value?.error - return { ok, error: error ? String(error) : undefined, value: JSON.stringify(value, (_key, item) => item instanceof Error ? String(item) : item) } + if (value instanceof Error) { refusal = String(value) } } catch (error) { - return { ok, error: String(error) } + if (!outcome) { throw error } + refusal = String(error) } + return { ...outcome, error: refusal } } } `), @@ -79,9 +84,10 @@ if (typeof window !== 'undefined') { true, ) const explanation = outcome.error ?? outcome.value - expect(explanation).toMatch( - /forbid|denied|unauthor|unregistered|unknown.{0,40}function|not.{0,40}(?:found|allow|available|expos|call)|server.only/i, - ) + // Any actionable refusal is allowed, including "not accessible from client". + expectDiagnostic(diagnosticsOf(explanation, 'error'), { + explains: true, + }) expect(explanation).not.toMatch(/TypeError|ReferenceError|SyntaxError/) expect(explanation).not.toContain('MARK_INTERNAL') }, diff --git a/packages/react-start-rsc/tests/ClientSlot.test.tsx b/packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/ClientSlot.test.tsx similarity index 96% rename from packages/react-start-rsc/tests/ClientSlot.test.tsx rename to packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/ClientSlot.test.tsx index fa6fef2e9c..6d3e41e14f 100644 --- a/packages/react-start-rsc/tests/ClientSlot.test.tsx +++ b/packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/ClientSlot.test.tsx @@ -1,7 +1,8 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { describe, expect, it, vi } from 'vitest' import { render, screen } from '@testing-library/react' -import { ClientSlot } from '../src/ClientSlot' -import { SlotProvider } from '../src/SlotContext' +import { ClientSlot } from '../../../src/ClientSlot' +import { SlotProvider } from '../../../src/SlotContext' describe('ClientSlot', () => { describe('error handling', () => { diff --git a/packages/react-start-rsc/tests/ReplayableStream.test.ts b/packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/ReplayableStream.test.ts similarity index 99% rename from packages/react-start-rsc/tests/ReplayableStream.test.ts rename to packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/ReplayableStream.test.ts index 3f2558bad6..c4e4e1e561 100644 --- a/packages/react-start-rsc/tests/ReplayableStream.test.ts +++ b/packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/ReplayableStream.test.ts @@ -1,8 +1,9 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { describe, expect, it } from 'vitest' import { REPLAYABLE_STREAM_MARKER, ReplayableStream, -} from '../src/ReplayableStream' +} from '../../../src/ReplayableStream' describe('ReplayableStream', () => { describe('basic functionality', () => { diff --git a/packages/react-start-rsc/tests/ServerComponent.test.tsx b/packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/ServerComponent.test.tsx similarity index 92% rename from packages/react-start-rsc/tests/ServerComponent.test.tsx rename to packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/ServerComponent.test.tsx index a15a47a608..a9cb5e95d0 100644 --- a/packages/react-start-rsc/tests/ServerComponent.test.tsx +++ b/packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/ServerComponent.test.tsx @@ -1,3 +1,4 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import React from 'react' import { describe, expect, it, vi } from 'vitest' import { act, render } from '@testing-library/react' @@ -7,11 +8,11 @@ import { createFromReadableStream as browserDecode } from '@vitejs/plugin-rsc/br import { createCompositeFromStream, createServerComponentFromStream, -} from '../src/createServerComponentFromStream' +} from '../../../src/createServerComponentFromStream' import { SERVER_COMPONENT_CSS_HREFS, SERVER_COMPONENT_JS_PRELOADS, -} from '../src/ServerComponentTypes' +} from '../../../src/ServerComponentTypes' // Force the client implementation to be used in tests. vi.mock('@tanstack/start-client-core', () => { @@ -69,7 +70,8 @@ describe('ServerComponent (client)', () => { const Component = createServerComponentFromStream(stream) - const { CompositeComponent } = await import('../src/CompositeComponent') + const { CompositeComponent } = + await import('../../../src/CompositeComponent') await act(async () => { render( diff --git a/packages/react-start-rsc/tests/SlotContext.test.tsx b/packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/SlotContext.test.tsx similarity index 95% rename from packages/react-start-rsc/tests/SlotContext.test.tsx rename to packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/SlotContext.test.tsx index c98ed733d1..7471995a11 100644 --- a/packages/react-start-rsc/tests/SlotContext.test.tsx +++ b/packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/SlotContext.test.tsx @@ -1,6 +1,7 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { describe, expect, it } from 'vitest' import { render, screen } from '@testing-library/react' -import { SlotProvider, useSlotContext } from '../src/SlotContext' +import { SlotProvider, useSlotContext } from '../../../src/SlotContext' describe('SlotContext', () => { describe('SlotProvider', () => { diff --git a/packages/react-start-rsc/tests/createRscProxy.test.tsx b/packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/createRscProxy.test.tsx similarity index 92% rename from packages/react-start-rsc/tests/createRscProxy.test.tsx rename to packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/createRscProxy.test.tsx index ba90346808..6b97454702 100644 --- a/packages/react-start-rsc/tests/createRscProxy.test.tsx +++ b/packages/react-start-rsc/tests/outside-compiler-corpus/noncompiler/createRscProxy.test.tsx @@ -1,11 +1,12 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import React from 'react' import { describe, expect, it } from 'vitest' import { render, screen } from '@testing-library/react' -import { ReactElement, ReactLazy } from '../src/reactSymbols' +import { ReactElement, ReactLazy } from '../../../src/reactSymbols' -import { awaitLazyElements } from '../src/awaitLazyElements' -import { CompositeComponent } from '../src/CompositeComponent' -import { createRscProxy } from '../src/createRscProxy' +import { awaitLazyElements } from '../../../src/awaitLazyElements' +import { CompositeComponent } from '../../../src/CompositeComponent' +import { createRscProxy } from '../../../src/createRscProxy' describe('createRscProxy rendering', () => { it('a renderable proxy renders its tree inline', () => { diff --git a/packages/react-start-rsc/tests/rsc-css-diagnostics.test.ts b/packages/react-start-rsc/tests/rsc-css-diagnostics.test.ts deleted file mode 100644 index 532020895f..0000000000 --- a/packages/react-start-rsc/tests/rsc-css-diagnostics.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -// @vitest-environment node -import { afterEach, describe, expect, test, vi } from 'vitest' -import { - captureConsole, - diagnosticPosition, - diagnosticsOf, - expectDiagnostic, - findDiagnostics, -} from '@tanstack/compiler-test-utils/diagnostics' -import { createStartCompiler } from '../../start-plugin-core/tests/regression-helpers' -import { createRscCssCompilerTransforms } from '../src/plugin/rscCssTransform' - -const id = '/test/src/stream.tsx' -const source = `import { renderToReadableStream } from '@tanstack/react-start/rsc' -export function render(node: React.ReactNode) { - const args = [node] as const - const first = renderToReadableStream(node) - const second = renderToReadableStream(...args) - return [first, second] -} -` - -afterEach(() => { - vi.unstubAllEnvs() -}) - -async function compile(mode: 'dev' | 'build') { - vi.stubEnv('NODE_ENV', mode === 'dev' ? 'development' : 'production') - const compilerTransforms = createRscCssCompilerTransforms({ - loadCssExpression: '[]', - }) - const { compiler } = createStartCompiler({ - env: 'server', - mode, - compilerTransforms, - }) - const warnings: Array = [] - const captured = await captureConsole(() => - compiler.compile({ - code: source, - id, - warn: (message) => { - warnings.push(message) - }, - }), - ) - return [...captured.diagnostics, ...diagnosticsOf(warnings, 'warning')] -} - -describe('RSC stream diagnostics from the real compiler', () => { - // Bug: identifier/spread stream arguments silently miss CSS delivery - // (a dev warning is required: decision D8(c), V1R H01). - // Source: react-start-rsc src/plugin/rscCssTransform.ts:91-93: the - // `renderToReadableStream` transform skips a spread argument (92) and an - // argument that is not JSX (93, `isTopLevelJsx`) with `continue`, and - // nothing in the transform warns. - // Impact: no diagnostic tells the developer to pass visible JSX instead. - test.fails( - 'dev explains the CSS limitation once per source file at an original call position', - async () => { - const diagnostics = await compile('dev') - const diagnostic = expectDiagnostic(diagnostics, { - file: id, - names: ['renderToReadableStream'], - times: 1, - }) - expect(diagnostic.text).toMatch(/css|styles?/i) - expect(diagnostic.text).toMatch(/jsx|inline|literal/i) - expect(diagnostic.text).toMatch( - /pass|use|wrap|move|instead|direct|cannot|unable|unavailable|unsupported|not supported|required|recommend|prefer|provide|static|literal/i, - ) - const calls = [ - 'renderToReadableStream(node)', - 'renderToReadableStream(...args)', - ] - const positions = calls.flatMap((call) => { - const start = source.indexOf(call) - return Array.from({ length: call.length }, (_, offset) => - diagnosticPosition(source, start + offset), - ) - }) - expect( - positions.some( - (position) => - findDiagnostics([diagnostic], { - file: id, - position, - source, - }).length > 0, - ), - ).toBe(true) - }, - ) - - test('production has no development-only stream warning', async () => { - expect( - findDiagnostics(await compile('build'), { - names: ['renderToReadableStream'], - }), - ).toEqual([]) - }) -}) diff --git a/packages/react-start-rsc/vite.config.ts b/packages/react-start-rsc/vite.config.ts index d8b16a35c5..013eadf084 100644 --- a/packages/react-start-rsc/vite.config.ts +++ b/packages/react-start-rsc/vite.config.ts @@ -35,13 +35,28 @@ const config = defineConfig({ reporters: ['default', '@tanstack/compiler-test-utils/budget-reporter'], projects: [ { - // Fast tier (`test:unit`): the runtime's unit tests (jsdom). The type - // tests (`*.test-d.tsx`) are checked by `test:types` (`tsc -p tests`). + // Fast compiler acceptance tier; real apps run in integration. + // Runtime coverage is selected by test:noncompiler below. extends: true, test: { name: 'unit', include: ['**/*.{test,spec}.?(c|m)[jt]s?(x)'], - exclude: [...configDefaults.exclude, 'tests/integration/**'], + exclude: [ + ...configDefaults.exclude, + 'tests/integration/**', + '**/outside-compiler-corpus/**', + ], + environment: 'jsdom', + setupFiles: ['./tests/setup.ts'], + }, + }, + { + extends: true, + test: { + name: 'noncompiler', + include: [ + 'tests/outside-compiler-corpus/noncompiler/**/*.test.ts?(x)', + ], environment: 'jsdom', setupFiles: ['./tests/setup.ts'], }, @@ -54,6 +69,7 @@ const config = defineConfig({ test: { name: 'integration', include: ['tests/integration/**/*.test.ts?(x)'], + exclude: [...configDefaults.exclude, '**/outside-compiler-corpus/**'], environment: 'node', // The dev servers and their module runners run in the test // process, and `vite dev` runs with `development`: Vitest's `test` diff --git a/packages/start-plugin-core/AGENTS.md b/packages/start-plugin-core/AGENTS.md index 58ffc1aa7f..c55cc77e57 100644 --- a/packages/start-plugin-core/AGENTS.md +++ b/packages/start-plugin-core/AGENTS.md @@ -8,3 +8,5 @@ - Tests run in two tiers. `test:unit` (fast tier, the inner loop) runs `tests/**` in process and depends on `^build` only. `test:integration` (slow tier) runs `tests/integration/**`: every test that starts a real build (`buildStart`), a dev server that links the built `@tanstack/react-start` (`startDevServer`, `startProtectedDevServer`, `linkStartRuntime`), an Rsbuild dev server, a child Node process or a browser page; its Nx target builds `@tanstack/react-start` first. Put such tests under `tests/integration/`; a file with tests of both kinds is split by test into files of the same name in both directories. Run both tiers before handing back. - To run one test file or `-t` filter quickly, the slow-tier load gate and the test budgets: [compiler-test-utils/AGENTS.md](../compiler-test-utils/AGENTS.md). - The spec these tests cite (clause ids such as `J4.12`, `G3`, `§5.7`), the rulings and the known bugs: [compiler-test-utils/oracle/README.md](../compiler-test-utils/oracle/README.md). + +- `test:noncompiler` retains runtime/build-plumbing coverage under `tests/outside-compiler-corpus/noncompiler/`; it is selected separately from compiler acceptance and implementation controls, and runs in root PR/CI and compiler platform jobs. diff --git a/packages/start-plugin-core/package.json b/packages/start-plugin-core/package.json index d281552b71..0596613a13 100644 --- a/packages/start-plugin-core/package.json +++ b/packages/start-plugin-core/package.json @@ -27,7 +27,7 @@ "scripts": { "clean": "rimraf ./dist && rimraf ./coverage", "clean:snapshots": "rimraf **/*snapshot* --glob", - "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit && pnpm test:integration", + "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit && pnpm test:integration && pnpm test:noncompiler", "test:unit": "vitest --project unit", "test:integration": "vitest --project integration", "test:implementation": "vitest --project implementation --project implementation-integration", @@ -42,7 +42,8 @@ "test:types:ts60": "tsc6", "test:types:ts70": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", - "build": "vite build" + "build": "vite build", + "test:noncompiler": "vitest --project noncompiler" }, "nx": { "targets": { diff --git a/packages/start-plugin-core/tests/createVirtualModule.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/createVirtualModule.test.ts similarity index 86% rename from packages/start-plugin-core/tests/createVirtualModule.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/createVirtualModule.test.ts index bca42afd36..223fa9db44 100644 --- a/packages/start-plugin-core/tests/createVirtualModule.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/createVirtualModule.test.ts @@ -1,5 +1,6 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { describe, expect, test } from 'vitest' -import { createVirtualModule } from '../src/vite/createVirtualModule' +import { createVirtualModule } from '../../../src/vite/createVirtualModule' describe('createVirtualModule', () => { test('resolves and loads the default vite virtual id', () => { diff --git a/packages/start-plugin-core/tests/csrf-warning-config.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/csrf-warning-config.test.ts similarity index 86% rename from packages/start-plugin-core/tests/csrf-warning-config.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/csrf-warning-config.test.ts index abe28087d0..9fb440e0c3 100644 --- a/packages/start-plugin-core/tests/csrf-warning-config.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/csrf-warning-config.test.ts @@ -1,7 +1,8 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { describe, expect, test } from 'vitest' -import { parseStartConfig as parseViteStartConfig } from '../src/vite/schema' -import { parseStartConfig as parseRsbuildStartConfig } from '../src/rsbuild/schema' -import { createViteDefineConfig } from '../src/vite/planning' +import { parseStartConfig as parseViteStartConfig } from '../../../src/vite/schema' +import { parseStartConfig as parseRsbuildStartConfig } from '../../../src/rsbuild/schema' +import { createViteDefineConfig } from '../../../src/vite/planning' const root = process.cwd() const corePluginOpts = { framework: 'react' as const } diff --git a/packages/start-plugin-core/tests/entry-planning.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/entry-planning.test.ts similarity index 91% rename from packages/start-plugin-core/tests/entry-planning.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/entry-planning.test.ts index a16bce888f..9df44dae28 100644 --- a/packages/start-plugin-core/tests/entry-planning.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/entry-planning.test.ts @@ -1,3 +1,4 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { mkdirSync, mkdtempSync, @@ -9,9 +10,9 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { normalize } from 'pathe' import { afterEach, describe, expect, test } from 'vitest' -import { resolveStartEntryPlan } from '../src/planning' -import { parseStartConfig as parseRsbuildStartConfig } from '../src/rsbuild/schema' -import { parseStartConfig as parseViteStartConfig } from '../src/vite/schema' +import { resolveStartEntryPlan } from '../../../src/planning' +import { parseStartConfig as parseRsbuildStartConfig } from '../../../src/rsbuild/schema' +import { parseStartConfig as parseViteStartConfig } from '../../../src/vite/schema' const corePluginOpts = { framework: 'react' as const } const defaultEntryPaths = { diff --git a/packages/start-plugin-core/tests/post-server-build.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/post-server-build.test.ts similarity index 82% rename from packages/start-plugin-core/tests/post-server-build.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/post-server-build.test.ts index e290382d4d..6ee597f5ca 100644 --- a/packages/start-plugin-core/tests/post-server-build.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/post-server-build.test.ts @@ -1,3 +1,4 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { describe, expect, it, vi } from 'vitest' vi.mock('@tanstack/start-server-core/constants', () => ({ @@ -6,14 +7,14 @@ vi.mock('@tanstack/start-server-core/constants', () => ({ }, })) -vi.mock('../src/build-sitemap', () => ({ +vi.mock('../../../src/build-sitemap', () => ({ buildSitemap: vi.fn(), })) describe('postServerBuild', () => { it('rejects absolute SPA maskPath URLs to avoid external prerendering', async () => { const prerender = vi.fn(async () => {}) - const { postBuild } = await import('../src/post-build') + const { postBuild } = await import('../../../src/post-build') const startConfig = { spa: { diff --git a/packages/start-plugin-core/tests/prerender-ssrf.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/prerender-ssrf.test.ts similarity index 96% rename from packages/start-plugin-core/tests/prerender-ssrf.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/prerender-ssrf.test.ts index 06050fdeee..7cb604fdee 100644 --- a/packages/start-plugin-core/tests/prerender-ssrf.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/prerender-ssrf.test.ts @@ -1,9 +1,10 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { promises as fsp } from 'node:fs' import { describe, expect, it, vi } from 'vitest' -import { prerender } from '../src/prerender' +import { prerender } from '../../../src/prerender' -vi.mock('../src/utils', async () => { - const actual = await vi.importActual('../src/utils') +vi.mock('../../../src/utils', async () => { + const actual = await vi.importActual('../../../src/utils') return { ...actual, createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {} }), diff --git a/packages/start-plugin-core/tests/prerender-vite.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/prerender-vite.test.ts similarity index 93% rename from packages/start-plugin-core/tests/prerender-vite.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/prerender-vite.test.ts index 013557e4df..f725f28b2d 100644 --- a/packages/start-plugin-core/tests/prerender-vite.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/prerender-vite.test.ts @@ -1,10 +1,11 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { prerenderWithVite } from '../src/vite/prerender' +import { prerenderWithVite } from '../../../src/vite/prerender' const preview = vi.hoisted(() => vi.fn()) -vi.mock('../src/utils', async () => { - const actual = await vi.importActual('../src/utils') +vi.mock('../../../src/utils', async () => { + const actual = await vi.importActual('../../../src/utils') return { ...actual, createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {} }), diff --git a/packages/start-plugin-core/tests/rsbuild/normalized-client-build.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/rsbuild/normalized-client-build.test.ts similarity index 90% rename from packages/start-plugin-core/tests/rsbuild/normalized-client-build.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/rsbuild/normalized-client-build.test.ts index ce88ade3c5..b674600675 100644 --- a/packages/start-plugin-core/tests/rsbuild/normalized-client-build.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/rsbuild/normalized-client-build.test.ts @@ -1,6 +1,7 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { describe, expect, test } from 'vitest' -import { normalizeRspackClientBuild } from '../../src/rsbuild/normalized-client-build' -import { buildStartManifest } from '../../src/start-manifest-plugin/manifestBuilder' +import { normalizeRspackClientBuild } from '../../../../src/rsbuild/normalized-client-build' +import { buildStartManifest } from '../../../../src/start-manifest-plugin/manifestBuilder' import type { Rspack } from '@rsbuild/core' // Rspack reports module paths using the OS native separator on Windows diff --git a/packages/start-plugin-core/tests/rsbuild/output-directory.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/rsbuild/output-directory.test.ts similarity index 96% rename from packages/start-plugin-core/tests/rsbuild/output-directory.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/rsbuild/output-directory.test.ts index c0185a74eb..2e0aafd207 100644 --- a/packages/start-plugin-core/tests/rsbuild/output-directory.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/rsbuild/output-directory.test.ts @@ -1,8 +1,9 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { describe, expect, test } from 'vitest' import { createRsbuildEnvironmentPlan, resolveRsbuildOutputDirectory, -} from '../../src/rsbuild/planning' +} from '../../../../src/rsbuild/planning' describe('resolveRsbuildOutputDirectory', () => { test('uses explicit environment distPath string', () => { diff --git a/packages/start-plugin-core/tests/rsbuild/post-build.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/rsbuild/post-build.test.ts similarity index 85% rename from packages/start-plugin-core/tests/rsbuild/post-build.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/rsbuild/post-build.test.ts index 34475b9427..d3170bb935 100644 --- a/packages/start-plugin-core/tests/rsbuild/post-build.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/rsbuild/post-build.test.ts @@ -1,3 +1,4 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { describe, expect, it, vi } from 'vitest' @@ -17,8 +18,8 @@ describe('postBuildWithRsbuild', () => { expect(await response.text()).toBe('ok') }) - vi.doMock('../../src/prerender', async () => { - const actual = await vi.importActual('../../src/prerender') + vi.doMock('../../../../src/prerender', async () => { + const actual = await vi.importActual('../../../../src/prerender') return { ...actual, prerender: prerenderSpy, @@ -37,7 +38,7 @@ describe('postBuildWithRsbuild', () => { ) const { postBuildWithRsbuild } = - await import('../../src/rsbuild/post-build') + await import('../../../../src/rsbuild/post-build') try { await postBuildWithRsbuild({ diff --git a/packages/start-plugin-core/tests/rsbuild/watch-ignored.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/rsbuild/watch-ignored.test.ts similarity index 92% rename from packages/start-plugin-core/tests/rsbuild/watch-ignored.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/rsbuild/watch-ignored.test.ts index f1adf018e7..5172dff7b1 100644 --- a/packages/start-plugin-core/tests/rsbuild/watch-ignored.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/rsbuild/watch-ignored.test.ts @@ -1,5 +1,6 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { describe, expect, test } from 'vitest' -import { addWorkspaceWatchIgnored } from '../../src/rsbuild/watch-ignored' +import { addWorkspaceWatchIgnored } from '../../../../src/rsbuild/watch-ignored' describe('workspace watch exclusions', () => { test('preserves flags on an existing regular expression', () => { diff --git a/packages/start-plugin-core/tests/schema.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/schema.test.ts similarity index 85% rename from packages/start-plugin-core/tests/schema.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/schema.test.ts index 41509e249c..3f25c4e278 100644 --- a/packages/start-plugin-core/tests/schema.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/schema.test.ts @@ -1,7 +1,8 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import path from 'node:path' import { describe, expect, test } from 'vitest' -import { parseStartConfig as parseViteStartConfig } from '../src/vite/schema' -import { parseStartConfig as parseRsbuildStartConfig } from '../src/rsbuild/schema' +import { parseStartConfig as parseViteStartConfig } from '../../../src/vite/schema' +import { parseStartConfig as parseRsbuildStartConfig } from '../../../src/rsbuild/schema' const root = process.cwd() const corePluginOpts = { framework: 'react' as const } diff --git a/packages/start-plugin-core/tests/sitemap-output.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/sitemap-output.test.ts similarity index 97% rename from packages/start-plugin-core/tests/sitemap-output.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/sitemap-output.test.ts index e056febbe9..aa441bd74e 100644 --- a/packages/start-plugin-core/tests/sitemap-output.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/sitemap-output.test.ts @@ -1,12 +1,13 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { mkdtemp, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import path from 'node:path' import { describe, expect, it, vi } from 'vitest' import { z } from 'zod' -import { postBuild } from '../src/post-build' -import { prerender } from '../src/prerender' -import { parseStartConfig } from '../src/schema' -import type { TanStackStartOutputConfig } from '../src/schema' +import { postBuild } from '../../../src/post-build' +import { prerender } from '../../../src/prerender' +import { parseStartConfig } from '../../../src/schema' +import type { TanStackStartOutputConfig } from '../../../src/schema' describe('post-build sitemap', () => { it('writes sitemap files before resolving, using pages discovered during prerendering', async () => { diff --git a/packages/start-plugin-core/tests/start-manifest-plugin.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/start-manifest-plugin.test.ts similarity index 94% rename from packages/start-plugin-core/tests/start-manifest-plugin.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/start-manifest-plugin.test.ts index bf7909567d..900f4f7df5 100644 --- a/packages/start-plugin-core/tests/start-manifest-plugin.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/start-manifest-plugin.test.ts @@ -1,8 +1,12 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { runInNewContext } from 'node:vm' import { VIRTUAL_MODULES } from '@tanstack/start-server-core/virtual-modules' import { afterEach, describe, expect, test, vi } from 'vitest' -import { DEV_CLIENT_ENTRY, START_ENVIRONMENT_NAMES } from '../src/constants' -import { startManifestPlugin } from '../src/vite/start-manifest-plugin/plugin' +import { + DEV_CLIENT_ENTRY, + START_ENVIRONMENT_NAMES, +} from '../../../src/constants' +import { startManifestPlugin } from '../../../src/vite/start-manifest-plugin/plugin' vi.mock('@tanstack/start-server-core/virtual-modules', () => ({ VIRTUAL_MODULES: { diff --git a/packages/start-plugin-core/tests/start-manifest-plugin/manifestBuilder.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/start-manifest-plugin/manifestBuilder.test.ts similarity index 99% rename from packages/start-plugin-core/tests/start-manifest-plugin/manifestBuilder.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/start-manifest-plugin/manifestBuilder.test.ts index e0c4a1c3ad..53b98a3e1f 100644 --- a/packages/start-plugin-core/tests/start-manifest-plugin/manifestBuilder.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/start-manifest-plugin/manifestBuilder.test.ts @@ -1,19 +1,20 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { describe, expect, test } from 'vitest' import { deserialize } from 'seroval' -import { shouldRebaseInlineCssUrls } from '../../src/start-manifest-plugin/inlineCss' +import { shouldRebaseInlineCssUrls } from '../../../../src/start-manifest-plugin/inlineCss' import { appendUniqueStrings, buildStartManifest, createManifestAssetResolvers, scanClientChunks, serializeStartManifest, -} from '../../src/start-manifest-plugin/manifestBuilder' +} from '../../../../src/start-manifest-plugin/manifestBuilder' import { getRouteFilePathsFromModuleIds, normalizeViteClientBuild, normalizeViteClientChunk, -} from '../../src/vite/start-manifest-plugin/normalized-client-build' -import type { StartManifest } from '../../src/start-manifest-plugin/manifestBuilder' +} from '../../../../src/vite/start-manifest-plugin/normalized-client-build' +import type { StartManifest } from '../../../../src/start-manifest-plugin/manifestBuilder' import type { ManifestCssLink } from '@tanstack/router-core' import type { Rollup } from 'vite' diff --git a/packages/start-plugin-core/tests/utils.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/utils.test.ts similarity index 92% rename from packages/start-plugin-core/tests/utils.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/utils.test.ts index 0b05da53a6..fb17f1a942 100644 --- a/packages/start-plugin-core/tests/utils.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/utils.test.ts @@ -1,3 +1,4 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { afterEach, describe, expect, test, vi } from 'vitest' const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') @@ -9,7 +10,7 @@ async function importUtilsWithPlatform(platform: NodeJS.Platform) { value: platform, }) - return await import('../src/utils') + return await import('../../../src/utils') } afterEach(() => { diff --git a/packages/start-plugin-core/tests/vite/bundled-dev-styles.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/vite/bundled-dev-styles.test.ts similarity index 95% rename from packages/start-plugin-core/tests/vite/bundled-dev-styles.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/vite/bundled-dev-styles.test.ts index 6d8403d80c..1cb6e75b2a 100644 --- a/packages/start-plugin-core/tests/vite/bundled-dev-styles.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/vite/bundled-dev-styles.test.ts @@ -1,3 +1,4 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import path from 'node:path' @@ -6,7 +7,7 @@ import { expect, test } from 'vitest' import { captureBundledDevStyles, collectBundledDevStyles, -} from '../../src/vite/dev-server-plugin/dev-styles' +} from '../../../../src/vite/dev-server-plugin/dev-styles' test('collects ordered static and dynamic CSS from a completed bundled graph', async () => { const root = await realpath( diff --git a/packages/start-plugin-core/tests/vite/dev-styles.test.ts b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/vite/dev-styles.test.ts similarity index 99% rename from packages/start-plugin-core/tests/vite/dev-styles.test.ts rename to packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/vite/dev-styles.test.ts index da355b74c2..da7b72ace5 100644 --- a/packages/start-plugin-core/tests/vite/dev-styles.test.ts +++ b/packages/start-plugin-core/tests/outside-compiler-corpus/noncompiler/vite/dev-styles.test.ts @@ -1,8 +1,9 @@ +// Noncompiler coverage: runtime/build plumbing, outside the J1–J7 compiler oracle. import { describe, expect, test } from 'vitest' import { collectDevStyles, fetchCssFromModule, -} from '../../src/vite/dev-server-plugin/dev-styles' +} from '../../../../src/vite/dev-server-plugin/dev-styles' import type { EnvironmentModuleNode } from 'vite' function createCssNode(url: string, css: string): EnvironmentModuleNode { diff --git a/packages/start-plugin-core/vite.config.ts b/packages/start-plugin-core/vite.config.ts index 63bbaa643e..ff3b63a57a 100644 --- a/packages/start-plugin-core/vite.config.ts +++ b/packages/start-plugin-core/vite.config.ts @@ -27,6 +27,14 @@ const config = defineConfig({ watch: false, reporters: ['default', '@tanstack/compiler-test-utils/budget-reporter'], projects: [ + { + extends: true, + test: { + name: 'noncompiler', + include: ['outside-compiler-corpus/noncompiler/**/*.test.ts'], + typecheck: { enabled: true }, + }, + }, { // Fast tier (`test:unit`): compiles and evaluates in process; a Vite // dev server in middleware mode is allowed. @@ -63,7 +71,11 @@ const config = defineConfig({ test: { name: 'implementation', include: ['**/outside-compiler-corpus/**/*.test.ts'], - exclude: [...configDefaults.exclude, 'integration/**'], + exclude: [ + ...configDefaults.exclude, + 'integration/**', + '**/noncompiler/**', + ], typecheck: { enabled: true }, }, },