Unverified Commit 672b02b2 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[next-playwright] Use unique cookie values for instant navigation testing lock (#91250)

Co-authored-by: 's avatarCursor Agent <cursoragent@cursor.com>
parent 63dff61b
...@@ -12,6 +12,6 @@ ...@@ -12,6 +12,6 @@
"devDependencies": { "devDependencies": {
"rimraf": "6.0.1", "rimraf": "6.0.1",
"next": "workspace:*", "next": "workspace:*",
"playwright": "^1.40.0" "playwright": "1.58.2"
} }
} }
...@@ -255,8 +255,8 @@ ...@@ -255,8 +255,8 @@
"octokit": "3.1.0", "octokit": "3.1.0",
"outdent": "0.8.0", "outdent": "0.8.0",
"pixrem": "5.0.0", "pixrem": "5.0.0",
"playwright": "1.48.0", "playwright": "1.58.2",
"playwright-chromium": "1.48.0", "playwright-chromium": "1.58.2",
"postcss": "8.4.31", "postcss": "8.4.31",
"postcss-nested": "4.2.1", "postcss-nested": "4.2.1",
"postcss-pseudoelements": "5.0.0", "postcss-pseudoelements": "5.0.0",
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
} }
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "1.58.2",
"typescript": "5.9.2" "typescript": "5.9.2"
} }
} }
...@@ -74,11 +74,14 @@ export async function instant<T>( ...@@ -74,11 +74,14 @@ export async function instant<T>(
// navigation-testing-lock.ts, which acquires the in-memory navigation lock. // navigation-testing-lock.ts, which acquires the in-memory navigation lock.
const { hostname } = new URL(resolveURL(page, options)) const { hostname } = new URL(resolveURL(page, options))
await step('Acquire Instant Lock', () => await step('Acquire Instant Lock', () =>
page page.context().addCookies([
.context() {
.addCookies([ name: INSTANT_COOKIE,
{ name: INSTANT_COOKIE, value: '[0]', domain: hostname, path: '/' }, value: JSON.stringify([0, `p${Math.random()}`]),
]) domain: hostname,
path: '/',
},
])
) )
try { try {
return await fn() return await fn()
......
...@@ -167,7 +167,7 @@ ...@@ -167,7 +167,7 @@
"@next/react-refresh-utils": "16.2.0-canary.100", "@next/react-refresh-utils": "16.2.0-canary.100",
"@next/swc": "16.2.0-canary.100", "@next/swc": "16.2.0-canary.100",
"@opentelemetry/api": "1.6.0", "@opentelemetry/api": "1.6.0",
"@playwright/test": "1.51.1", "@playwright/test": "1.58.2",
"@rspack/core": "1.6.7", "@rspack/core": "1.6.7",
"@storybook/addon-a11y": "8.6.0", "@storybook/addon-a11y": "8.6.0",
"@storybook/addon-essentials": "8.6.0", "@storybook/addon-essentials": "8.6.0",
......
...@@ -5,11 +5,6 @@ ...@@ -5,11 +5,6 @@
* during instant navigation captures, and owns all cookie state * during instant navigation captures, and owns all cookie state
* transitions (pending → captured-MPA, pending → captured-SPA). * transitions (pending → captured-MPA, pending → captured-SPA).
* *
* The cookie value is a JSON array:
* [0] — pending (waiting to capture)
* [1, null] — captured MPA page load
* [1, { from, to }] — captured SPA navigation (from/to route trees)
*
* External actors (Playwright, devtools) set [0] to start a lock scope * External actors (Playwright, devtools) set [0] to start a lock scope
* and delete the cookie to end one. Next.js writes captured values. * and delete the cookie to end one. Next.js writes captured values.
* The CookieStore handler distinguishes them by value: pending = external, * The CookieStore handler distinguishes them by value: pending = external,
...@@ -22,17 +17,30 @@ import { refreshOnInstantNavigationUnlock } from '../use-action-queue' ...@@ -22,17 +17,30 @@ import { refreshOnInstantNavigationUnlock } from '../use-action-queue'
type InstantNavCookieState = 'pending' | 'mpa' | 'spa' type InstantNavCookieState = 'pending' | 'mpa' | 'spa'
type InstantCookie =
// pending (waiting to capture)
| [captured: 0, id: string]
// captured MPA page load
| [captured: 1, id: string, state: null]
// captured SPA navigation (from/to route trees)
| [
captured: 1,
id: string,
state: { from: FlightRouterState; to: FlightRouterState | null },
]
function parseCookieValue(raw: string): InstantNavCookieState { function parseCookieValue(raw: string): InstantNavCookieState {
try { try {
const parsed = JSON.parse(raw) const parsed = JSON.parse(raw)
if (Array.isArray(parsed) && parsed.length >= 2) { if (Array.isArray(parsed) && parsed.length >= 3) {
return parsed[1] === null ? 'mpa' : 'spa' const rawState = parsed[2]
return rawState === null ? 'mpa' : 'spa'
} }
} catch {} } catch {}
return 'pending' return 'pending'
} }
function writeCookieValue(value: unknown[]): void { function writeCookieValue(value: InstantCookie): void {
if (typeof cookieStore === 'undefined') { if (typeof cookieStore === 'undefined') {
return return
} }
...@@ -101,7 +109,7 @@ export function startListeningForInstantNavigationCookie(): void { ...@@ -101,7 +109,7 @@ export function startListeningForInstantNavigationCookie(): void {
}) })
} }
writeCookieValue([1, null]) writeCookieValue([1, `c${Math.random()}`, null])
acquireLock() acquireLock()
} }
...@@ -151,7 +159,7 @@ export function transitionToCapturedSPA( ...@@ -151,7 +159,7 @@ export function transitionToCapturedSPA(
toTree: FlightRouterState | null toTree: FlightRouterState | null
): void { ): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) { if (process.env.__NEXT_EXPOSE_TESTING_API) {
writeCookieValue([1, { from: fromTree, to: toTree }]) writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])
} }
} }
...@@ -164,7 +172,7 @@ export function updateCapturedSPAToTree( ...@@ -164,7 +172,7 @@ export function updateCapturedSPAToTree(
toTree: FlightRouterState toTree: FlightRouterState
): void { ): void {
if (process.env.__NEXT_EXPOSE_TESTING_API) { if (process.env.__NEXT_EXPOSE_TESTING_API) {
writeCookieValue([1, { from: fromTree, to: toTree }]) writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])
} }
} }
......
...@@ -30,14 +30,15 @@ export type InstantNavCookieData = ...@@ -30,14 +30,15 @@ export type InstantNavCookieData =
function parseCookieValue(raw: string): InstantNavCookieData { function parseCookieValue(raw: string): InstantNavCookieData {
try { try {
const parsed = JSON.parse(raw) const parsed = JSON.parse(raw)
if (Array.isArray(parsed) && parsed.length >= 2) { if (Array.isArray(parsed) && parsed.length >= 3) {
if (parsed[1] === null) { const rawState = parsed[2]
if (rawState === null) {
return { state: 'mpa' } return { state: 'mpa' }
} }
// SPA capture: parsed[1] is { from, to } // SPA capture: rawState is { from, to }
if (typeof parsed[1] === 'object' && parsed[1] !== null) { if (typeof rawState === 'object' && rawState !== null) {
const fromTree: FlightRouterState = parsed[1].from ?? ['', {}] const fromTree: FlightRouterState = rawState.from ?? ['', {}]
const toTree: FlightRouterState | null = parsed[1].to ?? null const toTree: FlightRouterState | null = rawState.to ?? null
return { state: 'spa', fromTree, toTree } return { state: 'spa', fromTree, toTree }
} }
return { state: 'spa', fromTree: ['', {}], toTree: null } return { state: 'spa', fromTree: ['', {}], toTree: null }
......
...@@ -44,7 +44,7 @@ export function InstantNavsPanel() { ...@@ -44,7 +44,7 @@ export function InstantNavsPanel() {
if (typeof cookieStore !== 'undefined') { if (typeof cookieStore !== 'undefined') {
cookieStore.set({ cookieStore.set({
name: COOKIE_NAME, name: COOKIE_NAME,
value: '[0]', value: JSON.stringify([0, `p${Math.random()}`]),
path: '/', path: '/',
}) })
} }
...@@ -55,7 +55,7 @@ export function InstantNavsPanel() { ...@@ -55,7 +55,7 @@ export function InstantNavsPanel() {
if (typeof cookieStore !== 'undefined') { if (typeof cookieStore !== 'undefined') {
cookieStore.set({ cookieStore.set({
name: COOKIE_NAME, name: COOKIE_NAME,
value: '[0]', value: JSON.stringify([0, `p${Math.random()}`]),
path: '/', path: '/',
}) })
} }
......
This diff is collapsed.
...@@ -116,7 +116,8 @@ describe.each([['', '/docs']])( ...@@ -116,7 +116,8 @@ describe.each([['', '/docs']])(
const script = document.createElement('script') const script = document.createElement('script')
script.src = "${next.url}/_next/static/chunks/pages/_app.js" script.src = "${next.url}/_next/static/chunks/pages/_app.js"
script.onerror = (err) => { script.onerror = (error) => {
console.error('script error', error)
statusEl.innerText = 'error' statusEl.innerText = 'error'
} }
script.onload = () => { script.onload = () => {
...@@ -126,7 +127,13 @@ describe.each([['', '/docs']])( ...@@ -126,7 +127,13 @@ describe.each([['', '/docs']])(
})()` })()`
// ensure direct port with mismatching port is blocked // ensure direct port with mismatching port is blocked
const browser = await webdriver(`http://127.0.0.1:${port}`, '/about') const browser = await webdriver(
`http://127.0.0.1:${port}`,
'/about',
{
permissions: ['local-network-access'],
}
)
await browser.eval(scriptSnippet) await browser.eval(scriptSnippet)
await retry(async () => { await retry(async () => {
...@@ -136,6 +143,7 @@ describe.each([['', '/docs']])( ...@@ -136,6 +143,7 @@ describe.each([['', '/docs']])(
}) })
// ensure different host is blocked // ensure different host is blocked
// Requires local-network-access permission to send a request to next.url
await browser.get(`https://example.vercel.sh/`) await browser.get(`https://example.vercel.sh/`)
await browser.eval(scriptSnippet) await browser.eval(scriptSnippet)
...@@ -145,7 +153,11 @@ describe.each([['', '/docs']])( ...@@ -145,7 +153,11 @@ describe.each([['', '/docs']])(
) )
}) })
expect(next.cliOutput).toContain('Cross origin request detected from') expect(next.cliOutput).toContain(
// We're not sending an Origin header
// TODO: redundant spacing
'Cross origin request detected to'
)
} finally { } finally {
server.close() server.close()
} }
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('use-router-with-rewrites', () => { describe('use-router-with-rewrites', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -68,30 +69,33 @@ describe('use-router-with-rewrites', () => { ...@@ -68,30 +69,33 @@ describe('use-router-with-rewrites', () => {
const browser = await next.browser('/rewrite-to-same-segment/0') const browser = await next.browser('/rewrite-to-same-segment/0')
await browser.elementById('router-push').click() await browser.elementById('router-push').click()
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('1')
})
const url = new URL(await browser.url()) const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/rewrite-to-same-segment/1') expect(url.pathname + url.search).toBe('/rewrite-to-same-segment/1')
expect(await browser.elementByCss('p').text()).toBe('1')
}) })
it('should preserve current pathname when using useRouter.replace with rewrites on dynamic route', async () => { it('should preserve current pathname when using useRouter.replace with rewrites on dynamic route', async () => {
const browser = await next.browser('/rewrite-to-same-segment/0') const browser = await next.browser('/rewrite-to-same-segment/0')
await browser.elementById('router-replace').click() await browser.elementById('router-replace').click()
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('2')
})
const url = new URL(await browser.url()) const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/rewrite-to-same-segment/2') expect(url.pathname + url.search).toBe('/rewrite-to-same-segment/2')
expect(await browser.elementByCss('p').text()).toBe('2')
}) })
it('should preserve current pathname when using Link with rewrites on dynamic route', async () => { it('should preserve current pathname when using Link with rewrites on dynamic route', async () => {
const browser = await next.browser('/rewrite-to-same-segment/0') const browser = await next.browser('/rewrite-to-same-segment/0')
await browser.elementByCss('a').click() await browser.elementByCss('a').click()
await retry(async () => {
expect(await browser.elementByCss('p').text()).toBe('3')
})
const url = new URL(await browser.url()) const url = new URL(await browser.url())
expect(url.pathname + url.search).toBe('/rewrite-to-same-segment/3') expect(url.pathname + url.search).toBe('/rewrite-to-same-segment/3')
expect(await browser.elementByCss('p').text()).toBe('3')
}) })
}) })
}) })
...@@ -17,6 +17,7 @@ import { ...@@ -17,6 +17,7 @@ import {
check, check,
getRedboxHeader, getRedboxHeader,
normalizeManifest, normalizeManifest,
retry,
} from 'next-test-utils' } from 'next-test-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
...@@ -245,11 +246,12 @@ function runTests({ dev }) { ...@@ -245,11 +246,12 @@ function runTests({ dev }) {
await browser.eval('window.beforeNav = 1') await browser.eval('window.beforeNav = 1')
await browser.elementByCss(`#${id}`).click() await browser.elementByCss(`#${id}`).click()
await check(() => browser.eval('window.location.pathname'), pathname)
expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual( await retry(async () => {
navQuery expect(JSON.parse(await browser.elementByCss('#query').text())).toEqual(
) navQuery
)
})
expect(await browser.eval('window.location.pathname')).toBe(pathname) expect(await browser.eval('window.location.pathname')).toBe(pathname)
expect(await browser.eval('window.location.hash')).toBe(hash) expect(await browser.eval('window.location.hash')).toBe(hash)
expect( expect(
......
...@@ -12,6 +12,7 @@ import { ...@@ -12,6 +12,7 @@ import {
Locator, Locator,
Request as PlaywrightRequest, Request as PlaywrightRequest,
Response as PlaywrightResponse, Response as PlaywrightResponse,
BrowserContextOptions,
} from 'playwright' } from 'playwright'
import path from 'path' import path from 'path'
...@@ -19,10 +20,13 @@ type EventType = 'request' | 'response' ...@@ -19,10 +20,13 @@ type EventType = 'request' | 'response'
type PageLog = { source: string; message: string; args: unknown[] } type PageLog = { source: string; message: string; args: unknown[] }
export type Permissions = BrowserContextOptions['permissions']
let page: Page let page: Page
let browser: Browser | undefined let browser: Browser | undefined
let context: BrowserContext | undefined let context: BrowserContext | undefined
let contextHasJSEnabled: boolean = true let contextHasJSEnabled: boolean = true
let contextPermissions: Permissions = undefined
let pageLogs: Array<Promise<PageLog> | PageLog> = [] let pageLogs: Array<Promise<PageLog> | PageLog> = []
let websocketFrames: Array<{ payload: string | Buffer }> = [] let websocketFrames: Array<{ payload: string | Buffer }> = []
...@@ -167,7 +171,8 @@ export class Playwright<TCurrent = undefined> { ...@@ -167,7 +171,8 @@ export class Playwright<TCurrent = undefined> {
javaScriptEnabled: boolean, javaScriptEnabled: boolean,
ignoreHTTPSErrors: boolean, ignoreHTTPSErrors: boolean,
headless: boolean, headless: boolean,
userAgent: string | undefined userAgent: string | undefined,
permissions: Permissions
) { ) {
let device let device
...@@ -182,7 +187,13 @@ export class Playwright<TCurrent = undefined> { ...@@ -182,7 +187,13 @@ export class Playwright<TCurrent = undefined> {
} }
if (browser) { if (browser) {
if (contextHasJSEnabled !== javaScriptEnabled) { if (
contextHasJSEnabled !== javaScriptEnabled ||
// Even triggers on same set of permissions, but we don't want to deal
// with the complexity of diffing them, so we just always recreate the
// context when permissions are set.
contextPermissions !== permissions
) {
// If we have switched from having JS enable/disabled we need to recreate the context. // If we have switched from having JS enable/disabled we need to recreate the context.
await teardown(this.teardownTracing.bind(this)) await teardown(this.teardownTracing.bind(this))
await context?.close() await context?.close()
...@@ -192,8 +203,10 @@ export class Playwright<TCurrent = undefined> { ...@@ -192,8 +203,10 @@ export class Playwright<TCurrent = undefined> {
ignoreHTTPSErrors, ignoreHTTPSErrors,
...(userAgent ? { userAgent } : {}), ...(userAgent ? { userAgent } : {}),
...device, ...device,
permissions,
}) })
contextHasJSEnabled = javaScriptEnabled contextHasJSEnabled = javaScriptEnabled
contextPermissions = permissions
} }
return return
} }
...@@ -205,6 +218,7 @@ export class Playwright<TCurrent = undefined> { ...@@ -205,6 +218,7 @@ export class Playwright<TCurrent = undefined> {
ignoreHTTPSErrors, ignoreHTTPSErrors,
...(userAgent ? { userAgent } : {}), ...(userAgent ? { userAgent } : {}),
...device, ...device,
permissions,
}) })
contextHasJSEnabled = javaScriptEnabled contextHasJSEnabled = javaScriptEnabled
} }
...@@ -214,14 +228,16 @@ export class Playwright<TCurrent = undefined> { ...@@ -214,14 +228,16 @@ export class Playwright<TCurrent = undefined> {
await page?.close() await page?.close()
} }
async launchBrowser(browserName: string, launchOptions: Record<string, any>) { async launchBrowser(
browserName: string,
launchOptions: { headless: boolean }
) {
if (browserName === 'safari') { if (browserName === 'safari') {
return await webkit.launch(launchOptions) return await webkit.launch(launchOptions)
} else if (browserName === 'firefox') { } else if (browserName === 'firefox') {
return await firefox.launch({ return await firefox.launch({
...launchOptions, ...launchOptions,
firefoxUserPrefs: { firefoxUserPrefs: {
...launchOptions.firefoxUserPrefs,
// The "fission.webContentIsolationStrategy" pref must be // The "fission.webContentIsolationStrategy" pref must be
// set to 1 on Firefox due to the bug where a new history // set to 1 on Firefox due to the bug where a new history
// state is pushed on a page reload. // state is pushed on a page reload.
...@@ -231,9 +247,13 @@ export class Playwright<TCurrent = undefined> { ...@@ -231,9 +247,13 @@ export class Playwright<TCurrent = undefined> {
}, },
}) })
} else { } else {
let launchArgs: string[] = []
if (!launchOptions.headless) {
launchArgs.push('--auto-open-devtools-for-tabs')
}
return await chromium.launch({ return await chromium.launch({
devtools: !launchOptions.headless,
...launchOptions, ...launchOptions,
args: launchArgs,
ignoreDefaultArgs: ['--disable-back-forward-cache'], ignoreDefaultArgs: ['--disable-back-forward-cache'],
}) })
} }
......
import { debugPrint, getFullUrl } from 'next-test-utils' import { debugPrint, getFullUrl } from 'next-test-utils'
import os from 'os' import os from 'os'
import { import {
Permissions,
Playwright, Playwright,
PlaywrightNavigationWaitUntil, PlaywrightNavigationWaitUntil,
} from './browsers/playwright' } from './browsers/playwright'
...@@ -48,6 +49,7 @@ if (typeof afterAll === 'function') { ...@@ -48,6 +49,7 @@ if (typeof afterAll === 'function') {
} }
export interface WebdriverOptions { export interface WebdriverOptions {
permissions?: Permissions
/** /**
* whether to wait for React hydration to finish * whether to wait for React hydration to finish
*/ */
...@@ -121,6 +123,7 @@ export default async function webdriver( ...@@ -121,6 +123,7 @@ export default async function webdriver(
extraHTTPHeaders, extraHTTPHeaders,
locale, locale,
disableJavaScript, disableJavaScript,
permissions,
ignoreHTTPSErrors, ignoreHTTPSErrors,
headless, headless,
cpuThrottleRate, cpuThrottleRate,
...@@ -141,7 +144,8 @@ export default async function webdriver( ...@@ -141,7 +144,8 @@ export default async function webdriver(
Boolean(ignoreHTTPSErrors), Boolean(ignoreHTTPSErrors),
// allow headless to be overwritten for a particular test // allow headless to be overwritten for a particular test
typeof headless !== 'undefined' ? headless : !!process.env.HEADLESS, typeof headless !== 'undefined' ? headless : !!process.env.HEADLESS,
userAgent userAgent,
permissions
) )
;(global as any).browserName = browserName ;(global as any).browserName = browserName
......
...@@ -48,7 +48,7 @@ ...@@ -48,7 +48,7 @@
"minimist": "^1.2.8", "minimist": "^1.2.8",
"picocolors": "1.0.1", "picocolors": "1.0.1",
"pidusage-tree": "^2.0.5", "pidusage-tree": "^2.0.5",
"playwright-chromium": "1.48.0", "playwright-chromium": "1.58.2",
"split2": "^4.2.0", "split2": "^4.2.0",
"tree-kill": "^1.2.2" "tree-kill": "^1.2.2"
} }
......
...@@ -348,7 +348,7 @@ export async function newBrowserSession(options: { ...@@ -348,7 +348,7 @@ export async function newBrowserSession(options: {
}): Promise<BrowserSession> { }): Promise<BrowserSession> {
const browser = await chromium.launch({ const browser = await chromium.launch({
headless: options.headless ?? process.env.HEADLESS !== 'false', headless: options.headless ?? process.env.HEADLESS !== 'false',
devtools: true, args: options.headless ? undefined : ['--auto-open-devtools-for-tabs'],
timeout: 60000, timeout: 60000,
}) })
const context = await browser.newContext({ const context = await browser.newContext({
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment