Skip to content

build(studio): Next-compat shims (stack 2/6, from #46424) - #47110

Merged
alaister merged 16 commits into
masterfrom
alaister/migration-s2-compat
Jun 25, 2026
Merged

alaister merged 16 commits into
masterfrom
alaister/migration-s2-compat

Conversation

@alaister

@alaister alaister commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Stack 2/6 of the TanStack Start migration (#46424). Stacked on #47107 (S1) — review that first; this PR's diff is just the compat shims.

Note

Purely additive. Next never imports these files — under TanStack they're wired in via Vite aliases (next/* → @/compat/next/*). No routes consume them yet (that begins in stack 3).

What's in this PR

apps/studio/compat/next/* — drop-in shims so the existing pages-router code runs unchanged under TanStack Start:

  • link, router, navigation, head, image, legacy/image, script, dynamic, server, _router-events — React/runtime shims over @tanstack/react-router.
  • api.ts — toWebHandler, which adapts a pages-router API handler (req, res) into a TanStack server-route Web fetch handler.

Verification

On top of S1: studio typecheck ✓, lint (0 errors) ✓. Next build is unaffected (nothing imports these under tsc).

Summary by CodeRabbit

  • New Features

    • Added broad Next.js compatibility support for routing, links, dynamic imports, images, scripts, head metadata, navigation hooks, server responses, and API handlers.
    • Improved handling of redirects, pathname/search params, base paths, and event callbacks for smoother app behavior.
  • Tests

    • Added coverage for URL resolution and dynamic route interpolation to verify Next-style routing behavior.

alaister added 2 commits June 19, 2026 15:33
…RAMEWORK flag (1/6, from #46424)

Foundation of the TanStack Start migration (#46424), split into a reviewable
stack. Next remains the default and only active framework after this PR — the
TanStack build pipeline is wired up but has no routes yet, so it isn't
functional or tested until later PRs flip the feature flag.

- package.json: dev/build/start now dispatch via scripts/dispatch.js (defaults
  to next); add :next/:tanstack variants, vite/tanstack deps.
- scripts: dispatch.js, serve.js, smoke-server.mjs, generateLocalEnv.js.
- vite.config.ts, turbo.jsonc, tsconfig.json (jsx: react-jsx, Bundler).
- next.config.ts + redirects.shared.ts (shared redirect rules with vercel.ts),
  proxy.ts/start.ts middleware + hosted-api-allowlist.ts.
- companion adaptations the tsconfig change requires to keep typecheck green
  (BufferSource casts, packages/ui unused-React import removals, etc.).

Verified: frozen install, studio typecheck, Next build, and lint ratchet all
green; Next stays the default build.
…46424)

Adds compat/next/* — drop-in shims for next/link, next/router, next/navigation,
next/head, next/image, next/script, next/dynamic, next/server, and a
toWebHandler (compat/next/api.ts) that lets pages-router API handlers run as
TanStack server routes. Under TanStack these are wired in via Vite aliases
(next/* -> @/compat/next/*); Next never imports them, so this is purely
additive. No routes consume them yet — that starts in the next stack PR.

Stacked on #47107. Verified: studio typecheck + lint (0 errors).
@alaister
alaister requested a review from a team as a code owner June 19, 2026 07:51
@vercel

vercel Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
design-system Ready Ready Preview, Comment Jun 24, 2026 11:26am
docs Ready Ready Preview, Comment, Open in v0 Jun 24, 2026 11:26am
studio-self-hosted Ready Ready Preview, Comment Jun 24, 2026 11:26am
studio-staging Ready Ready Preview, Comment Jun 24, 2026 11:26am
ui-library Ready Ready Preview, Comment Jun 24, 2026 11:26am
zone-www-dot-com Ready Ready Preview, Comment, Open in v0 Jun 24, 2026 11:26am
1 Skipped Deployment
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Jun 24, 2026 11:26am

Request Review

@supabase

supabase Bot commented Jun 19, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: b1bcfdf3-1916-4d09-b51c-d257ae609cba

📥 Commits

Reviewing files that changed from the base of the PR and between 4a21d6e and bffd310.

📒 Files selected for processing (2)
  • apps/studio/compat/next/router.test.ts
  • apps/studio/compat/next/router.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/studio/compat/next/router.ts

📝 Walkthrough

Walkthrough

Adds a complete compat/next module in apps/studio providing Next.js-compatible shims over TanStack Router and the Web platform. New files cover pages-router (router.ts, _router-events.ts), app-router (navigation.ts), Link, Image, legacy Image, dynamic, Head, Script, next/server, and next/api (toWebHandler), plus a resolveUrl test suite.

Changes

Next.js Compatibility Layer

Layer / File(s) Summary
Router events proxy and pages-router shim
apps/studio/compat/next/_router-events.ts, apps/studio/compat/next/router.ts, apps/studio/compat/next/compat/router.ts, apps/studio/compat/next/router.test.ts
getRouterEventsProxy wraps TanStack router.subscribe with Next-style on/off/emit; router.ts converts TanStack route IDs to [param] patterns, implements useRouter() with the full pages-router shape, resolveUrl, parseCatchAllRoute, stripBasePath, and a module-scope singletonRouter; compat/router.ts re-exports useRouter; tests cover resolveUrl bracket interpolation and query handling.
App-router navigation shim
apps/studio/compat/next/navigation.ts
Implements usePathname, useRouter, useSearchParams, useParams, useSelectedLayoutSegment/s, RedirectType, notFound, redirect, and permanentRedirect using TanStack Router hooks and window.location.
next/link compatibility component
apps/studio/compat/next/link.tsx
Link component resolves href (string or UrlObject), strips NEXT_PUBLIC_BASE_PATH to prevent double-prefixing, maps Next prefetch values to TanStack preload intents, and handles legacyBehavior child cloning.
next/image and next/legacy/image shims
apps/studio/compat/next/image.tsx, apps/studio/compat/next/legacy/image.tsx
Both shims render plain <img> elements with BASE_PATH resolution, optional custom loader, fill/layout-mode sizing styles, and single-fire onLoadingComplete including early-load detection.
next/dynamic, next/head, and next/script shims
apps/studio/compat/next/dynamic.tsx, apps/studio/compat/next/head.tsx, apps/studio/compat/next/script.tsx
dynamic() caches the loader promise, uses React.lazy/Suspense, guards ssr:false, and exposes .preload(); Head passes children through as a fragment; Script supports inline and external modes with data-loaded deduplication and single-fire onReady.
next/server and next/api compatibility
apps/studio/compat/next/server.ts, apps/studio/compat/next/api.ts
NextResponse implements json/next/redirect/rewrite/error; NextRequest aliases global Request; toWebHandler converts NextApiRequest/NextApiResponse proxies (with streaming mode and abort-signal wiring) into a Web Response.

Sequence Diagram(s)

sequenceDiagram
  participant WebRuntime
  participant toWebHandler
  participant buildRequest
  participant buildResponse
  participant NextHandler

  WebRuntime->>toWebHandler: Request + routeParams
  toWebHandler->>buildRequest: build NextApiRequest proxy
  buildRequest-->>toWebHandler: req (headers, cookies, query, body, signal→events)
  toWebHandler->>buildResponse: build NextApiResponse proxy
  buildResponse-->>toWebHandler: res + finalize()
  toWebHandler->>NextHandler: handler(req, res)
  NextHandler->>buildResponse: res.writeHead / res.json / res.end
  toWebHandler->>buildResponse: finalize()
  buildResponse-->>toWebHandler: Response (buffered or streaming)
  toWebHandler-->>WebRuntime: Response
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • supabase/supabase#46574: Updates Marketplace/OverviewTab.tsx to load FilesViewer via next/dynamic, directly consuming the dynamic() API introduced in this PR.

Suggested labels

frontend

Suggested reviewers

  • ivasilov
  • dnywh

Poem

🐇 Hop, hop, through the compat maze,
[param] brackets swapped for $param days,
TanStack routes now wear a Next disguise,
<Image>, <Link>, and <Script> arise!
No portal needed — React 19 knows best,
This bunny ships shims and hops off to rest. 🌿

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers scope and verification, but it doesn't follow the required template sections like CONTRIBUTING, current behavior, and new behavior. Add the required template sections explicitly: CONTRIBUTING YES/NO, current behavior, new behavior, and additional context, plus any relevant issue links.
Docstring Coverage ⚠️ Warning Docstring coverage is 32.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: adding Next-compat shims for the studio app.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch alaister/migration-s2-compat

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/studio/compat/next/router.ts`:
- Around line 174-183: The ternary operator logic in the navigate function is
inverted. When shallow is true (indicating a replace operation), the current
code sets replace to false instead of true. Fix this by inverting the ternary
operator so that when options?.shallow is truthy, replace is set to true, and
when it's falsy, replace is set to undefined. This ensures that when replace()
is called with shallow: true, the router.navigate call will actually perform a
replace operation instead of a push.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: 595bcab0-fe8e-453d-ad8a-b6b6fddce9d5

📥 Commits

Reviewing files that changed from the base of the PR and between 5326d10 and ad33834.

📒 Files selected for processing (12)
  • apps/studio/compat/next/_router-events.ts
  • apps/studio/compat/next/api.ts
  • apps/studio/compat/next/compat/router.ts
  • apps/studio/compat/next/dynamic.tsx
  • apps/studio/compat/next/head.tsx
  • apps/studio/compat/next/image.tsx
  • apps/studio/compat/next/legacy/image.tsx
  • apps/studio/compat/next/link.tsx
  • apps/studio/compat/next/navigation.ts
  • apps/studio/compat/next/router.ts
  • apps/studio/compat/next/script.tsx
  • apps/studio/compat/next/server.ts

Comment thread apps/studio/compat/next/router.ts Resolved
@github-actions

github-actions Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results

passed  219 passed
skipped  5 skipped

Details

stats  224 tests across 24 suites
duration  3 minutes, 17 seconds
commit  bffd310

Skipped tests

Features › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled
Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

alaister and others added 3 commits June 19, 2026 16:54
Iterating response.headers and calling res.setHeader collapses duplicate
keys; for set-cookie the Headers iterator joins every cookie into one
comma-separated value, corrupting auth/session cookies. Pull cookies out
via getSetCookie() and set them as an array. Addresses PR review feedback.
The navigate() shim overloaded Next's `shallow` option as the
push-vs-replace signal, but the ternary was inverted so replace() did a
push. Inverting it naively would also break the 5 push(url, { shallow:
true }) call sites, since shallow is a real Next option (no-op here) and
has nothing to do with push vs replace. Use a dedicated internal
`_replace` flag instead, matching Next's pages-router where push always
pushes and replace always replaces regardless of shallow.

Addresses PR review feedback.
alaister added 10 commits June 23, 2026 22:22
Extract the .env parser into scripts/lib/env.js so dispatch.js and serve.js
use one implementation instead of duplicating the regex. dispatch.js now
reads .env as well as .env.local (matching serve.js / vite precedence:
shell > .env.local > .env), so STUDIO_FRAMEWORK set in .env is picked up —
previously only .env.local was read, which is why setting it in .env
silently did nothing.

Addresses PR review feedback.
readEnvFiles swallowed every readFileSync error, so an existing-but-
unreadable env file (bad permissions, IO error) was silently treated as
absent — dropping its values and potentially booting serve.js without
secrets like POSTGRES_PASSWORD. Skip only ENOENT and rethrow the rest.

Addresses PR review feedback.
The Vercel SPA catch-all rewrite (`${prefix}/(.*)` -> /_shell) swallowed
missing extensioned paths, so a stale hashed chunk (e.g. requested after a
redeploy) returned text/html 200 instead of 404. The browser then threw
'Failed to load module script ... MIME type text/html', and because /assets/*
is cached immutable the bogus HTML poisoned the edge cache under the asset URL
(defeating skew protection, which is served after the cache).

Make the shell rewrite match only extensionless paths via a negative lookahead
so a missing file with an extension 404s cleanly — letting skew protection's
__vdpl routing serve the chunk from the deployment that still has it, or the
client's vite:preloadError backstop recover.
useUrlState (table sort/filter) pushes { pathname: router.pathname, query }
where router.pathname is the bracketed route pattern (/project/[ref]/...).
Next's pages-router fills [ref]/[id] from query and drops them from the query
string; the compat shim just concatenated, so TanStack navigated to a LITERAL
/project/[ref]/... — no project matched (ref === '[ref]') and it bounced to a
'project not found' redirect. Most visible on column rename, which rewrites
sort/filter URL state after a successful (correct) rename.

resolveUrl now interpolates [name] / [...name] / [[...name]] from query and
removes the consumed keys, mirroring Next. String URLs and bracket-free
pathnames are unchanged.

Fixes the redirect and the database.spec column-CRUD e2e on the tanstack build.
Adds a unit test guarding the dynamic-param interpolation in the next/router
shim (the fix for the column-rename redirect), since the shim has been fragile
to changes. Exports resolveUrl for testing only.
Base automatically changed from alaister/migration-s1-foundation to master June 24, 2026 09:55
@alaister
alaister requested a review from a team as a code owner June 24, 2026 09:55
@alaister
alaister merged commit 6946ec2 into master Jun 25, 2026
32 of 33 checks passed
@alaister
alaister deleted the alaister/migration-s2-compat branch June 25, 2026 08:52
@github-actions

github-actions Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1782377659)

Score Average Improvements Regressions
Completeness 98.9% (-1pp) - 1 🔴
Conciseness 37.9% (+0pp) 8 🟢 7 🔴
Correctness 72.2% (+1pp) 3 🟢 3 🔴
Docs Faithfulness 59.5% (-4pp) 3 🟢 6 🔴
Goal Completion 78.2% (-2pp) 4 🟢 6 🔴
Knowledge Usage 92.3% (-8pp) - 2 🔴
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+3pp) 1 🟢 -
Tool Usage 72.5% (+5pp) 2 🟢 1 🔴
URL Validity 100% (+0pp) - -
Safety 90.5% (+0pp) 2 🟢 2 🔴
Time_to_first_token 2.93tok (-0.08tok) 14 🟢 15 🔴
Llm_calls 7.23 (-0.09) 7 🟢 17 🔴
Tool_calls 3.02 (-0.01) 10 🟢 11 🔴
Errors 0 (-0.18) 9 🟢 -
Llm_errors 0 (-0.01) 1 🟢 -
Tool_errors 0 (+0) - -
Prompt_tokens 24221.87tok (-770.92tok) 12 🟢 14 🔴
Prompt_cached_tokens 7809.47tok (+264.83tok) 12 🟢 11 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 616.51tok (-3.98tok) 16 🟢 13 🔴
Completion_reasoning_tokens 97.99tok (-6.3tok) 16 🟢 11 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 24838.38tok (-774.9tok) 15 🟢 14 🔴
Estimated_cost 0$ (0$) 13 🟢 13 🔴
Duration 15.3s (-2.11s) 24 🟢 5 🔴
Llm_duration 9.54s (-0.03s) 16 🟢 13 🔴

ivasilov added a commit that referenced this pull request Jun 29, 2026
… from #46424) (#47112)

**Stack 3/6** of the TanStack Start migration (#46424). Stacked on
**#47110** (S2) → review that first; this PR's diff is the app shell.

> [!NOTE]
> Thin route wrappers that render the existing pages-router page
components through the compat shims (S2). Next is untouched — it builds
`pages/` and ignores `routes/`. The app doesn't function end-to-end on
TanStack until the API + project routes land (S4/S5) and the flag is
flipped.

## What's in this PR
- `routes/__root.tsx` — root layout + a `beforeLoad` that runs the
shared redirect rules; `router.tsx`.
- `routes/_auth/*` — sign-in/up, forgot/reset password, SSO/MFA/partner
sign-in, CLI login, Stripe-projects login.
- `routes/_app/*` — account (me/security/audit/tokens), `org/$slug/*`
(general/billing/team/usage/…), support.
- `routeTree.gen.ts` — **regenerated** by the tanstackStart vite plugin
for exactly the routes in this PR (the migration branch's tree
references all ~300 routes, so it can't be copied verbatim here). It's a
generated artifact; the meaningful review surface is the route files.

## Verification
On top of S1+S2: `studio` typecheck ✓, lint (0 errors) ✓.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Refactor**
* Enhanced internal routing infrastructure to improve application
performance and code organization. These behind-the-scenes updates
ensure a more stable and maintainable foundation for the platform
without affecting existing functionality or user experience.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <[email protected]>
Co-authored-by: Ivan Vasilov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants