diff --git a/packages/start-plugin-core/tests/integration/importProtection/v2-edits-page-rsbuild.test.ts b/packages/start-plugin-core/tests/integration/importProtection/v2-edits-page-rsbuild.test.ts new file mode 100644 index 0000000000..033a6f498c --- /dev/null +++ b/packages/start-plugin-core/tests/integration/importProtection/v2-edits-page-rsbuild.test.ts @@ -0,0 +1,149 @@ +/** + * The edits of v2-edits-page.test.ts (FIX-PLAN V2-14; SPEC J6.13, G10) seen + * by a real browser page of a Start app on Rsbuild's dev server (Start's + * whole Rsbuild plugin, `@rsbuild/plugin-react` for React Refresh, as the + * hydrate-dev Rsbuild rows): the component uses the server-only + * `src/secret.server.ts` only in `createIsomorphicFn().server()` (allowed), + * then also live (denied), then only in `.server()` again; the target is + * deleted and recreated between the steps. After each step the page shows + * the edited component through a hot update (no page load), never the + * secret, the live use reads a safe mock, and the step reports its + * violations and only those. + */ +import { pluginReact } from '@rsbuild/plugin-react' +import { afterAll, describe, expect, test } from 'vitest' +import { openPage } from '@tanstack/compiler-test-utils/browser' +import { describeValuePrelude } from '../../importProtection/mock-helpers' +import { startRsbuildStartDevServer } from '../../rsbuild-dev-server' +import { + pageApp, + pageSteps, + pageWidget, + reportedImporters, + secretServerModule, +} from './v2-hosts' + +const timeout = 60_000 +const compileTimeout = timeout + +interface StepOutcome { + /** The widget's text. */ + text: string + /** `window.liveSecret()`, described, when the step uses it. */ + live?: string + /** Page loads so far (1: no full reload). */ + loads: number + /** Whether the client's code (its chunks or the step's hot updates) contains the secret. */ + servedSecret: boolean + /** The importers reported for the client by the compile of the step. */ + reported: Array +} + +/** The server and page close after the last test. */ +const cleanups: Array<() => Promise> = [] +afterAll(async () => { + for (const cleanup of cleanups.reverse()) { + await cleanup() + } +}) +const registerCleanup = (cleanup: () => Promise) => { + cleanups.push(cleanup) +} + +/** Runs every step once, shared by the tests. */ +let outcomes: Promise> | undefined +const run = () => + (outcomes ??= (async () => { + const server = await startRsbuildStartDevServer({ + compileTimeout, + hmr: true, + browser: true, + // Start serves the pages, not an HTML template. + config: { tools: { htmlPlugin: false }, plugins: [pluginReact()] }, + // `log: 'always'`: each compile reports what it finds, so a stale + // violation shows in the compile of the step that removed it. + start: { importProtection: { log: 'always' } }, + files: pageApp, + registerCleanup, + }) + const browser = await openPage(server.url!, { registerCleanup }) + const result: Array = [] + for (const { step, live } of pageSteps) { + if (step > 1) { + // The deletion and the recreation each in their own edit, settled: + // a removal landing while Rspack compiles is lost (FOLLOWUPS + // "UPSTREAM (W3-harness2)": watchpack 2.5.2 vendored by Rspack). + // Merge the steps back once Rspack bundles watchpack >= 2.6. + await server.edit({ 'src/secret.server.ts': null }) + await server.settle() + await server.edit({ 'src/secret.server.ts': secretServerModule }) + await server.settle() + await server.edit({ 'src/widget.tsx': pageWidget(step, live) }) + } + await browser.waitForText(`step-${step}`, { + selector: '[data-testid=widget]', + }) + const client = [ + ...Object.values(await server.outputs('client')), + ...Object.values(await server.hotUpdates('client')), + ] + result.push({ + text: await browser.text('[data-testid=widget]'), + ...(live && { + live: await browser.page.evaluate(`(() => { +${describeValuePrelude} +return describeValue(window.liveSecret(), 'MARK_SECRET') +})()`), + }), + loads: browser.loads(), + servedSecret: client.some((code) => code.includes('MARK_SECRET')), + // The last compile's warnings: with `log: 'always'` it reports every + // violation of the step's state. + reported: reportedImporters(server.warnings, 'client'), + }) + } + return result + })()) + +describe.each(pageSteps)('step $step (live use: $live)', ({ step, live }) => { + const outcome = async () => (await run())[step - 1]! + + test( + 'the page shows the edit without a page load, and never the secret', + async () => { + const { text, loads } = await outcome() + expect({ + clientBranch: text.includes('MARK_CLIENT_BRANCH'), + secret: text.includes('MARK_SECRET'), + loads, + }).toEqual({ clientBranch: true, secret: false, loads: 1 }) + }, + timeout, + ) + + test( + 'no code the client gets contains the secret', + async () => { + expect((await outcome()).servedSecret).toBe(false) + }, + timeout, + ) + + if (live) { + test( + 'the live use reads a safe mock', + async () => { + expect((await outcome()).live).toBe('a safe mock') + }, + timeout, + ) + } + + test( + 'the step reports its violations, and only those', + async () => { + expect((await outcome()).reported).toEqual(live ? ['src/widget.tsx'] : []) + }, + timeout, + ) +}) diff --git a/packages/start-plugin-core/tests/integration/importProtection/v2-edits-page.test.ts b/packages/start-plugin-core/tests/integration/importProtection/v2-edits-page.test.ts index 963c879d4c..ad20584b2d 100644 --- a/packages/start-plugin-core/tests/integration/importProtection/v2-edits-page.test.ts +++ b/packages/start-plugin-core/tests/integration/importProtection/v2-edits-page.test.ts @@ -12,76 +12,18 @@ import react from '@vitejs/plugin-react' import { afterAll, describe, expect, test } from 'vitest' import { openPage } from '@tanstack/compiler-test-utils/browser' -import { startDevServer, startServerEntryFiles } from '../../dev-server' +import { startDevServer } from '../../dev-server' import { describeValuePrelude } from '../../importProtection/mock-helpers' -import { reportedImporters } from './v2-hosts' +import { + pageApp, + pageSteps, + pageWidget, + reportedImporters, + secretServerModule, +} from './v2-hosts' const timeout = 30_000 -const secretServer = `export const secret = () => 'MARK_SECRET'\n` - -/** - * `src/widget.tsx` at `step`; `live`: also uses the denied import live - * (and gives it to the page, `window.liveSecret`). - */ -const widget = ( - step: number, - live: boolean, -) => `import { createIsomorphicFn } from '@tanstack/react-start' -import { secret } from './secret.server' -const read = createIsomorphicFn() - .server(() => secret()) - .client(() => 'MARK_CLIENT_BRANCH') -export function Widget() { -${ - live - ? ` ;(window as unknown as Record).liveSecret = secret - return

{read() + ' ' + String(secret()) + ' step-${step}'}

` - : ` return

{read() + ' step-${step}'}

` -} -} -` - -/** - * A Start app a browser opens (Start's default server and client entries, - * the real router over the generated route tree) whose index route renders - * `Widget` on the client only (`ssr: false`). - */ -const app = { - ...startServerEntryFiles, - 'harness/client-entry.ts': `import { createElement } from 'react' -import { hydrateRoot } from 'react-dom/client' -import { StartClient } from '@tanstack/react-start/client' -hydrateRoot(document, createElement(StartClient)) -`, - 'src/router.ts': `import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' -export const getRouter = () => createRouter({ routeTree }) -`, - 'src/routes/__root.tsx': `import { HeadContent, Outlet, Scripts, createRootRoute } from '@tanstack/react-router' -export const Route = createRootRoute({ component: Root }) -function Root() { - return ( - - - - - -
- - - - ) -} -`, - 'src/routes/index.tsx': `import { createFileRoute } from '@tanstack/react-router' -import { Widget } from '../widget' -export const Route = createFileRoute('/')({ ssr: false, component: Widget }) -`, - 'src/secret.server.ts': secretServer, - 'src/widget.tsx': widget(1, false), -} - /** Pre-bundled up front, as Vite does for an app that installed them. */ const config = { optimizeDeps: { @@ -112,12 +54,6 @@ interface StepOutcome { reported: Array } -const steps = [ - { step: 1, live: false }, - { step: 2, live: true }, - { step: 3, live: false }, -] as const - /** The server and page close after the last test. */ const cleanups: Array<() => Promise> = [] afterAll(async () => { @@ -138,21 +74,21 @@ const run = () => browser: true, config, plugins: [react()], - files: app, + files: pageApp, registerCleanup, }) const browser = await openPage(new URL('/', server.url).href, { registerCleanup, }) const result: Array = [] - for (const { step, live } of steps) { + for (const { step, live } of pageSteps) { let since = { logs: 0, hmr: 0 } if (step > 1) { await server.edit({ 'src/secret.server.ts': null }) - await server.edit({ 'src/secret.server.ts': secretServer }) + await server.edit({ 'src/secret.server.ts': secretServerModule }) await server.idle() since = { logs: server.logs.length, hmr: server.hmr.length } - await server.edit({ 'src/widget.tsx': widget(step, live) }) + await server.edit({ 'src/widget.tsx': pageWidget(step, live) }) } await browser.waitForText(`step-${step}`, { selector: '[data-testid=widget]', @@ -184,7 +120,7 @@ return describeValue(window.liveSecret(), 'MARK_SECRET') return result })()) -describe.each(steps)('step $step (live use: $live)', ({ step, live }) => { +describe.each(pageSteps)('step $step (live use: $live)', ({ step, live }) => { const outcome = async () => (await run())[step - 1]! test( diff --git a/packages/start-plugin-core/tests/integration/importProtection/v2-edits.test.ts b/packages/start-plugin-core/tests/integration/importProtection/v2-edits.test.ts index ea79aa4419..bac2ab3e17 100644 --- a/packages/start-plugin-core/tests/integration/importProtection/v2-edits.test.ts +++ b/packages/start-plugin-core/tests/integration/importProtection/v2-edits.test.ts @@ -232,6 +232,15 @@ describe('vite dev', () => { 'src/secret.server.ts': secretServer(index), 'src/widget.client.ts': widgetClient(index), }) + // The recreated state, loaded in both environments before the + // step's edit: the handling of the recreations (the SSR runner's + // reload, the transforms it starts) ends here, by the loads' + // completion, not by a timer, so the logs from `since` on are the + // step's edit alone. + await evaluateServed(server, '/src/router.ts', { + stubs: servedStartRuntime, + }) + await server.import('/src/router.ts', 'ssr') await server.idle() // The logs of the step: from its edit on since = server.logs.length @@ -273,7 +282,12 @@ describe('vite dev', () => { // before any request, built from the previous version of the file (its // code frame shows the removed line `export const liveWidget = () => // widget()`). With the default `log: 'once'` the dedupe hides it. The - // client twin (step 2 of `src/client-side.ts`) logs nothing. + // client twin (step 2 of `src/client-side.ts`) logs nothing. Traced + // (W3-harness2): logged ~35 ms into the edit's handling, inside + // `edit()`'s settle, from `processPendingViolations` reached through + // `resolveId` while the Start compiler resolves `./widget.client` in + // the SSR transform of the edited file (the SSR runner's reload), with + // the location of the previous version. // Impact: after a fix, the dev server reports the violation the fix // removed, as if it were still there (SPEC J6.13: no stale report). // Source: FIX-PLAN V2-14. @@ -299,24 +313,21 @@ describe('rsbuild dev', () => { const outcomes: Array = [] for (const [index, step] of steps.entries()) { if (index > 0) { - // Known upstream flake (FOLLOWUPS "Rspack loses a file removal - // that lands while a compile runs"): a removal that lands while - // the watcher is paused for a compile is never reported, and the - // first removal starts a compile at once. Not worked around here. - await server.edit({ - 'src/secret.server.ts': null, - 'src/widget.client.ts': null, - }) - // Recreated with the step's edit (W3-ip-v2): recreated on their - // own, under load the second file was never compiled (very likely - // the same mechanism: a change landing while the watcher is paused, - // with an mtime before the compile's start); the edited importers - // resolve them again. - await server.edit({ - 'src/secret.server.ts': secretServer(index), - 'src/widget.client.ts': widgetClient(index), - ...stepEdits(step.live), - }) + // Each deletion and each recreation in its own edit, settled before + // the next write: a removal (or a write) landing while Rspack + // compiles the previous one can be lost (FOLLOWUPS "UPSTREAM + // (W3-harness2)": watchpack 2.5.2 vendored by Rspack, fixed in + // 2.6.0). Merge the deletions, then the recreations, back into one + // edit each once Rspack bundles watchpack >= 2.6. + await server.edit({ 'src/secret.server.ts': null }) + await server.settle() + await server.edit({ 'src/widget.client.ts': null }) + await server.settle() + await server.edit({ 'src/secret.server.ts': secretServer(index) }) + await server.settle() + await server.edit({ 'src/widget.client.ts': widgetClient(index) }) + await server.settle() + await server.edit(stepEdits(step.live)) } const values = (ran: { result: unknown } | { error: string }) => { expect(ran).toEqual({ result: expect.anything() }) diff --git a/packages/start-plugin-core/tests/integration/importProtection/v2-hosts.ts b/packages/start-plugin-core/tests/integration/importProtection/v2-hosts.ts index 64b708cb02..d91bb88077 100644 --- a/packages/start-plugin-core/tests/integration/importProtection/v2-hosts.ts +++ b/packages/start-plugin-core/tests/integration/importProtection/v2-hosts.ts @@ -7,10 +7,83 @@ import { createRequire } from 'node:module' import path from 'node:path' import vm from 'node:vm' +import { startServerEntryFiles } from '../../dev-server' import { reportedViolations } from '../../importProtection/start-apps' import type { ReportOutput } from '../../importProtection/violation-report' import type { RsbuildDevServer } from '@tanstack/compiler-test-utils/rsbuild-dev-server' +// --------------------------------------------------------------------------- +// The V2-14 page app (v2-edits-page.test.ts on Vite, v2-edits-page-rsbuild +// .test.ts on Rsbuild): a Start app a browser opens (Start's default server +// and client entries, the real router over the generated route tree) whose +// index route renders `Widget` on the client only (`ssr: false`). + +export const secretServerModule = `export const secret = () => 'MARK_SECRET'\n` + +/** + * `src/widget.tsx` at `step`; `live`: also uses the denied import live + * (and gives it to the page, `window.liveSecret`). + */ +export const pageWidget = ( + step: number, + live: boolean, +) => `import { createIsomorphicFn } from '@tanstack/react-start' +import { secret } from './secret.server' +const read = createIsomorphicFn() + .server(() => secret()) + .client(() => 'MARK_CLIENT_BRANCH') +export function Widget() { +${ + live + ? ` ;(window as unknown as Record).liveSecret = secret + return

{read() + ' ' + String(secret()) + ' step-${step}'}

` + : ` return

{read() + ' step-${step}'}

` +} +} +` + +export const pageApp = { + ...startServerEntryFiles, + 'harness/client-entry.ts': `import { createElement } from 'react' +import { hydrateRoot } from 'react-dom/client' +import { StartClient } from '@tanstack/react-start/client' +hydrateRoot(document, createElement(StartClient)) +`, + 'src/router.ts': `import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export const getRouter = () => createRouter({ routeTree }) +`, + 'src/routes/__root.tsx': `import { HeadContent, Outlet, Scripts, createRootRoute } from '@tanstack/react-router' +export const Route = createRootRoute({ component: Root }) +function Root() { + return ( + + + + + +
+ + + + ) +} +`, + 'src/routes/index.tsx': `import { createFileRoute } from '@tanstack/react-router' +import { Widget } from '../widget' +export const Route = createFileRoute('/')({ ssr: false, component: Widget }) +`, + 'src/secret.server.ts': secretServerModule, + 'src/widget.tsx': pageWidget(1, false), +} + +/** The steps of the page: allowed, denied (live use), allowed again. */ +export const pageSteps = [ + { step: 1, live: false }, + { step: 2, live: true }, + { step: 3, live: false }, +] as const + /** * The importers of the violations reported for `environment` (`client` or * `server`) in `output` (text, log entries, or an Rsbuild dev server's diff --git a/packages/start-plugin-core/tests/integration/rsbuild/dev-server.test.ts b/packages/start-plugin-core/tests/integration/rsbuild/dev-server.test.ts index 5287c3d542..1217c4bb01 100644 --- a/packages/start-plugin-core/tests/integration/rsbuild/dev-server.test.ts +++ b/packages/start-plugin-core/tests/integration/rsbuild/dev-server.test.ts @@ -264,10 +264,12 @@ export const ${name} = createServerFn().handler(async () => 'MARK_${name}') 'src/entry.ts': `export { a } from './a'\nexport { b } from './b'\n`, }, }) - await server.edit({ - 'src/b.ts': null, - 'src/entry.ts': `export { a } from './a'\n`, - }) + // The deletion in its own edit, before the entry's: a write landing + // while Rspack compiles the deletion can be lost (FOLLOWUPS "UPSTREAM + // (W3-harness2)": watchpack 2.5.2 vendored by Rspack). Merge the two + // edits back once Rspack bundles watchpack >= 2.6. + await server.edit({ 'src/b.ts': null }) + await server.edit({ 'src/entry.ts': `export { a } from './a'\n` }) expect(server.errors).toEqual([]) const ssr = Object.values(await server.outputs('ssr')).join('\n') expect(ssr).toContain('MARK_a')