* fix: add next/offline shim with useOffline() hook (#701)
Add a no-op shim for next/offline that exports useOffline() returning false.
Registers it in the shim resolution map, type declarations, and import support
check so libraries importing next/offline don't fail. The full offline retry
behavior is deferred until the feature stabilizes upstream.
* fix: address review feedback for next/offline shim
- Add "use client" directive to offline.ts for RSC plugin compatibility
- Add JSDoc block explaining the stub (matching amp.ts pattern)
- Fix test comment to reference PR instead of implementation file
* Apply suggestion from @james-elicx
---------
Co-authored-by: James Anderson <james@eli.cx>
* fix(fonts): make Google font shim registrations stable
Repeated next/font/google calls currently mint counter-based class names and append new SSR style rules. During dev HMR, the app module can re-evaluate while the shim module stays alive, so stale classes and links accumulate and the first emitted :root variable keeps winning.
The bad invariant was treating each runtime call as a new font registration. Use a deterministic identity for each family and options pair, remove the non-Next :root variable rule, and keep variable declarations scoped to the returned variable class.
Regression coverage verifies stable class identities, no :root emission, and no SSR style growth for repeated equivalent calls.
* fix(fonts): address Google font review feedback
The first PR version left two edge cases in the new stable identity path: crafted font family names could still leak unsafe selector characters into class names, and omitted display hashed differently from explicit display: swap even though both generate the same font URL.
Sanitize the readable family segment used in selectors, normalize display to the same default used by buildGoogleFontsUrl, and tighten the CSS variable regression so it checks CSS added by the current call instead of accumulated module state.
* fix(fonts): canonicalize Google font identity hashing
Equivalent Google font loader options could generate the same CSS and font URL while still producing different class identities. That reintroduced duplicate SSR style rules when option arrays used a different order or representation.
The identity hash now canonicalizes unordered option sets, default-style equivalence, and fallback whitespace before hashing. A focused regression test covers reordered weights and subsets, explicit normal style, and trimmed fallback names.
* fix(fonts): normalize default fallback font identities
Omitting next/font/google fallback produced the same CSS as fallback: ["sans-serif"] but still hashed a different raw option shape. That left the most common default call path outside the deterministic identity dedupe.
The identity hash now uses the resolved fallback list and no longer includes the serialized font-family CSS string. Regression coverage verifies implicit and explicit default fallback calls share class and variable identities, and the :root assertion now checks only styles added by its own test.
* refactor(app-router): delegate RSC preload hint normalization
The App Router RSC entry currently owns the React Flight preload hint stream transform inline. That keeps byte-stream buffering logic inside generated code, so the behavior is only indirectly covered by generated-entry snapshots.
Move the stream normalization into a typed server helper and keep the generated RSC entry as a thin wrapper around renderToReadableStream. Add direct coverage for complete lines, split chunks, and final unterminated Flight hint lines.
* test(app-router): cover mixed Flight preload hints
The RSC entry still owned route matching, intercept lookup construction, and dynamic metadata pattern matching inside generated source. That kept request-path behavior in a template string and made direct tests awkward.
Move the matching behavior into a typed server helper, keep route import and manifest emission in the generator, and update entry-template assertions to verify delegation instead of inline matcher code.
Middleware cookies set through NextResponse only updated Set-Cookie, so cookies() in the same request could not observe values written by middleware. External middleware rewrites were normalized to pathname and search, so cross-origin destinations were routed locally instead of being proxied.
Mirror middleware cookie mutations into x-middleware-set-cookie and merge that internal header back into the request cookie store. Preserve cross-origin rewrite URLs through middleware execution and proxy them across app, pages, prod, and deploy request paths, while stripping internal middleware headers from client and upstream responses.
* fix(app-router): scope layout params and propagate layout head errors
Layouts received full route params, layout generateMetadata failures were swallowed, and layout-thrown forbidden()/unauthorized() fell back through the not-found boundary path. Those diverge from Next.js when nested layouts depend on segment params, when head generation fails before page render, or when HTTP access APIs are thrown from a layout.
The generated RSC entry now delegates param slicing, head resolution, and parent access-boundary selection to typed runtime helpers. The helpers keep route-specific imports in the entry while moving the behavioral core into unit-tested modules.
Tests port Next.js layout params, global-error, forbidden, and unauthorized coverage into focused helper and integration regressions.
* test(app-router): cover layout viewport error boundaries
Layout generateViewport() failures now intentionally share the same boundary path as layout generateMetadata() failures. Copilot flagged that this behavior change needed direct coverage.
Add dev and production-preview compat assertions for co-located error.tsx handling and global-error escalation, with fixtures that throw from layout generateViewport().
* chore(app-router): address head review nits
Cached App Router pages only carried implicit revalidatePath tags derived from the resolved URL. That left dynamic routes tagged with concrete values, so pattern-scoped invalidation like revalidatePath("/blog/[slug]", "layout") could miss entries rendered at /blog/hello.
The generated RSC entry now delegates implicit tag construction to a typed helper that combines exact pathname tags with route-segment-derived layout, page, and route handler tags. Focused tests cover dynamic route patterns, route groups, root aliases, and route handler leaves.
Refs cloudflare/vinext#921
App route handlers appended cookies().set() mutations after cookies already present on the returned Response. That made same-name mutable cookies override the Response cookies, which differs from Next.js route-handler semantics.
Next.js treats mutable cookies as fallbacks and reapplies returned Response cookies as final values. Deduplicate vinext pending mutable cookies by name, filter out pending cookies shadowed by the returned response, and then reappend the returned Set-Cookie headers last.
Adds focused helper coverage plus a nextjs-compat fixture that exercises the live App Route path.
Move renderToReadableStream() before buildPagesShellHtml() + clearSsrContext()
so that <Head> and other SSR state collectors (styled-jsx, useServerInsertedHTML)
are populated before they are read. This fixes a race condition where head styles
were silently dropped because they were collected before the page had finished
rendering.
Mirrors Next.js fix: vercel/next.js@9853944
The specific styled-jsx race condition (styledJsxInsertedHTML() called
concurrently with page render via Promise.all) does not exist in vinext because
vinext does not implement a styled-jsx style registry at all. However, the same
class of ordering bug affected vinext's Pages Router prod path where getSSRHeadHTML
was called before rendering completed.
* fix: resolve symlink paths in standalone BFS package copy (#724)
When resolvePackageJsonPath finds a package via the lookup-paths
fallback, the returned path may be a symlink (e.g., under a hoisted
node_modules/ directory). Calling createRequire() on a symlink
path causes Node module resolution to miss transitive dependencies
because it walks up from the symlink ancestor directories rather
than the real (e.g., .pnpm/) path.
Fix: call fs.realpathSync() on the resolved package.json path
before using it for createRequire() and readPackageJson().
Also adds E2E test coverage for the standalone output mode.
* fix: address review feedback
Add standalone-output to CI E2E matrix, rename server header test
to reflect what it actually asserts, fix unused req parameter.
* fix(app-router): return 405 for non-action mutations to static pages
Static and SSG App Router page routes currently render HTML or RSC payloads for POST and PUT requests that are not server actions. That diverges from Next.js and makes unsupported mutation methods look successful.
The App Router page render path only handled server actions and route handlers before falling through to page rendering. Add a small page-method policy helper and call it from the generated RSC entry before page rendering so static and SSG candidates return 405 with Allow: GET, HEAD while possible server action POSTs still pass through.
Tests cover the helper policy and the live App Router fixture for static and ISR pages.
* fix(app-router): preserve 405 allow header
Set the App Router page 405 Allow header after merging middleware response headers so middleware cannot clobber the methods advertised by the generated Method Not Allowed response.
Add a focused regression test that keeps middleware header propagation while asserting Allow remains GET, HEAD.
* fix(app-router): reject middleware control responses in route handlers
App Route handlers currently treat NextResponse.next() and NextResponse.rewrite() as ordinary 200 responses. That diverges from Next.js, where those helpers are middleware control-flow signals and are rejected after a route handler returns.
The route-handler execution path now validates returned responses before cache policy or response finalization runs. Focused unit and integration tests cover the invalid next and rewrite helper responses.
* Update tests/app-route-handler-execution.test.ts
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Update packages/vinext/src/server/app-route-handler-response.ts
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* fix(app-router): validate route handler ISR regeneration responses
Stale App Route handler regeneration called runAppRouteHandler directly and could serialize a middleware control response into the ISR cache. That bypassed the validation used by the live route-handler execution path.
Run the same response assertion before background regeneration writes a new APP_ROUTE cache entry, restore exact Next.js error wording for parity, and cover the x-middleware-next boundary semantics.
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
App Router SSR rendered useServerInsertedHTML callbacks only once before returning the HTML stream. CSS-in-JS registries registered at shell render were cleared before later Suspense chunks, so styles collected after the shell never reached streamed HTML.
Keep callback registrations alive for the stream lifetime and let the tick-buffered HTML transform request insertion HTML on each flush after the initial head injection. This matches Next.js per-chunk server inserted HTML transform and preserves cleanup on stream completion or cancellation.
Adds regression coverage for persistent callback rendering and a Next.js-ported Suspense CSS-in-JS streaming order case.
* fix(router): reject invalid app route discovery conflicts
App Router route discovery currently lets upward interception markers climb past the normalized root and relies on generic duplicate-pattern validation when a page and route handler share the same app route.
The scanner now validates visible interception climb depth before resolving the target, and reports an explicit page/route conflict before running generic route pattern validation.
Regression coverage captures the Next.js parity cases for root interception markers, route-group-transparent roots, two-level upward markers, and page plus route handler conflicts.
* fix(router): address app route validation review
* fix(app-router): restore hash anchors on history traversal
App Router hash-only entries can be pushed without saved vinext scroll state while vinext has browser scroll restoration set to manual. On forward traversal, the URL moves back to the fragment but the browser no longer performs native anchor scrolling, so the page can remain at the top.
Restore saved numeric scroll state first, then fall back to Next-compatible hash target scrolling when no vinext scroll state exists. The regression test drives a hash-only Link entry through back and forward traversal.
* test(app-router): cover hash scroll edge cases
The RSC fetch error E2E used direct private navigation calls and Playwright route mocking for a redirect chain. Those assumptions are timing-sensitive and can skip the intended RSC request under parallel Playwright runs.
Drive the cases through fixture links and serve the redirect-to-500 chain from middleware so the test observes real browser fetch behavior. This keeps coverage for hard navigation to the post-redirect URL while removing the route redispatch dependency.
Ownerless URL sync commits from hash navigation and patched history methods could decrement an active client navigation snapshot. That let hooks stop reading the pending render snapshot before the transition committed, briefly exposing stale committed URL state.
The snapshot release invariant was tied only to commit count underflow, not to ownership of the activated snapshot.
Only navigation-owned commits release snapshots now, while App Router superseded-transition cleanup opts into snapshot release without taking pending pathname ownership. A regression test covers external history.pushState during an active pending render snapshot.
Routes whose first layout lives below app/ currently inherit slots discovered before that layout and clamp them to layout index 0. That incorrectly passes top-level parallel slots into a separate root layout.
Keep the pre-layout sentinel while scanning ancestors, skip those slots once the route has a real layout, and preserve the existing layout-less scanner metadata path for separate validation work. Add routing tests for the pre-root leak and the valid in-subtree slot case.
* fix(cache): scope use cache entries by build id
Shared "use cache" entries currently key only on the cached function id and serialized arguments. That lets a persistent cache handler reuse serialized results after a deploy when the generated function id and arguments remain stable.
The violated invariant is that a cache entry belongs to the build that produced its function body, matching Next.js buildId key material.
Include __VINEXT_BUILD_ID in the shared cache key when it is available, preserving the existing key shape for environments without a build id. Add a regression test that proves two builds with the same function id do not share the stale value.
* fix(cache): capture use cache build id at registration
Shared "use cache" wrappers should derive their build scope from the bundle that registered the cached function, not from a fresh environment lookup on every invocation.
The prior implementation still produced build-scoped keys, but it kept the build id read inside the hot wrapper path and allowed a mutated environment to change the key for an already-registered function.
Resolve the build id once in registerCachedFunction and close over it when constructing cache keys. Keep the direct process.env.__VINEXT_BUILD_ID access so Vite can inline the build id for processless Worker bundles.
Fetch cache entries without explicit next.tags could survive revalidatePath(). The page or route cache entry was invalidated, but the regenerated render could still read the old fetch response and reproduce stale data.
The missing boundary was Next.js soft tag semantics: path-derived implicit tags are read-time context for fetch cache lookups, not durable tags stored on the fetch entry.
Thread route-derived soft tags through App Router renders, pass them to fetch cache reads, and teach the memory and KV handlers to treat revalidated soft tags as cache misses without deleting shared fetch entries.
Regression coverage verifies revalidatePath invalidates untagged fetch cache reads and that KV soft-tag misses do not delete the shared entry.
* fix(fonts): google fonts building perfectly (it was just a regex 😭)
* fix(fonts): allow newlines inside bracket clauses
Previous fix's [^;\n]+? blocked the semicolon-less line bug but also
stopped matching multi-line bracket imports/exports — Prettier wraps
specifiers across lines once the clause crosses printWidth.
Clause is now a sequence of brace blocks (newlines allowed inside, but
[^}] keeps the lazy match from spanning past the matching close brace)
or single non-;\n chars. Multi-line shapes match again; the original
swallow-prevention guard still holds.
Reverts the export regex back to [^}]+ — } already delimits, so the
extra \n exclusion was over-defensive.
* fix(fonts): apply formatter to test file
---------
Co-authored-by: MrIago <28714061+MrIago@users.noreply.github.com>
* debug(dev): hoist socket-error backstop to module top-level + opt-in trace
Two changes intended to pin down why the process-level handler from
PR #913 still doesn't catch the ECONNRESET trace some users report:
1. Move installation from inside configureServer to module top-level,
guarded by Symbol.for to prevent double-install. Earlier versions
tied teardown to httpServer 'close', which Vite emits on dep
re-optimization, full reloads, and other lifecycle events — leaving
a window where the listener is absent when a stale stream errors.
Module-level install + Symbol guard removes that window entirely.
2. Add an opt-in console.warn marker behind
VINEXT_DEBUG_SOCKET_ERRORS=1 that fires whenever the listener
absorbs a peer-disconnect error. The visible
`node:events:487 throw er; // Unhandled 'error' event` output
otherwise leaves it ambiguous whether the listener never ran
(install / lifecycle issue) or ran but was somehow bypassed
(different async surface / dispatcher). The marker disambiguates.
No behavior change for users not setting the env flag beyond the
hoisting. Filter codes and re-throw shape are unchanged from #913.
Refs #905.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: address bonk review on dev socket-error backstop
Three issues from PR #916 review:
1. Module-top-level install was wrong — it ran during 'vinext build',
'vp pack', and Vitest worker imports too, so the JSDoc 'dev-only'
claim was inaccurate and a real ECONNRESET from a pre-render fetch
in CI would have been silently swallowed. Move the install back into
configureServer (which only fires in dev) but **without** binding
teardown to httpServer 'close' — that was the original lifecycle bug
PR #913 had. Symbol.for guard makes re-invocation a no-op so the
listener still survives server restarts within a session.
2. Restore the middleware-mode skip dropped in the previous commit.
Embedders running vinext in middleware mode (Express/Connect) keep
ownership of their own process-level handlers. Gated on
server.httpServer, matching the prior PR #913 behavior.
3. Document the listener-ordering implication of installing during
configureServer (registers late in the queue, so Sentry / structured
logging / test-runner hooks still observe non-peer-disconnect errors
before vinext's sync re-throw aborts iteration), and the Symbol.for
first-loaded-wins caveat for the multi-version case.
Refactor: collapse the duplicated `(err as Error & { code }).code` casts
into a single `peerDisconnectCode` helper that returns the matched code
or undefined, so the debug log path reuses it without recasting.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(dev): re-hoist socket-error backstop to module load (configureServer too late)
The previous attempt to address bonk's review by moving install back
into configureServer was wrong — it didn't restore working behavior:
$ VINEXT_DEBUG_SOCKET_ERRORS=1 vp dlx vinext@455a61b dev
...
GET /stage/oliver 200 in 1.1s
node:events:487
throw er; // Unhandled 'error' event
Error: read ECONNRESET
...
No `[vinext] dev socket-error backstop installed` startup line. The
function never ran. Cause: in vite-plus's plugin lifecycle,
`server.httpServer` is null at the moment configureServer fires, so
the `if (server.httpServer)` middleware-mode guard skipped install.
Requests still get served (httpServer is created later) but the
listener was never attached.
Hoist back to module load. To address bonk's "loaded in build/test
contexts too" concern, gate install on:
- `process.env.VITEST === "true"` → Vitest worker imports
- `process.argv` contains "build" → `vinext build` / `vp build`
`process.argv` is read because the CLI entry imports index.ts before
it has a chance to set an env var, and `configResolved` runs too late
for module-load gating.
Updated JSDoc to be honest about the install context, the listener-
ordering implication, the middleware-mode embedder situation, and the
Symbol.for first-loaded-wins caveat.
Refs #905.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(dev): positive-gate socket backstop on argv[2]==='dev'
Replace the negative VITEST/build skip list with a single positive
check: install only when argv[2] === "dev". Matches `vinext dev`,
`vp dev`, `vite dev`, and any CLI following the "<bin> dev"
convention. Everything else — build, Vitest workers, library
embedders with a custom runner — skips install, so genuine
peer-disconnect errors surface normally in those contexts.
Cleaner default: no listener unless we're confident this is a dev
server invocation.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(dev): gate socket backstop on Vite's command==='serve'
Replace argv-sniffing with the canonical signal: Vite's `config()`
hook receives `{ command: "serve" | "build" }` directly. Install
the backstop only when `command === "serve"`. Works identically for
`vinext dev`, `vp dev`, `vite dev`, and library embedders that call
`createServer` themselves — anywhere Vite considers itself a dev
server.
`config()` runs before `configureServer` (so before httpServer
matters) and before the dep-optimization or full-reload events that
broke the earlier `httpServer.close`-tied teardown. Symbol.for guard
keeps the install idempotent across server restarts within a session.
Removes:
- Module-load-time install + argv[2] === "dev" check
- VITEST / build env-var negative skip list
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(dev): narrow gate to !isPreview so vite preview skips install
`command === "serve"` covers both `vite dev` and `vite preview` (the
post-build static server). Preview doesn't stream RSC and doesn't
need this guard, so narrow to `command === "serve" && !env.isPreview`.
`vinext start` runs prod-server.ts directly without Vite, so it was
already correctly excluded — `config()` never fires there.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: extend socket-error backstop to vinext start (Next.js parity)
Next.js installs uncaughtException + unhandledRejection handlers in
their router-server unconditionally — no dev/prod gate. Both the
Node.js dev server and the Node.js prod server share the same
process-level error guards. See vercel/next.js
packages/next/src/server/lib/router-server.ts:809-810.
vinext was only guarding the dev path. `vinext start` runs
prod-server.ts directly as a Node HTTP server (used for self-hosted
deploys; Cloudflare Workers prod doesn't load this module — the
runtime owns socket lifecycle there) and had the same theoretical
exposure to peer-disconnect crashes through the pipeline() / fetch()
paths it streams responses through.
Refactor:
- Extract the install function from index.ts into a new
src/server/socket-error-backstop.ts (drop the "Dev" prefix —
no longer dev-only).
- Keep the call from the vinext:config plugin's config() hook,
gated on command === "serve" && !isPreview (covers vinext dev /
vp dev / vite dev / library embedders).
- Add a parallel call at the top of startProdServer() in
prod-server.ts (covers vinext start).
vinext is more conservative than Next.js's log-only handler — we
filter strictly on peer-disconnect codes and sync re-throw the rest,
so genuine bugs still surface. The parity is in *where* we install,
not what we swallow.
Vitest workers and `vinext build` never reach either entry point, so
peer-disconnect errors in those contexts surface normally.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(dev): auto-install socket-error backstop at module load
The Vite config() hook gate (`command === "serve" && !isPreview`)
proved unreliable in vite-plus's lifecycle — the hook didn't fire
(or didn't pass command correctly), and install was silently skipped.
Field reproducer: published 501dd95 had the call site in the bundle
at the right spot, but `VINEXT_DEBUG_SOCKET_ERRORS=1` produced no
startup marker, immediate ECONNRESET crash on first request.
Move the install back to module load — invoked unconditionally as a
side effect when socket-error-backstop.ts is imported. This was the
last shape verified to work via the diagnostic flag.
Drop the import-and-call pattern in index.ts in favor of a
side-effect import (`import "./server/socket-error-backstop.js"`),
which is enough to trigger the auto-install. The import order keeps
the install ahead of every other vinext server code path.
Skip in Vitest workers via `process.env.VITEST === "true"` so
genuine peer-disconnect errors during test runs surface normally.
Build runs are unaffected (short-lived, no peer-disconnect-prone
streams) — matches Next.js's pattern of installing in any
HTTP-serving entry without further gating.
prod-server.ts still calls installSocketErrorBackstop() explicitly
for `vinext start`. Idempotent via Symbol.for guard.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor: call installSocketErrorBackstop directly in index.ts
Remove the side-effect import + auto-install indirection. Just call
the function explicitly at module top-level in index.ts, where it's
obvious. Same observable behavior, clearer code.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: gate socket backstop on NODE_ENV to keep prerender ECONNRESET fatal
Bonk's PR #916 review caught a real corruption bug: the build path
calls startProdServer() during prerender (build/run-prerender.ts:181,
build/prerender.ts:398, :720), so the install fires twice during a
build — once at index.ts module load, once inside startProdServer.
User fetch() calls inside prerendered pages can hit ECONNRESET from
flaky upstream APIs. With the backstop installed, those errors are
silently absorbed instead of crashing the build, producing corrupt
prerendered HTML/RSC output.
Add NODE_ENV gating inside installSocketErrorBackstop:
- Skip if NODE_ENV === "production" → covers vinext build + prerender
- Skip if NODE_ENV === "test" → covers test runners that follow convention
- Skip if VITEST === "true" → kept for Vitest specifically
Vite sets NODE_ENV=production for the build command before plugins
load, so the gate fires correctly. Trade-off: vinext start with
NODE_ENV=production set in shell will also skip install — losing
strict Next.js parity for that path. Acceptable: prod-server's
pipeline() callbacks already handle the streaming case, and the
real-world bug reports are all dev-server.
Also fix the now-stale comment at prod-server.ts:817 that still
referenced the reverted "Vite plugin config() hook" install path,
and document the listener-ordering trade-off more honestly in the
JSDoc — `index.ts` imports synchronously at the top of every user's
vite.config.ts, registering vinext's listener earlier than user /
tooling crash reporters. Sync re-throw on non-peer-disconnect errors
still surfaces the crash but later-registered observers don't see
the event; users who need crash-reporter visibility for those errors
must register their handler before importing vinext.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: bypass socket backstop during prerender via VINEXT_PRERENDER
Replace the install-time NODE_ENV gate (which broke vinext start
parity by skipping installation entirely when NODE_ENV=production)
with a fire-time VINEXT_PRERENDER check inside the listener. The
listener is always installed, but during prerender it re-throws all
errors unconditionally — acting as if no listener were present —
so user fetch() ECONNRESETs during prerender crash the build with
the original stack instead of being silently absorbed into corrupt
prerendered output.
The fire-time check (vs. install-time) is necessary because
index.ts loads at Vite plugin import — well before prerender begins
— and the Symbol.for guard then makes any later install call a
no-op. A static install-time gate can't catch the prerender phase
that follows.
Set VINEXT_PRERENDER=1 in run-prerender.ts at the top of
runPrerender() so the flag covers the entire prerender orchestration
including startProdServer setup. prerender.ts already sets the same
var around its actual render passes; this widens the scope.
Restores Next.js-parity install for vinext start (NODE_ENV gate is
gone). Test-runner skip stays install-time on VITEST / NODE_ENV=test
since those contexts genuinely shouldn't have the listener.
Refs PR #916 review feedback.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: address bonk PR #916 follow-up review
Three issues bonk flagged after the prerender fix landed:
1. Stale comment in prod-server.ts:816-820 — described the NODE_ENV
self-gate that was reverted in b3e8759. Replace with one that
describes the current behavior: idempotent install via Symbol.for
guard, kept here for entry points that load prod-server without
index.ts (Next.js parity), prerender bypass is fire-time via
VINEXT_PRERENDER not install-time.
2. prerender.ts's finally blocks `delete VINEXT_PRERENDER` clobbers
any value set by the caller. After prerenderApp returns inside
runPrerender (which sets the flag for the whole orchestration),
the var is deleted instead of restored to runPrerender's "1",
leaving narrow gap windows around shared-server close where
ECONNRESET would be absorbed instead of re-thrown. Save the
prior value and restore it. Doesn't cause prerender output
corruption (rendering already complete by these gaps) but it's
the correct hygiene.
3. Document the orchestrator-induced ECONNRESET trade-off in the
backstop's JSDoc — unconditional re-throw during prerender
means a hung-route + orchestrator timeout surfaces the build
crash as ECONNRESET rather than the route's own error.
Acceptable but worth calling out so debuggers know to set
VINEXT_DEBUG_SOCKET_ERRORS=1 to disambiguate.
Plus minor JSDoc wording nit: the "Symbol.for guard prevents
re-install" line was load-bearing in the wrong way — the relevant
point is timing, not de-dup. Reworded.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: address bonk PR #916 follow-up review (round 2)
- run-prerender.ts: save/restore VINEXT_PRERENDER to avoid leaking the
env var into Vitest workers (mirrors prerender.ts pattern).
- index.ts: correct stale install-site comment — install gate is
Vitest-only; build/prerender bypass is fire-time via VINEXT_PRERENDER.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test: focused unit test for socket-error-backstop predicate + install gate
Addresses bonk PR #916 review item #3 (carried over). Extracts
'peerDisconnectCode' as an exported pure predicate so the matching
logic can be tested in isolation without process-state mutation, and
adds a thin 'isSocketErrorBackstopInstalled()' query so the test can
verify the Vitest install-gate short-circuit fires in worker processes.
Tests cover:
- ECONNRESET / EPIPE / ECONNABORTED accepted, other codes rejected
- non-Error / null / primitive reasons handled (unhandledRejection
fires with arbitrary reason values)
- Install gate skips Vitest workers (process.env.VITEST === 'true')
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: ask-bonk[bot] <ask-bonk[bot]@users.noreply.github.com>
* shim: rewrite buildGoogleFontsUrl on top of the new build-url helper
Replace the inline URL builder in shims/font-google-base.ts with a thin
wrapper around the pure buildGoogleFontsUrl helper from PR 1
(packages/vinext/src/build/google-fonts/build-url.ts). The shim still
takes a FontOptions object and still returns a CSS URL, so external
callers and the existing 84 unit tests are unaffected.
Two visible behaviour changes:
1. Empty options no longer emit `:wght@100..900`. They emit no axis
segment at all, which makes Google return the default static face
(HTTP 200) for every font, including narrow-axis families like Sen
that previously got HTTP 400. This is the dev fallback only; the
build plugin always pre-resolves the real axis range from metadata
in production.
2. Italic-only requests no longer drop the ital axis. Pre-fix the outer
guard `weights.length > 0 || styles.length > 0` entered the block
but the inner branch only handled the wght path, so a call like
`Inter({ style: ['italic'] })` produced `family=Inter&display=swap`
with no italic anywhere in the URL. The shim now derives an ital
array from style and falls back to weight '400' when ital is set
without an explicit weight, so Google has somewhere to attach the
ital axis in the URL.
The shim deliberately does not import font-data.json or validate.ts: a
388 KB metadata file in the Worker bundle would dwarf the rest of the
shim, and the production path already has the metadata-aware variant.
Refs #885.
* plugin: validate options against metadata, surface HTTP errors as build errors
Replace the inline URL builder in plugins/fonts.ts with the pipeline added
in PR 1: validateGoogleFontOptions parses the call's options against the
bundled font metadata, getFontAxes resolves the actual `wght` range for
variable fonts, and buildGoogleFontsUrl emits the URL.
Three behaviour changes:
1. Variable fonts called with no `weight` now request the font's real
axis range (Sen 400..800, Inter 100..900) instead of a hardcoded
100..900. This is the user-visible fix for issue #885: Sen returns
HTTP 200 with all five face files instead of HTTP 400.
2. Validation errors surface as build errors with the source file path
attached. Unknown family, missing weight on a static font (Anton,
Archivo Black, etc.), unknown weight, mixing 'variable' with explicit
weights, axes on non-variable fonts, invalid display values, and
missing/unknown subsets are now all caught at transform time. Pre-fix
these silently produced URLs that Google rejected at request time.
3. HTTP non-2xx responses from Google are now distinguished from network
errors. A 4xx/5xx is wrapped in GoogleFontsHttpError and surfaced
with the failing URL plus the response body, because pre-fix the
silent `catch { return; }` skipped self-hosting and let the runtime
CDN path retry the same broken URL in the browser. Network errors
(offline dev) still fall through silently to keep `vp dev` usable
without a connection.
The fontCache key is the URL, so existing on-disk caches under
`.vinext/fonts/<hash>/` will be stale for affected fonts after this
change. One refetch per font on the next build.
Refs #885.
* tests: regression coverage for the #885 narrow-axis bug and validator throws
Five new tests in tests/font-google.test.ts plus subset additions to
existing fixtures whose Inter() / Roboto() calls were missing them.
Shim regressions:
- buildGoogleFontsUrl with empty options must not emit `:wght@100..900`
- buildGoogleFontsUrl with style-only options must keep the ital axis
visible in the URL
Plugin regressions:
- Sen() with no weight must fetch `:wght@400..800`, not `:wght@100..900`
- unknown families throw a build error with the file path attached
- non-variable fonts called without an explicit weight throw at build
time instead of silently emitting a broken URL
- HTTP 4xx/5xx from Google surfaces as a build error containing the URL
and the response body
- network errors (DNS, ECONNREFUSED, AbortError) still fall through
silently so offline dev keeps working
The existing plugin transform tests passed `Inter({ weight: '400' })`
without subsets; the validator now treats that as a missing-subsets
error (matches Next.js behaviour), so those fixtures gain
`subsets: ['latin']`. The two nested-brace regression tests still
exercise the parser's balanced-brace logic but use a benign
`_placeholder` field instead of `axes: { wght: 400 }`, which is
semantically invalid for Inter under the new validator.
Refs #885.
* address google font review feedback
* fix(dev): backstop uncaughtException for socket disconnects pipe() misses
PR #911 attached an error listener to every connection socket, which
fixes the direct res.socket case. But Node's pipe() machinery has a
separate re-emission path: when a Readable source errors and the
destination has no error listener, pipe() emits the error on the
destination — and that destination is not always the connection
socket. Two real call sites trigger this:
- fromWeb(fetch().body).pipe(res) in proxyExternalRewriteNode, where
the source is the upstream fetch body, not the inbound socket
- streaming surfaces inside @vitejs/plugin-rsc that own their own
pipe topology
Outbound sockets created by fetch() also never fire 'connection' on
server.httpServer, so they sit completely outside the existing guard.
Add a process-level uncaughtException handler scoped to the dev server
that drops only peer-disconnect codes (ECONNRESET, EPIPE,
ECONNABORTED) and re-throws everything else on nextTick to preserve
Node's default crash behavior for real errors. Removed on httpServer
'close' so it doesn't leak across server restarts.
Refs #905.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: address bonk review on uncaughtException backstop
Three issues from PR #913 review:
1. (Blocker) The process.nextTick(() => throw err) re-throw created an
infinite loop, not a crash: the listener is still installed when the
nextTick callback fires, so it catches the re-thrown error and
schedules another, forever — silently swallowing genuine bugs.
Replace with a synchronous throw inside the handler, which Node
treats as fatal and produces the same observable as no listener
(stack to stderr, non-zero exit).
2. Skip installation entirely in middleware mode (httpServer is null).
The embedding host owns process-level handlers and there's no
reliable teardown hook to remove ours, so installation would leak.
3. Mirror the same filter onto unhandledRejection — peer-disconnect
errors from outbound fetch() and pipe re-emissions can surface
through either channel depending on the async path.
Verified locally: sync throw inside the handler crashes Node with the
original stack and a non-zero exit code; the previous nextTick pattern
loops indefinitely on the same input.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(app-router): flatten Error.cause chain into dev-server error output
Vite's dev-server "Internal server error:" formatter
(buildErrorMessage in vite-plus-core) builds output from err.message
and err.stack only, silently dropping err.cause. A wrapper like
`new Error("Failed query", { cause: pgError })` would surface in the
dev console as just "Failed query" — the actual postgres ECONNREFUSED,
role-missing, or workerd socket error in .cause was invisible.
This commit adds flattenErrorCauses(err), called at the App Router RSC
handler boundary before any error escapes to Vite. It walks .cause
(depth-capped, cycle-safe) and embeds each cause's message into
err.message and stack frames into err.stack as `at` lines (so they
survive Vite's cleanStack /^\s*at/ filter). Marked idempotent via a
non-enumerable symbol so Node's util.inspect output is unaffected and
prod logs that already format causes correctly are not duplicated.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: address bonk review feedback
1. Gate flatten on NODE_ENV !== "production" at the call site. Without
this, prod-server.ts:1106's `console.error("[vinext] Server error:", e)`
would render the cause twice — once in the synthesized message line,
once in util.inspect's native [cause]: block. Vite build-time-replaces
NODE_ENV, so the prod bundle compiles the catch branch out entirely.
2. Replace the marker-enumerability test with one that actually invokes
util.inspect and asserts the marker symbol is invisible to it.
3. Wrap the three mutating operations (defineProperty, .message =,
.stack =) in try/catch so frozen / non-extensible errors are left
untouched rather than masking the user's real failure with a
TypeError from inside the helper.
4. Switch FLATTENED_MARKER from Symbol.for(...) to module-private
Symbol(...) — there's no cross-module coordination needed.
Add a regression test for the frozen-error case.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Node throws on unhandled 'error' events on sockets. When the browser
drops a connection mid-response (HMR triggers a reload while an RSC
stream is still flushing), the next res.write surfaces ECONNRESET on
res.socket with no listener attached and takes down `bun dev`.
Attach a no-op error listener on every connection — same guard Vite's
HMR server and Next.js install for the same reason. Closes#905.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(app-router): block javascript: URLs in router.push/replace/prefetch
router.push("javascript:alert(1)") currently runs the script. _appRouter.push,
.replace, and .prefetch in shims/navigation.ts forward the href straight to
navigateClientSide, where isExternalUrl matches the javascript: scheme and
falls through to window.location.assign, which executes the URL. router-derived
hrefs (URL params, user content, query state) become an XSS vector.
Next.js blocks dangerous URI schemes at the router boundary and throws
"Next.js has blocked a javascript: URL as a security precaution." See
packages/next/src/client/components/app-router-instance.ts:343,400,440,458 in
the canary tree. Vinext's url-safety.isDangerousScheme already covers
javascript:/data:/vbscript: with the same obfuscation handling Next.js uses,
and Link and Form already gate on it; the App Router programmatic surface was
the remaining gap.
Add assertSafeNavigationHref at the top of push/replace/prefetch, before the
isServer short-circuit so SSR callers fail loudly too. Throw an Error with
the verbatim Next.js message so consumer error tooling can match across both
frameworks.
Test: tests/router-javascript-urls.test.ts ports the assertions from
.nextjs-ref/test/e2e/app-dir/javascript-urls/javascript-urls.test.ts down to
unit scope, covering javascript:/data:/vbscript:, uppercase, embedded tabs,
leading whitespace, and a safe-URL no-throw guard for each method.
* test(router): split ported vs vinext-only dangerous-scheme cases
The header said "Ported from Next.js" but data: and vbscript: are vinext
extensions, not in the upstream e2e suite. Add a Coverage split note that
attributes each scheme: javascript: + obfuscation variants come from
test/e2e/app-dir/javascript-urls/javascript-urls.test.ts; data: and vbscript:
ride on top via shims/url-safety.isDangerousScheme.
* fix app router dangerous redirect gaps
* test address dangerous URL review nits
useSelectedLayoutSegment(parallelRoutesKey) returned the first segment for every route key. That matches children routes, but it misreports nested named parallel routes such as a slot path with members/profile by returning members instead of the active leaf profile.
The root cause was treating the array returned by useSelectedLayoutSegments() as having the same reduction rule for children and named slots. Match Next.js by keeping first-segment behaviour for children and using the final segment for non-children parallel route keys.
Adds a nested @team fixture route that mirrors Next.js parallel-routes-use-selected-layout-segment coverage.
* vendor Google Fonts metadata from Next.js
Adds packages/vinext/src/build/google-fonts/font-data.json (1911 entries,
388 KB pretty-printed) plus a typed re-export wrapper. The metadata
enumerates each Google Font's available weights, styles, variable axes, and
preloadable subsets, and is the source of truth a faithful next/font/google
port needs to encode the right URL for variable fonts and reject invalid
options at build time.
Today vinext hardcodes :wght@100..900 in both the shim runtime URL builder
and the build-time plugin, which produces HTTP 400 from Google for fonts
whose wght axis is narrower (Sen 400..800, Anton single 400). Without
metadata there is no way to emit the correct axis range, validate weights
against the font's real options, or auto-disable preload for fonts with no
preloadable subsets.
The JSON itself is consumed only at build time and during dev. Production
Workers run the self-hosted CSS injected by the build plugin and never read
this file. The pretty-printed shape matches the upstream layout so future
refreshes from canary remain reviewable.
This commit only vendors the data and types. URL pipeline and validator
land in the next two commits.
Refs #885.
* port Google Fonts URL pipeline from Next.js
Adds three pure helpers under packages/vinext/src/build/google-fonts:
sortFontsVariantValues (numeric variant comparator), buildGoogleFontsUrl
(URL assembler), and getFontAxes (metadata-driven axis resolver). Each is a
direct port of the matching module in vercel/next.js packages/font/src and
has no defaults of its own. Defaults live in the validator (next commit).
This is the layer that translates a validated options object into the URL
shape Google Fonts CDN actually accepts. Sorting matters because Google
rejects out-of-order variant lists with HTTP 400. The metadata-driven axis
resolver is what lets a Sen({}) call produce :wght@400..800 instead of the
broken :wght@100..900 default.
No consumer wired up yet. The shim and plugin still call the old hardcoded
URL builders; the integration lands in PR 2.
Tests: 21 new tests across the three modules. Each helper is exercised in
isolation against the vendored metadata, including the regression case
from #885 (variable Sen resolves to wght 400..800) and the italic-only
branch that vinext currently drops.
Refs #885.
* port Google Fonts options validator from Next.js
Adds validateGoogleFontOptions, the parse-once boundary for next/font/google
calls. Mirrors Next's validate-google-font-function-call.ts, dropping the
SWC-coupled (functionName, fontFunctionArgument) signature in favour of
(fontFamily, options). Returns ValidatedGoogleFontOptions, a type whose
existence proves the input was rejected if Google would have rejected it.
Behavior matches Next.js: throws on unknown family, unknown weight, mixing
'variable' with explicit weights, axes on non-variable fonts, axes without
weight 'variable', invalid display, unknown subsets, preload with no
subsets. Defaults missing weight to ['variable'] for variable fonts, and
auto-disables preload for fonts with no preloadable subsets.
This closes the loop on the URL pipeline added in the previous commit.
Together with getFontAxes and buildGoogleFontsUrl, vinext now has a
metadata-driven path from caller options to a valid Google Fonts URL.
The shim and plugin still build URLs the old way; PR 2 wires this through.
Tests: 16 new tests covering every throw branch and every default branch,
plus an index.ts barrel that the future plugin import will use. The
"auto-disable preload" test pins on Playwrite AR Guides, which has empty
subsets in upstream metadata; if a future canary refresh adds a subset to
that family the test will need a different fixture.
Refs #885.
* fold attribution into font-metadata header, drop unused exports
Drop NOTICE.md and the index.ts barrel, demote four type aliases from
exports to module-internal. Knip flagged the index file as unused (no
consumer until PR 2) and the type aliases as unused exports for the same
reason; YAGNI says wait for the consumer rather than ship dead public API.
Vercel's MIT copyright on font-data.json is preserved in the
font-metadata.ts header instead of in a sibling NOTICE.md, matching the
in-tree pattern Next.js uses for vendored third-party files.
Tests: vp run knip exits 0, 37 google-fonts tests still pass.
* address PR 892 review: document subsets parity, harden preload-disable test
`validateGoogleFontOptions` rejects `subsets: []` with `preload: true`
where Next.js silently accepts it (Next uses a truthy check on
`subsets`, vinext defaults to `[]` and checks `length`). The behavior
is intentional (an empty subsets array with preload enabled is always
a caller mistake), but undocumented divergence from a faithful port
invites a future "fix back to upstream" PR. Annotate the divergence
at the throw site.
Auto-disable-preload test pins on `Playwrite AR Guides` having an
empty subsets array in the bundled metadata. If a metadata refresh
ever adds a subset to that family, the family-specific test silently
flips into a false positive. Add an invariant test asserting the
bundled metadata still contains at least one family with no
preloadable subsets, so loss of branch coverage fails CI loud.
Bots throw "max_tokens not supported, use max_completion_tokens" on
1.4.6 with gpt-5.x reasoning models. opencode 1.4.6 predates the
cf-ai-gateway plugin's chat.params hook (PR #22864, landed in 1.4.7),
which strips maxOutputTokens for OpenAI reasoning models so the
@ai-sdk/openai-compatible default no longer leaks the rejected field.
The earlier ProviderInitError on 1.14.x was a separate regression in
opencode's npm install path: the major bump introduced loadOptions(dir)
via @npmcli/config inside Npm.add, which fails on CI runners and bubbles
up as InstallFailedError, then gets re-wrapped at provider.ts:1522 as
ProviderInitError with the original cause swallowed by the session
error path. Other Cloudflare repos (workers-sdk, workerd, kumo) hit the
same regression on anthropic and pinned 1.4.6 / 1.2.27 to dodge it.
1.4.11 is the last 1.4.x release: it has the chat.params max_tokens
patch and predates the loadOptions install regression. Same
ai-gateway-provider 3.1.2, same @ai-sdk pins as 1.4.6, so the install
path stays the known-good arborist.reify call shape that works for
workers-sdk + anthropic on 1.4.6.
Verified locally with opencode 1.14.25 + cf-ai-gateway/openai/gpt-5.4 +
fake creds: empty-cache short-circuit and loadOptions both reproduce
the silent ProviderInitError. 1.4.11 lacks both code paths.
Every bonk and bigbonk run since opencode 1.14.25 throws
UnknownError: ProviderInitError during cf-ai-gateway SDK init,
regardless of model. Verified across gpt-5.5 (#898), gpt-5.4 (#900),
and the throw fires before any per-model code path runs.
workers-sdk hit the same regression and pinned opencode_version to
1.4.6 with an inline comment naming ProviderInitError as the cause.
Several other Cloudflare repos pin 1.2.27 / 1.4.6 for the same
reason. vinext is the only Cloudflare repo running OAI through
cf-ai-gateway, so the OAI-specific path stayed unobserved until #898
re-tried it on 1.14.25.
Pinning to 1.4.6 here reuses workers-sdk's known-good version. The
gpt-5.4 model from #900 stays; gpt-5.4 predates 1.4.6's bundled
snapshot by over a month, so registry resolution is fine.
bonk and bigbonk currently throw ProviderInitError on every invocation
after the gpt-5.5 switch in #898. The lookup-side regression that #899
patched was masked by the opencode bump (1.14.22 -> 1.14.25) but a
second failure now surfaces during SDK init for cloudflare-ai-gateway.
opencode swallows the underlying cause, and the gpt-5.5 path through
ai-gateway-provider has no working precedent in this repo, so iterating
on it would block PR review indefinitely.
Roll the model back to gpt-5.4, which has a known-good path through
opencode + ai-gateway-provider + Cloudflare AI Gateway, and remove the
opencode.json workaround introduced in #899. Reasoning effort stays at
"xhigh" per James's preference; opencode will fall back to its default
effort if gpt-5.4 doesn't accept it.
Once gpt-5.5 SDK init is fixed upstream (opencode + ai-gateway-provider
+ models.dev cloudflare-ai-gateway entry), we can roll forward again.
* ci(bonk): switch bonk workflow to GPT-5.5 xhigh variant
Updates the bonk workflow to use cloudflare-ai-gateway/openai/gpt-5.5
with reasoning effort variant xhigh, replacing the previous
claude-opus-4-7 model.
https://claude.ai/code/session_012n6RFuqfQGQY7AaayqLcaG
* ci(bonk): extend GPT-5.5 xhigh switch to bigbonk, agent defs, and docs
- bigbonk workflow: cloudflare-ai-gateway/openai/gpt-5.5 with variant xhigh (was claude-opus-4-7 + max)
- viguy and reviewer OpenCode agent definitions: openai/gpt-5.5 (was anthropic/claude-opus-4-7)
- CONTRIBUTING.md: update recommended setup and BigBonk description to GPT-5.5 xhigh
The Next.js tracker workflow and agent are intentionally left on Claude
Opus 4.7.
https://claude.ai/code/session_012n6RFuqfQGQY7AaayqLcaG
* ci(opencode): register openai/gpt-5.5 under cloudflare-ai-gateway
bonk and bigbonk currently throw ProviderModelNotFoundError when
invoked because opencode's bundled models snapshot predates GPT-5.5
(released 2026-04-23) and the cloudflare-ai-gateway entry on
models.dev does not yet list it. opencode resolves
provider.models[modelID] before any network call, so the lookup miss
fires synchronously and the workflow exits non-zero before reaching
the gateway.
opencode merges user-supplied provider.<id>.models into the resolved
registry dict, so registering the entry locally unblocks workflow
invocations without waiting on either an upstream registry merge or
an opencode release that rebundles the snapshot.
Pricing, limits, modalities, and reasoning capability mirror the
direct openai/gpt-5.5 entry from models.dev.
---------
Co-authored-by: Claude <noreply@anthropic.com>
* ci(bonk): switch bonk workflow to GPT-5.5 xhigh variant
Updates the bonk workflow to use cloudflare-ai-gateway/openai/gpt-5.5
with reasoning effort variant xhigh, replacing the previous
claude-opus-4-7 model.
https://claude.ai/code/session_012n6RFuqfQGQY7AaayqLcaG
* ci(bonk): extend GPT-5.5 xhigh switch to bigbonk, agent defs, and docs
- bigbonk workflow: cloudflare-ai-gateway/openai/gpt-5.5 with variant xhigh (was claude-opus-4-7 + max)
- viguy and reviewer OpenCode agent definitions: openai/gpt-5.5 (was anthropic/claude-opus-4-7)
- CONTRIBUTING.md: update recommended setup and BigBonk description to GPT-5.5 xhigh
The Next.js tracker workflow and agent are intentionally left on Claude
Opus 4.7.
https://claude.ai/code/session_012n6RFuqfQGQY7AaayqLcaG
---------
Co-authored-by: Claude <noreply@anthropic.com>