Commit Graph

1420 Commits

Author SHA1 Message Date
James Anderson 78bb36a656 fix(app-router): preserve dynamic interception source routes (#2042) 2026-06-15 23:06:50 +01:00
James Anderson 76de660c20 fix(image): emit static imports as managed assets (#2040)
* fix(image): emit static imports as managed assets

* fix(image): handle static asset rebuilds and caching

* fix(image): scope managed media hash etags

* test(image): escape all URL ampersands
2026-06-15 23:04:40 +01:00
James Anderson b58adb3cfa fix(middleware): classify Pages data requests by URL (#2039) 2026-06-15 23:00:09 +01:00
James Anderson 48f4df28cb fix(pages-router): cancel deduped GSSP data waits (#2038) 2026-06-15 22:58:02 +01:00
James Anderson 0fb9bd32bf fix(pages): apply Document renderPage enhancers (#2034)
* fix(pages): apply document renderPage enhancers

* fix(pages): propagate document render errors

* fix(pages): delegate document initial props

* fix(pages): render dev errors through document

* fix(pages): preserve document-provided html

* fix(pages): keep render page enhancer type internal

* fix(pages): buffer custom dev error documents
2026-06-15 22:53:40 +01:00
James Anderson 68414e68a5 fix(router): re-enter filesystem routes after rewrites (#2032)
* fix(router): re-enter static files after i18n rewrites

* fix(router): re-enter filesystem routes for all rewrites
2026-06-15 22:50:57 +01:00
James Anderson b91d5d1396 fix(pages): interpolate same-segment rewrite params (#2030)
* fix(pages): interpolate same-segment rewrite params

* test(pages): fix same-segment navigation CI
2026-06-15 21:49:28 +00:00
James Anderson c3dcdba1fe fix(pages): honor basePath in dev module loaders (#2033)
* fix(pages): honor basePath in dev module loaders

* fix(pages): preserve basePath in ISR loaders

* style(pages): format dev module loader changes

* fix(pages): preserve dynamic route module paths

* test(pages): run basePath dev coverage in CI
2026-06-15 22:42:33 +01:00
James Anderson 9958567949 fix(pages): route hybrid form data requests (#2029) 2026-06-15 22:37:31 +01:00
James Anderson 866c71809e fix(pages): preserve rewritten URLs during navigation (#2028)
* fix(router): preserve rewritten pages query navigation

* fix(router): align pages url object locale handling

* fix(router): preserve raw pages url search

* fix(router): escape fragments in raw pages search

* fix(router): preserve localized rewritten pages urls

* test(router): fix pages navigation CI failures

* fix(router): preserve Next search fragment formatting
2026-06-15 22:34:36 +01:00
James Anderson 8b5390504e fix(actions): return body-limit errors without closing responses (#2026)
* fix(actions): preserve overflow error responses

* fix(actions): backpressure body overflow handling

* fix(server): own Node request stream chunks

* fix(server): preserve cloned request bodies
2026-06-15 21:56:55 +01:00
James Anderson 5146b1f47b fix(router): render slots beside grouped children (#2022) 2026-06-15 21:52:28 +01:00
James Anderson fc8e6f0e86 fix(app-router): settle superseded link navigations (#2025) 2026-06-15 21:51:56 +01:00
MaxtuneLee b67a8ddd1e fix(prerender): deduplicate generateStaticParams entries (#2031)
* fix(prerender): deduplicate generateStaticParams entries to prevent duplicate routes in prerendering

* docs(prerender): simplify deduplication comment for generateStaticParams entries
2026-06-15 10:55:03 +01:00
github-actions[bot] 5310d14170 chore: version packages (#1940)
* chore: version packages

* Apply suggestion from @james-elicx

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: James Anderson <james@eli.cx>
@vinext/cloudflare@0.1.2 vinext@0.1.3
2026-06-15 09:54:40 +00:00
James Anderson 62db98056c fix(image): allow any quality 1-100 when images.qualities is unset (#2023)
* fix(image): allow any quality 1-100 when images.qualities is unset

The image optimization endpoint returned 400 for any quality other than
75 (e.g. `<Image quality={90}>`) because vinext defaulted the allowed
quality list to `[75]` whenever `images.qualities` was not configured.

Next.js only enforces a quality allowlist when `images.qualities` is set;
when unset it permits any integer quality from 1-100. This aligns vinext
with that behaviour: `parseImageParams`/`resolveDevImageRedirect` now take
an optional allowlist and only restrict quality when one is provided, and
the build/runtime plumbing emits `null` (not `[75]`) when unset so the
"allow all" semantics survive into the deploy worker.

Repro: GET /_next/image?url=%2Fshop%2Ftablet.png&w=750&q=90 -> 400.

Fixes the app-router-playground image optimization failure.

* test(image): update App Router blur-exception tests for quality parity

With `images.qualities` unset, any quality 1-100 is now permitted (Next.js
parity), so q=70 is a normal quality rather than a rejected one. Pin the
blur-quality-exception tests to `qualities: [75]` so they still exercise the
dev-only exception, and add a case asserting q=70 is allowed in production
when qualities is unset.
2026-06-15 10:43:20 +01:00
Nathan Nguyen a3d2f92152 fix(router): honor hybrid pages route priority (#1997)
* fix(router): honor hybrid pages route priority

* fix(router): share hybrid owner decision with client navigation

PR #1997 fixed the server-side route ownership for direct document loads,
but the same invariant broke for client-side soft navigations and the
matching prefetch path:

- navigateClientSide() always delegated to the App runtime's RSC fetch,
  even when the Pages route had higher priority. renderPagesFallback()
  short-circuits RSC requests with null, so the App catch-all won.
- prefetchUrl() prefetched an RSC stream for any URL that matched an App
  route, again ignoring Pages ownership.
- The Pages entry was loaded on every hybrid request, even when a static
  App route had already matched (Pages can never win in that case).

Expose the Pages route manifest on the client via a new
__VINEXT_PAGES_LINK_PREFETCH_ROUTES__ window global emitted by both the
App and Pages browser entries. The link shim consults a shared
resolveHybridClientRouteOwner helper that mirrors the server-side
pagesRouteHasPriorityOverAppRoute comparison. When Pages owns the URL,
the click handler issues a window.location navigation and the prefetch
path returns early.

Gate the renderPagesFallback call behind a static-App-route check in
handleAppRscRequest: when a static App route matches, the bridge
cannot win, so skip the eager Pages entry load. Centralise the
comparison in a new resolveHybridRouteOwner helper so server and
client reach the same answer for the same (URL, route pair).

Adds the missing client-navigation coverage to the use-params e2e
fixture (Link from /app/ to /pages-dir/foobar) and unit tests for
the shared owner decision.

* fix(router): mirror server hybrid owner decision on the client

PR review flagged two split-brain bugs in the previous hybrid
ownership fix: a hand-copied client comparator and a Link-only
ownership gate that left programmatic App Router navigations on
the wrong path.

The hand-copied routePrecedence in hybrid-client-route-owner.ts
omitted the static-prefix reduction that lives in
routing/utils.ts#routePrecedence, and used a strict-less-than
comparison that returned App for identical dynamic patterns. The
server returns Pages for both cases (Pages providers sort ahead
of App providers, and routePrecedence subtracts 50 per static
prefix segment). The split produced a real ownership disagreement
on overlapping patterns like /_sites/:slug* (Pages) vs /:slug*
(App).

Add a shared compareHybridRoutePatterns to routing/utils.ts as
the single source of truth: the static/dynamic short-circuits plus
a sortRoutes call (which carries the static-prefix reduction and
the Pages-first equal-pattern tiebreak). The server
pagesRouteHasPriorityOverAppRoute and the client
resolveHybridClientRouteOwner both delegate to it, so they
cannot diverge. Drop the hand-copied routePrecedence entirely.

Wire the ownership check at the App navigation runtime boundary
so useRouter().push, useRouter().replace, gesturePush, and form
submits all get the same hard-nav contract as the Link click
handler. Specifically:

- navigateClientSide: after same-origin normalization, if Pages
  owns the URL, hard-navigate via window.location and return
  (matching the existing external-URL branch).
- _appRouter.prefetch: short-circuit RSC URL construction for
  Pages-owned targets so we do not warm an unusable cache entry.

Centralise the existing two inline hard-nav branches in
navigateClientSide into a hardNavigateTo helper for clarity.

Tests:

- Direct unit tests for compareHybridRoutePatterns covering
  identical-dynamic tiebreak, static-prefix dynamic overlap,
  static-prefix catch-all overlap, and infix-static bonus.
- Direct unit tests for resolveHybridClientRouteOwner mirroring
  the server assertions plus a basePath-stripping test.
- e2e: useRouter().push('/pages-dir/foobar') from an App page
  resolves to the Pages document.
- e2e: useRouter().prefetch('/pages-dir/foobar') issues zero
  RSC requests for the target URL.

* docs(router): fix stale score in static-prefix catch-all test comment

The hand-copied comparator note quoted the dynamic-segment scores
(51 / 1000) for the optional-catch-all example (/_sites/:slug*
vs /:slug*). The current optional-catch-all scoring actually
produces 1951 vs 2000. The test assertion was correct; only the
comment was stale.

* test(use-params): fix direct-load single dynamic param to use /a instead of /a/b

* fix(router): compare hybrid routes structurally

* fix(router): reject hybrid route conflicts

* fix(router): refresh hybrid route ownership

* fix(router): preserve hybrid routing lifecycle

* fix(router): recheck pages routes after rewrites

* fix(router): preserve rewritten pages queries

* fix(router): preserve rewritten route ownership

* fix(router): resolve client rewrites sequentially

* fix(router): apply rewrite phases sequentially

* fix(router): preserve rewrite params and endpoints

* fix(router): hand off endpoint navigations

* fix(router): preserve rewrite fragment params

* test(e2e): avoid hybrid fixture route conflicts

* test(pages): await async config validation

* test(hybrid): avoid duplicate page fixtures

* chore(router): clarify hybrid priority semantics

* refactor(router): remove duplicate app route matcher

* docs(router): clarify client hybrid comparator

---------

Co-authored-by: James <james@eli.cx>
2026-06-15 00:22:00 +01:00
Nathan Nguyen 10b5086f4d fix(app-router): align router autoscroll with Next (#2004)
* fix(app-router): align router autoscroll with Next

App Router navigation could diverge from Next.js router autoscroll semantics around hydration timing, loading-shell same-page search navigations, and routes whose first committed node is React-hoisted into head. That broke the upstream router-autoscroll deploy-suite because the client marked hydration too early, static loading-shell templates were not usable for navigation, and the fallback scroll path masked the old-handler hoisted-head behavior.

The fix moves the Next-compatible hydration marker into a passive effect, wires production hydrateRoot error callbacks to match Next's implicit root-boundary and recoverable-error handling, lets authoritative loading-shell templates drive static route optimistic payloads, and skips fallback document scrolling when the committed document only exposes a React-hoisted head resource. The ported tests cover the upstream router-autoscroll behavior plus focused unit boundaries for prefetch mode, optimistic routing, head-resource detection, and hydrateRoot callbacks.

* fix(app-router): hoisted-head scroll fallback is per-intent, not global head scan

* test(app-router): add full-chain scroll intent integration test

* fix(app-router): match legacy scroll focus parity

* fix(app-router): preserve latest scroll navigation intent

* fix(app-router): scope scroll and error recovery

* fix(app-router): gate navigation failure recovery

* fix(app-router): match navigation failure handling

* fix(app-router): align scroll completion parity

* fix(app-router): retain latest failure target

* fix(app-router): preserve route error boundaries

* fix(app-router): clear discarded failure targets

* fix(app-router): align failure recovery boundaries

* fix(app-router): disarm refused recovery targets

* fix(app-router): preserve failure target ownership

* fix(app-router): match boundary recovery parity

---------

Co-authored-by: James <james@eli.cx>
2026-06-14 23:59:28 +01:00
Xplod13 2b67523e9e fix(server): strip HTTP/2 pseudo-headers before building Headers (#2021)
## Summary
- Drop RFC 7540 §8.1.2.1 pseudo-headers (`:method`, `:authority`, `:path`,
  `:scheme`) before constructing WHATWG `Headers` from Node's `req.headers`.
- Fixed at every `Headers`-from-`req.headers` site: the Pages Router
  middleware snapshot (index.ts), the edge API request builder
  (api-handler.ts), and the shared `appendWebHeader` helper used by
  `nodeToWebRequest` (prod-server.ts).
- Also excluded pseudo-headers from the `reportRequestError` header metadata
  in both api-handler.ts and dev-server.ts so error reports reflect real
  request headers only.
- Added a regression unit test driving `nodeToWebRequest` with a fake HTTP/2
  request.

## Root Cause
Over HTTP/2, Node's `http2` server exposes the request pseudo-headers as
`:`-prefixed keys on `req.headers`. The WHATWG `Headers`
constructor/`append`/`set` reject any header name containing `:`
(`TypeError: Headers.set: ":method" is an invalid header name`), so building a
`Headers` object directly from `req.headers` threw and returned a 500 on every
HTTP/2 request. Per RFC 7540 §8.1.2.1, pseudo-headers must not be treated as
regular header fields, so they are stripped at each construction site.

## References
- Issue: cloudflare/vinext#2013
- RFC 7540 §8.1.2.1 (HTTP/2 pseudo-header fields)
- Node `http2` request `:`-prefixed headers; WHATWG Fetch `Headers` name validation

## Verification
- `node -e "new Headers({':method':'GET'})"` → throws (repro).
- `CI=true pnpm test tests/http2-pseudo-headers.test.ts` → red before fix,
  green after.
- `CI=true npx vp check` on all changed files → pass (format + lint + types).

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 23:34:22 +01:00
Nathan Nguyen 1b3a35606e refactor(navigation): drop V0 suffix from planner types (#2008)
The navigation planner's public and internal types were suffixed `V0`
(RouteSnapshotV0, NavigationDecisionV0, FlightResultV0, and 19 others).
The suffix implied a versioning scheme that never materialized — there is
no V1, and the schema-version concerns it hinted at are carried explicitly
elsewhere (NAVIGATION_TRACE_SCHEMA_VERSION, CACHE_PROOF_MODEL_SCHEMA_VERSION).
The bare suffix was pure noise at every call site.

Rename all 22 `…V0` planner types to their unsuffixed names across the
planner, the browser state/entry/action modules, and the planner test
suite. Pure mechanical rename: no behavior change, all 295 planner and
browser-entry tests pass unchanged.
2026-06-14 23:32:10 +01:00
Xplod13 201f4a64dc fix(shims): guard AsyncLocalStorage construction for browser bundles (#2020)
## Summary
- Guard `getOrCreateAls` so it no longer calls `new AsyncLocalStorage()`
  unconditionally; when the runtime does not expose a usable constructor it
  falls back to a no-op store instead of throwing.
- Add a `NoopAsyncLocalStorage` whose `getStore()` returns `undefined`, mirroring
  Next.js' `FakeAsyncLocalStorage` and this repo's `async-hooks-stub.ts`.
- Preserve the cross-bundle singleton behavior (`Symbol.for` + `??=`).

## Root Cause
In browser/client bundles `node:async_hooks` can resolve to a stub without a
usable `AsyncLocalStorage` constructor (e.g. Vite's `__vite-browser-external`).
`getOrCreateAls` ran `new AsyncLocalStorage()` at module-eval time, throwing
`TypeError: AsyncLocalStorage is not a constructor`. Because many client-reachable
shims (request-context, headers, cache, …) call this helper on import, the whole
client bundle died and hydration crashed. Checking
`typeof AsyncLocalStorage === "function"` before constructing, with a no-op
fallback, matches Next.js' availability guard.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 23:31:38 +01:00
Xplod13 37e839e2f1 fix(prerender): surface thrown generateStaticParams/getStaticPaths errors (#2017)
The build-time prerender proxies that fetch the static-params (App Router)
and pages-static-paths (Pages Router) endpoints treated every non-ok
response identically: they logged a misleading "stale or missing prerender
secret" warning and returned the no-params sentinel, discarding the response
body. But the endpoint returns 404 for the genuine disabled/secret case and
500 (with the real error in its JSON body) when the user's
generateStaticParams/getStaticPaths throws. Swallowing the 500 silently
dropped the route from prerendering and let the default-mode build "succeed"
while shipping an app missing pre-rendered pages, blaming a non-existent
secret problem.

Branch on status: a 500 throws the real error (parsed from the body). App
Router's existing per-route collector turns it into a "Failed to call
generateStaticParams(): ..." error; the Pages Router getStaticPaths call is
now wrapped to produce the same per-route error instead of crashing. Non-500
responses keep the warn-and-skip path, so the legitimate secret/disabled case
is unchanged. This matches Next.js, which fails the build with the real error.

Fixes #1982

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 23:28:37 +01:00
Nathan Nguyen 47b38a91f3 fix(app-router): recover SSR shell render errors via __next_error__ document (#1908)
* fix(plugin): resolve vinext/shims/* package subpaths to local shim files

Runtime helper modules embedded into generated entries import vinext's
own shims by package subpath (e.g. `vinext/shims/headers`), while source
checkouts alias userland `next/*` imports to the local shim files. The
two specifiers resolved to different module instances, so request-scoped
singleton state (navigation context, headers) split between the source
shim copy and the package export copy.

The violated invariant is that every shim module must be a per-request
singleton regardless of import specifier. Resolve `vinext/shims/*`
through the same plugin path as the `next/*` aliases so both forms land
on the local shim files.

Exercised by the SSR shell-error recovery browser spec, whose fixture
imports vinext from the source checkout and depends on shared
navigation state across both import forms.

* fix(app-router): recover SSR shell render errors via __next_error__ document

When the HTML (Fizz) render rejects during SSR, vinext re-rendered a
server-side global-error page whose flight payload encodes the error
tree. For an app without a custom global-error.tsx that meant the
default error card with no path back to the real page: an SSR-phase-only
throw (e.g. a client component using the "throw to opt out of server
rendering" pattern) left the browser stuck on the card even though the
client render would succeed.

The violated expectation is Next.js's shell-error semantics: a failed
HTML shell is served as the default `__next_error__` error document
carrying the ORIGINAL flight payload and the bootstrap module, and the
browser re-renders the real tree from that payload with createRoot
instead of hydrating. Local error.tsx boundaries still win — they ship
inside the flight payload and catch the re-thrown error client-side.

handleSsr now resolves to that recovery document instead of rejecting,
but only when both hold:
- the error did not originate in the RSC render (no string `digest`),
  so flight errors, redirect()/notFound(), and server-component throws
  keep driving the existing rejection-based boundary machinery, and
- the app has no custom global-error.tsx (the generated entry knows at
  build time and threads hasCustomGlobalError through dispatch/render
  options); apps with one keep the server-rendered boundary re-render.

The browser entry switches from hydrateRoot to createRoot when the
document root carries id="__next_error__", dropping the error-shell
styles first.

Covered by the new ssr-error-shell-recovery browser spec (recovery to
real content, local error.tsx for SSR-only and unconditional client
throws) and the existing tests/nextjs-compat/global-error.test.ts
boundary-semantics suite.

* refactor(review): address PR 1908 non-blocking notes

- Add static prerender no-boundary recovery regression test to
  ssr-error-shell-recovery.browser.spec.ts
- Document broad __next_error__ browser marker in app-browser-entry.ts
- Extract stripJsExtension to utils/path.ts and wire into all shim
  resolution sites (vinext/shims/* + react-server shims)

Non-functional: targeted regression coverage + code documentation
+ minor resolver hardening per reviewer feedback.

* refactor(review): clarify shell recovery assumptions

* fix(ssr): cancel abandoned prerender streams

* refactor(ssr): clarify error shell root options

* fix(isr): recover shell errors during regeneration

* fix(ssr): scope client recovery to marked shells

* fix(plugin): explicitly filter vinext shim subpaths

* fix(plugin): retain null-prefixed shim resolution

* test(nextjs-compat): cover no-boundary shell recovery fallback

An unconditional client throw during SSR shell recovery without a local error boundary must still land on the default global-error card. Without a regression test, a future change could tear down the recovery shell and leave a blank document.\n\nAdd a production browser case that exercises the no-boundary route and asserts the default error UI after the client re-render throws again.

* fix(app-router): preserve shell recovery error semantics

* test(app-router): harden shell recovery cache semantics

* fix(app-router): mark global error responses uncacheable

* test(app-router): align error response status expectations

* fix(build): preserve null-prefixed og resolution

* fix(cache): delegate cache header cleanup to adapters

---------

Co-authored-by: James <james@eli.cx>
2026-06-14 22:28:25 +00:00
Nathan Nguyen b7ef466742 fix(pages): preserve app props for GSSP requests (#1996)
* fix(pages): preserve app props for gssp requests

* docs(pages): update _next/data comment to reflect full props envelope

* fix(pages-router): preserve _app.getInitialProps during stale ISR regeneration

Stale ISR background regeneration called getStaticProps directly and rendered
HTML and __NEXT_DATA__ with only the page's pageProps, dropping app-level
props from _app.getInitialProps. The foreground path already loads
_app.getInitialProps first and merges its props, but the background
regeneration path skipped that step.

Extract a shared loadPagesAppInitialRenderProps helper from the production
foreground path and reuse it during background regeneration in both
pages-page-data.ts and dev-server.ts. This ensures regenerated pages carry the
same full props envelope as the original render.

Add a regression test in tests/pages-page-data.test.ts.

* fix(pages-router): skip _app.getInitialProps on ISR cache hits

The foreground render path ran _app.getInitialProps before consulting the
ISR cache, so fresh and stale cache hits executed userland App data code
even though the cached HTML was returned verbatim. That wasted work on the
hot path and ran side-effecting App code whose result the cached response
never reflected.

The eager App initial-props load happened up front, ahead of the HIT and
STALE short-circuits. Defer it until the request will actually render:
load it lazily inside the getServerSideProps / getStaticProps /
getInitialProps branches, after the cache short-circuits return.
Stale-while-revalidate already re-runs it inside the regeneration closure,
so regenerated HTML still carries app-level props. The dev SSR handler and
the production page-data resolver are updated in lockstep to preserve
dev/prod parity.

Tests cover the fresh-HIT skip and the stale foreground-skip vs
regeneration-run split at the page-data resolver boundary.

* refactor(pages-router): extract dev App getInitialProps loader into a tested helper

The dev SSR handler ran _app.getInitialProps inside an inline closure that
mutated captured pageProps/renderProps and read res directly, so its lazy
load-only-on-render behavior could only be covered by a heavyweight
integration test that vi.doMock'd the isr-cache and file-matcher modules —
a mock cascade with little signal.

Move the decision into loadDevAppInitialProps in pages-get-initial-props.ts.
It takes the App component, req/res, and an injected AppTree builder (keeping
React out of the module) and returns a discriminated result —
skip / response-sent / render — that the caller applies. The dev-server
closure is now thin glue: build the React tree, delegate, apply the result.

Adds focused unit tests that drive the helper through its real boundary
(genuine getInitialProps functions, plain req/res inputs) — no module mocks:
the skip path, App/page prop merging, pageProps normalization, the
response-sent short-circuit, and the router/ctx wiring passed to userland.

* fix(pages): preserve app props across data requests

* fix(pages): preserve fallback cache expiry

* fix(pages): preserve dev app context during ISR

* fix(pages): hydrate middleware rewrite fallbacks

* fix(pages): retarget middleware data rewrites

* fix(pages): preserve rewrite query on navigation

* fix(pages): finalize rewrite navigation state

* fix(pages): resolve rewrite data targets consistently

* fix(pages): await static props during regeneration

* fix(pages): preserve original query in resolved url

* Revert "fix(pages): await static props during regeneration"

This reverts commit cbdcdf65cd.

* test(app): cover rewrite params in app search

---------

Co-authored-by: James <james@eli.cx>
2026-06-14 20:17:05 +01:00
James Anderson 4821d247b0 fix(pages): preserve module identity with deployment ids (#2012) 2026-06-14 19:45:38 +01:00
Xplod13 5e37596183 fix(routing): re-encode trailing-slash Location for non-Latin-1 paths (#2011)
normalizeTrailingSlash built the redirect Location from the already
percent-decoded pathname. A character above U+00FF (e.g. a CJK slug or
emoji under trailingSlash:true) made the Headers constructor throw
'Cannot convert argument to a ByteString', caught by the outer handler
and surfaced as a 500 instead of a 308. Latin-1 characters such as
spaces did not throw but produced a malformed, un-percent-encoded
Location.

Percent-encode the redirect target before building the response,
encoding every character that is invalid raw in an RFC 3986 path while
preserving existing %xx escapes and / delimiters so already-encoded
delimiters like %23 are not double-encoded.

Fixes #1979

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 19:18:25 +01:00
James Anderson e1958ae3fa fix(router): share Pages Router context across chunks (#2010) 2026-06-14 16:15:23 +01:00
Jerry Zhao de9d03a846 test(shims): normalize expected og shim path for Windows (#2006) 2026-06-14 00:45:25 +01:00
Nathan Nguyen 930e03c449 fix(ppr): gate fallback shells until request-time resume is supported (#1716)
* fix(app-router): prerender cacheComponents root-param fallback shells

PR 1 of 4: core model + build integration.
Model: app-ppr-fallback-shell, pregenerated-concrete-paths, prerender-manifest
Build: prerender/run-prerender fallback shell artifact generation
Tests: createAppPprFallbackShells, pregenerated-concrete-paths core

* feat(ppr): add fallback shell payload identity

* feat(ppr): safely serve fallback shell cache entries

* refactor(ppr): extract fallback shell render pipeline and dedupe getViteMajorVersion

* fix(ppr): restore safe-serving CI checks

The safe-serving branch failed CI because a client-side server-only guard rejected valid 'use server' action modules, a fallback-shell dependency cast no longer matched its helper type, apps/web lost the Cloudflare cache adapter source path during typecheck, and Knip could not resolve the documented Cloudflare cache adapter subpaths.

The server-only guard now reads the directive prologue and skips top-level 'use server' modules, fallback-shell regeneration passes an explicit typed dependency object, apps/web gets the workspace Cloudflare cache path, the Cloudflare package exports explicit adapter subpaths, Knip uses a relative source import in the dispatch unit test, and the readiness test awaits the actual cache-ready promise.

* fix(ppr): guard fallback shell reads for queries

* fix(ppr): normalize pregenerated concrete paths

* fix(ppr): address review comments on fallback shell serving and react runtime check

* fix(ci): restore knip ignores for unlisted binaries and prune dependencies

* fix(ppr): restrict bracket check in fallback detection to legacy manifests

* fix(ppr): prefer stable ESM react-dom/static.edge before CJS fallback

The loadStaticPrerender dev-mode path hard-codes react-dom's internal
CJS file layout (cjs/react-dom-server.edge.development.js). A React
upgrade could silently break fallback-shell rendering in dev without
affecting production because the function never tried the stable ESM
entry in development.

Change the order so that react-dom/static.edge is attempted first in
all environments. Only fall back to the CJS path when the ESM entry
does not export prerender() and we are in a development runtime. This
lets future React dev builds that expose prerender() from the ESM entry
work automatically, and it surfaces the CJS-path failure only when the
stable path is genuinely unavailable.

Also handle the CJS default-export interop shape that Node.js ESM
produces when dynamically importing a CommonJS module.

* refactor(ppr): address four review cleanup items

1. Remove redundant double-normalization in seed-cache.ts
   addPregeneratedConcretePath already normalizes internally, so the
   call-site normalizePregeneratedPathname() was redundant. Dropping it
   gives a single source of truth for pathname normalization.

2. Lazily construct FallbackShellRenderDeps in tryServePprFallbackShell
   Extract the large FallbackShellRenderDeps object into a top-level
   buildFallbackShellRenderDeps helper. The closure in the probe loop
   now just delegates, so the heavy object is only created when a STALE
   entry actually triggers regeneration, not on every HIT probe.

3. Add dev-only warning for legacy bracket heuristic
   When isFallbackShellArtifactPath falls back to the bracket substring
   scan (route.fallback === undefined), emit a console.warn in dev so
   developers know a legacy manifest is being used and concrete URLs
   with literal brackets may be misclassified.

4. Update pregenerated-concrete-paths.test.ts to colon notation
   The production manifest writer uses colon notation (/:slug) for the
   route field, but the test fixtures used bracket notation (/[slug]).
   Update the fixtures so the test format matches production, exercising
   the real key format that the safe-serving guard depends on.

* test(ppr): compact fallback shell dispatch fixtures

* refactor(ppr): name fallback shell render phases

* refactor(app-router): deduplicate PPR fallback shell and app page cache render paths

* fix(ppr): avoid serving incomplete fallback shells

* chore: drop redundant cloudflare cache aliases

* fix(ppr): track fallback navigation hooks

* test(ppr): render navigation hook probes

* test(ppr): type navigation hook probes

* refactor(ppr): remove unused shell regeneration path

* refactor(ppr): remove unused shell result type

* fix(ppr): safely gate fallback shell prerendering

* fix(ppr): keep fallback shell gate internal

* fix(ppr): mark generated dynamic fallback shells

* test(ppr): align fallback fixture and search params

---------

Co-authored-by: James <james@eli.cx>
2026-06-14 00:44:54 +01:00
Nathan Nguyen b5619c19f9 refactor(navigation): route prefetch reuse through planner (#1962)
* refactor(navigation): route prefetch reuse through planner

Navigation cache reuse decisions were still split across the browser executor, which made visited-response reuse, prefetch consumption, and optimistic shell attempts hard to verify at the control-plane boundary.

Move the reuse decision table into navigationPlanner with typed candidate facts, keep cache reads and React effects in the executor, and preserve silent stale-prefetch eviction for navigation probes.

* refactor(navigation): exercise visited cache miss planning

Visited response cache misses were represented in the planner API, but the browser executor still returned before invoking that classifier when the entry was absent or intentionally bypassed.

That made the missing-candidate branch planner-owned in tests but executor-local in production. The executor now builds candidate facts for both present and missing states, asks the planner for the decision, and keeps cache mutation in the executor as the effect boundary.

* fix(navigation): avoid prefetch probes on visited cache hits

Visited-response reuse should stay on the soft-navigation fast path without touching the prefetch cache. The planner extraction accidentally computed prefetch availability before deciding to reuse a visited response, so stale prefetch entries could be silently evicted on a path that previously left them untouched.

Add a planner prefetch-probe decision and have the browser executor consult it before reading the prefetch cache. This keeps cache mutation in the executor while making the no-probe condition explicit and tested.

* fix(navigation): preserve prefetch fallback behavior

* fix(navigation): keep slot mismatch probe behavior

---------

Co-authored-by: James <james@eli.cx>
2026-06-13 22:12:34 +01:00
Nathan Nguyen 4baf85ad5e fix(router): restore pages scroll traversal state (#1999)
* fix(router): restore pages scroll traversal state

* fix(router): preserve pages component identity across HTML fallback

Pages Router HTML fallback could import the module URL from fetched __NEXT_DATA__ even when the generated page loader already existed. In Vite chunk graphs that can evaluate a duplicate page or router module, same-route param navigations remounted the page and lost listener state before routeChangeComplete.

Store the router wrapper component types on the shared browser runtime singleton, prefer registered page loaders on the HTML fallback path, and resolve navigation at the root commit boundary that Next.js awaits instead of waiting for passive effects. Non-DOM document mocks still resolve immediately so unit harnesses do not masquerade as real browser commits.

Validated with the upstream reload-scroll-backforward-restoration deploy suite and the local router-events and scroll-restoration regressions.

* test(router): simulate pages router commits in shims tests

* fix(router): move Pages Router readiness into shared runtime state

Move the pagesRouterReady bit into PagesRouterRuntimeState so duplicated
next/router module instances (client entry + page chunks) observe the same
readiness value. The initial value is still computed from
shouldDeferInitialPagesRouterReady() once per document.

Also tighten the scroll-restoration e2e fixture so routeChangeComplete
assertions cannot pass from stale page state, and add a regression test
that simulates two evaluated router instances on a deferred-ready page.

* fix(router): early-exit scroll restoration when target unreachable, document useRouter fallback

Addresses ask-bonk review feedback on PR #1999:

- restorePagesRouterScrollPosition now breaks early when window.scrollY
  stops changing across frames, avoiding the full 60-frame budget when
  the saved scroll position exceeds the rendered page height.
- useRouter() fallback path now has an explanatory comment documenting
  the non-reactive singleton return is intentional for split-chunk compat.

* fix(router): harden scroll restoration settling

---------

Co-authored-by: James <james@eli.cx>
2026-06-13 22:11:18 +01:00
Nathan Nguyen d1a80cd668 fix(app-router): preserve front redirects through fallback route handlers (#2000)
* fix(app-router): preserve front redirects through fallback route handlers

* test(e2e): assert single bootstrap hydration in front-redirect test

* chore: remove dead stripDeploymentIdQuery export

* fix(app-router): handle cancelled bootstrap streams

* docs(app-router): clarify bootstrap recovery

* test(e2e): tolerate dangling fixture symlink

* test(e2e): run front redirect regression in CI

* fix(app-router): always hide internal RSC queries

* fix(app-router): preserve visible hydration URL

* test(e2e): scope visible URL regression

* refactor(app-router): trim front redirect residue

* test(e2e): group fixture setup command

* test(e2e): tighten front redirect assertions

* fix(app-router): preserve ordinary route handler URLs

* fix(app-router): normalize edge route handler URLs

* docs(app-router): explain route URL parity

* fix(app-router): preserve Node RSC request URLs

* fix(app-router): normalize route handler RSC paths

* fix(app-router): forward RSC tokens through rewrites

---------

Co-authored-by: James <james@eli.cx>
2026-06-13 22:08:02 +01:00
Nathan Nguyen 3253aafd77 fix(pages-router): pass rewrite URL to edge API requests (#1998)
* fix(pages-router): pass rewrite URL to edge API requests

* fix(pages-router): preserve edge API request URL parity

* fix(pages-router): configure edge API NextRequest

* fix(pages-router): preserve edge API locale config

* fix(pages-router): preserve edge request metadata

* fix(pages-router): align edge API URL formatting

* fix(pages-router): match API locale casing

* fix(pages-router): match domain locales by locale

* docs(pages-router): clarify edge API basePath parity

* test(deploy): expect metadata-preserving URL clone

* docs(pages-router): note basePath rewrite parity

---------

Co-authored-by: James <james@eli.cx>
2026-06-13 22:05:31 +01:00
Nathan Nguyen dabcb55e63 fix(app-router): expose active source page on window.next (#1995)
* fix(app-router): expose active source page on window.next

App Router pages did not update window.next.__internal_src_page, so Next.js-compatible tooling and deploy tests could not observe the active source page on initial render or client transitions.

The payload only exposed URL route IDs, which drop route groups and bracketed dynamic segment names. The fix carries a source-page metadata field from the app route's filesystem segments, reads it from committed browser router state, and mirrors it onto window.next like Next.js does.

Adds regression coverage for route-group and dynamic source-page encoding plus the window.next writer contract ported from the upstream app-dir test.

* fix(app-router): preserve source page across boundary renders

* fix(app-router): tolerate malformed source page metadata

* fix(app-router): preserve intercepted fallback source page

* fix(app-router): omit unknown boundary source page

---------

Co-authored-by: James <james@eli.cx>
2026-06-13 21:59:39 +01:00
James Anderson 5ace0db7ac fix(deploy): preserve app module identity with deployment ids (#2005) 2026-06-13 12:06:36 +01:00
James Anderson 3d9639510e fix(build): honour experimental.lightningCssFeatures include/exclude (#1498) (#1664)
vinext silently ignored `experimental.lightningCssFeatures` because the
options were never plumbed into Vite's CSS pipeline. `light-dark()` and
other modern CSS features were still lowered to polyfills even when the
user explicitly listed them under `exclude`.

Resolve `experimental.useLightningcss` and convert the dash-case feature
names from `experimental.lightningCssFeatures` into the numeric bitmask
expected by lightningcss (mirroring Next.js's `featureNamesToMask` in
`packages/next/src/build/webpack/loaders/lightningcss-loader/src/loader.ts`
and `crates/next-core/src/next_config.rs`). When `useLightningcss` is on,
forward `transformer: 'lightningcss'` plus the resolved `include`/`exclude`
masks to Vite's `css.lightningcss` bridge.

Adds a regression test that builds a fixture with
`exclude: ['light-dark']` and asserts the function survives untouched in
the emitted CSS, plus an inverse `include: ['light-dark']` case and unit
coverage for the feature-name → bitmask helper.

Ported from Next.js:
test/e2e/app-dir/experimental-lightningcss-features/experimental-lightningcss-features.test.ts
2026-06-13 00:39:58 +00:00
James Anderson cd181cc755 chore: add codex to gitignore (#1992) 2026-06-13 00:39:29 +00:00
James Anderson eef22e07a8 fix(pages-router): block fallback shell for crawler UAs on prerender (#1543) (#1663)
* fix(pages-router): block fallback shell for crawler UAs on prerender (#1543)

When `getStaticPaths` returns `fallback: true` and an unlisted path is hit
by a known bot/crawler, vinext was serving the `Loading...` shell so the
crawler indexed the fallback HTML instead of the real page. Mirror Next.js
`pages-handler.ts` and flip `isFallback` to false for bot User-Agents so
the request renders synchronously with real props.

- Add `isBotUserAgent` helper (DOM + HTML bot regex) in `utils/html-limited-bots.ts`,
  matching Next.js `shared/lib/router/utils/is-bot.ts`.
- Plumb `userAgent` + `htmlLimitedBots` into `resolvePagesPageData` and
  flip the fallback bit when the UA matches.
- Apply the same flip in the dev `createSSRHandler` for parity.
- Targeted unit + integration regression tests covering Googlebot,
  Bingbot, DuckDuckBot, YandexBot, facebookexternalhit, and a normal
  Chrome UA control. Ported from `.nextjs-ref/test/e2e/prerender-crawler.test.ts`.

Refs #1543.

* fix(pages-router): preserve array user-agent bot detection
2026-06-13 00:35:28 +00:00
Jared Stowell 6ad04e246d perf: skip unnecessary import parsing (#1991)
* perf(optimize-imports): skip unnecessary import parsing

* fix(optimize-imports): keep parsing edge static imports

* Update packages/vinext/src/plugins/optimize-imports.ts

Co-authored-by: ask-bonk[bot] <249159057+ask-bonk[bot]@users.noreply.github.com>

---------

Co-authored-by: ask-bonk[bot] <249159057+ask-bonk[bot]@users.noreply.github.com>
2026-06-13 01:30:08 +01:00
James Anderson ca34394865 fix(app-router): fold typeof window before resolution (#1956)
* fix(app-router): fold typeof window before resolution

* fix(build): respect window bindings during folding

* fix(build): handle typeof window environment edge cases
2026-06-13 01:24:34 +01:00
James Anderson bf41ee49dd fix(image): prevent optimizer cache-key amplification (#1944)
* fix(image): validate optimizer parameters

* fix(image): close optimizer amplification aliases

* fix(image): validate pure app dev requests

* fix(image): address optimizer review findings
2026-06-13 01:10:12 +01:00
James Anderson 24d3dfcf00 fix(pages): harden cookie parsing (#1947)
* fix(pages): harden cookie parsing

* fix(pages): preserve cookie object compatibility

* fix(shims): distinguish edge cookie parser

* refactor(cookies): dedupe header parsing
2026-06-13 00:57:45 +01:00
James Anderson c023fc3810 fix(actions): bound Flight payload graph validation (#1942) 2026-06-13 00:56:57 +01:00
James Anderson 04db457691 fix(deploy): prevent Windows shell injection (#1946)
* fix(deploy): avoid Windows shell invocation

* fix(deploy): preserve long Wrangler env names
2026-06-13 00:47:15 +01:00
James Anderson d7447d8d88 test(compat): classify runtime cli-output deploy suite (#1954)
* test(compat): exclude runtime cli output deploy suite

* style: format deploy manifest test

* test(compat): simplify deploy suite exclusion

* test(compat): skip deploy case by title

* test(compat): satisfy deploy manifest lint
2026-06-13 00:30:07 +01:00
James Anderson 70ee909adf fix(app-router): support extensionless variable imports (#1958)
* fix(app-router): support extensionless variable imports

* fix(build): harden extensionless dynamic imports

* fix(build): align variable import resolution

* fix(build): cover dynamic import contexts

* fix(build): scope variable import contexts

* fix(build): avoid comment parser backtracking
2026-06-13 00:22:22 +01:00
James Anderson b50af3e39d fix(link): preserve basePath hash navigation (#1952)
* fix(link): preserve relative hash navigation with basePath

* fix(link): remove stale relative href resolution
2026-06-13 00:15:49 +01:00
James Anderson b3d407a6fd fix(headers): prioritize config cache headers for metadata assets (#1953)
* fix(headers): prioritize config cache headers for metadata assets

* test(headers): guard metadata header precedence

* style: format metadata header fix
2026-06-13 00:14:59 +01:00
James Anderson a84a038fe6 fix(config): share CommonJS module fallback (#1990)
* fix(config): share CommonJS module fallback

* fix(config): harden CommonJS retry detection
2026-06-13 00:13:22 +01:00
James Anderson a155fdf997 fix(deploy): improve deployment id parity (#1949)
* fix(deploy): improve deployment id parity

* test(router): isolate deployment prefetch globals

* fix(deploy): restrict asset tokens to managed files
2026-06-13 00:10:42 +01:00