Files
supabase/apps/studio/lib/internal-url.ts
Alaister YoungandAlaister Young e395e057cf [FE-5108] (part 6) chore(studio): remove next/link shim and Vite alias (#54309)
Part 6 (final) of a 6-PR stack migrating all `next/link` imports in
`apps/studio` onto TanStack Router's `Link` (or plain `<a>` for known
external URLs) and removing `compat/next/link.tsx`.

| Part | PR | Scope |
| --- | --- | --- |
| 1 | #54304 | `data/prefetchers/PrefetchableLink.tsx` and
`components/ui/**` |
| 2 | #54305 | `components/layouts/**` and top-level shell components |
| 3 | #54306 | Database, TableGridEditor, Storage, SQLEditor,
BranchManagement, Branching, Functions, Realtime |
| 4 | #54307 | Integrations, Settings, Observability, LogDrains, Issues,
Linter, Reports, QueryPerformance, QuerySources, ConfigDrift,
DiskManagement, Compute |
| 5 | #54308 | Remaining `components/interfaces/**` (Org, Billing, Auth,
Support, Home, SignIn, ConnectSheet, etc.) |
| **6** | **#54309 ← this PR** | **Remove `compat/next/link.tsx` shim,
Vite alias, and update basePath tests/docs** |

Now that no files in `apps/studio` import `next/link`, deletes
`compat/next/link.tsx` and removes its Vite alias so any future
`next/link` import fails the build.

**Removed:**

- `apps/studio/compat/next/link.tsx`
- `'next/link'` entry from `nextShims` in `apps/studio/vite.config.ts`

**Changed:**

- Moved `apps/studio/compat/next/link-basepath-navigation.test.tsx` to
`apps/studio/lib/navigation-basepath.test.tsx` to keep basePath
navigation coverage for `DynamicLink` and `navigateToUrl`
- Updated `nextCompat()` error text in `apps/studio/vite.config.ts` and
routing docs in `apps/studio/AGENTS.md` to reflect that only
`next/script` remains shimmed
- Cleaned up stale `next/link` / `Link shim` comments in
`apps/studio/lib/internal-url.ts`,
`apps/studio/lib/router-url-shape.test.tsx`, and `knip.jsonc`

Addresses
[FE-5108](https://linear.app/supabase/issue/FE-5108/replace-the-nextlink-shim-with-tanstack-link)

## To test

- [ ] Confirm `git grep -E 'next/link|compat/next/link' apps/studio
knip.jsonc` returns zero matches
- [ ] Confirm Studio typecheck, ESLint ratchet, Knip, production Vite
build, and Vitest suite pass
- [ ] Spot-check `apps/studio/lib/navigation-basepath.test.tsx` and
`apps/studio/lib/router-url-shape.test.tsx`

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 17:51:56 +08:00

168 lines
8.0 KiB
TypeScript

// Shared URL-splitting for TanStack <Link> callers and navigateToUrl.
//
// TanStack's `to` is a route-pattern *path*; query params and hash must be
// passed separately via `search` / `hash`. Embedding `?query` (or `#hash`)
// inside `to` is not just a matching problem — router-core runs the whole
// `to` string through path interpolation (`interpolatePath` → `decodePath`
// → `decodeSegment` → `sanitizePathSegment`), which percent-DECODES it and
// then strips control characters (`/[\x00-\x1f\x7f]/`). Any `%0A` (newline)
// in a query value is silently deleted — e.g. the Logs Explorer's multi-line
// SQL in the `s` param loses its newlines, gluing `order by timestamp desc`
// and `limit 5` into one token. So every internal navigation target must be
// split into { to, search, hash } before it reaches TanStack.
//
// Studio code (and Next's own contract) routinely passes one of three
// URL shapes:
// 1. a relative path like `/project/abc/editor/123?schema=public`
// 2. a same-origin absolute URL produced by `new URL(...).toString()`,
// e.g. `http://localhost:8082/project/abc/editor/123?schema=public`
// (this is what `buildTableEditorUrl` does)
// 3. a genuinely external URL like `https://supabase.com/docs`.
//
// Split into three parts: pathname, search, hash. Same-origin absolute
// URLs are normalised to a relative path. Cross-origin URLs are left
// alone so TanStack's external-link path handles them.
//
// Same-origin is not enough on its own, though. Next only treats an
// *absolute* URL as local when it is same-origin AND under the basePath
// (`isLocalURL` + `hasBasePath`). With `basePath: '/dashboard'` on
// supabase.com, `https://supabase.com/docs/...` is a different app on the
// same origin. Normalising it to `/docs/...` would make TanStack prefix its
// basepath (`/dashboard/docs/...`), so it is returned untouched like a
// cross-origin URL. Relative inputs are always local, as in Next.
//
// basePath quirk: TanStack's `to` is **basepath-relative** — given
// `basepath: '/dashboard'` and `to: '/foo'`, TanStack builds the href
// `/dashboard/foo`. Next's contract treats `href` as the **full path
// from app root including basePath**, and studio code routinely
// pre-prefixes BASE_PATH (e.g. `buildTableEditorUrl` calls
// `new URL(`${BASE_PATH}/project/.../editor/...`, location.origin)`).
// Forwarding the BASE_PATH-prefixed pathname as `to` makes TanStack
// double-prefix it (`/dashboard/dashboard/project/...`). Strip the
// basePath when we see it, so what we hand TanStack is always
// basepath-relative. (Inputs that are *already* basepath-relative pass
// through unchanged, since no studio route pathname itself starts with the
// basePath segment.)
import { BASE_PATH } from './constants'
import { searchParamsToRecord, type SearchRecord } from './router-search-params'
// Inlined at build time via Vite's `define`. Must agree with Vite `base`
// and `tanstackStart({ router: { basepath } })`. Empty string when no
// basePath is configured.
const NEXT_PUBLIC_BASE_PATH = process.env.NEXT_PUBLIC_BASE_PATH ?? ''
export interface SplitInternalUrlResult {
to: string
search?: SearchRecord
hash?: string
}
function hasBasePath(pathname: string): boolean {
return pathname === NEXT_PUBLIC_BASE_PATH || pathname.startsWith(`${NEXT_PUBLIC_BASE_PATH}/`)
}
// True for inputs that carry their own origin: a scheme (`https:`,
// `mailto:`) or protocol-relative (`//host`). This is how callers tell an
// external `to` returned by `splitInternalUrl` apart from an internal path.
export function isAbsoluteUrl(url: string): boolean {
return url.startsWith('//') || /^[a-z][a-z\d+.-]*:/i.test(url)
}
export function splitInternalUrl(url: string): SplitInternalUrlResult {
// Try to detect cross-origin absolute URLs cheaply before paying for a
// full parse. Protocol-relative URLs (`//host/...`) are always external.
if (url.startsWith('//')) {
return { to: url }
}
// Use the document origin as the parse base so relative inputs resolve.
// SSR has no `location`; fall back to a placeholder host that won't ever
// collide with a real one.
const base =
typeof window !== 'undefined' && window.location ? window.location.origin : 'http://_/'
let parsed: URL
try {
parsed = new URL(url, base)
} catch {
return { to: url }
}
// Cross-origin → leave for TanStack to handle as external. Compare against
// the origin of the parse base (not `window` directly) so the check is
// intentionally window-independent: SSR and client agree, and an absolute
// external URL is never mistaken for an internal path on the server.
const baseOrigin = new URL(base).origin
if (parsed.origin !== baseOrigin) {
return { to: url }
}
let pathname = parsed.pathname
// Same-origin absolute URL outside the basePath → another app on this
// origin (e.g. `/docs`), so leave it external.
if (NEXT_PUBLIC_BASE_PATH && isAbsoluteUrl(url) && !hasBasePath(pathname)) {
return { to: url }
}
// Strip a leading basePath segment so we hand TanStack a basepath-
// relative path. Match `/dashboard` exactly OR `/dashboard/...`; don't
// strip a coincidental prefix like `/dashboard-other`.
if (NEXT_PUBLIC_BASE_PATH && hasBasePath(pathname)) {
pathname = pathname.slice(NEXT_PUBLIC_BASE_PATH.length) || '/'
}
// Repeated keys must survive as arrays (Object.fromEntries would keep only
// the last occurrence) — matches the router's Next-style parseSearch shape.
const search = searchParamsToRecord(parsed.searchParams)
// URL.hash includes the leading `#`; TanStack's `hash` prop expects the
// bare fragment and prepends its own `#` (passing it through would
// navigate to `##section` and break hash-scroll).
const hash = parsed.hash ? parsed.hash.slice(1) : undefined
return {
to: pathname,
search: Object.keys(search).length > 0 ? search : undefined,
hash,
}
}
// Next's pages-router exposes `router.pathname` as the route *pattern*
// (e.g. `/project/[ref]/sql/[id]`), not the resolved URL. TanStack's
// route id uses `$param` — convert so legacy code that does
// `router.pathname.endsWith('/sql/[id]')` keeps working.
//
// Also strip the trailing slash TanStack appends to index-route ids
// (`/project/$ref/`). Next's pages-router never includes a trailing
// slash, so consumers like `router.pathname.split('/')[3]` (used in
// the project sidebar's active-route check) silently see an empty
// string for index pages instead of `undefined`, and the home icon
// stops highlighting. The root path stays `/` either way.
export function toRoutePattern(routeId: string): string {
// Strip TanStack's layout-route segments — they're prefixed with `_`
// (`_app`, `_auth`, etc.) and don't appear in the URL or in Next's
// `router.pathname`. Without this, downstream code that derives a path
// segment from `pathname.split('/')[N]` indexes into the wrong slot —
// e.g. Sidebar uses index 3 to pick the active route, expecting
// `/org/[slug]/general` but receiving `/_app/org/[slug]/general` and
// ending up with `[slug]` instead of `general`.
const withoutLayoutSegments = routeId.replace(/\/_[a-zA-Z0-9_]+(?=\/|$)/g, '')
const withBracketParams = withoutLayoutSegments.replace(/\$([a-zA-Z0-9_]+)/g, '[$1]')
if (withBracketParams === '' || withBracketParams === '/') return '/'
return withBracketParams.replace(/\/$/, '')
}
// Prefix an app-served asset path with the basePath, as Next's image
// optimizer URL does. Full URLs, already-prefixed and relative paths are
// returned unchanged.
export function applyBasePath(src: string): string {
if (!BASE_PATH) return src
// Schemes (http:, https:, data:, blob:) and protocol-relative URLs.
if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(src) || src.startsWith('//')) return src
// Already prefixed — happens when callers manually prepend BASE_PATH
// (several studio components do this today).
if (src === BASE_PATH || src.startsWith(`${BASE_PATH}/`)) return src
// Absolute app path — prepend.
if (src.startsWith('/')) return `${BASE_PATH}${src}`
// Relative path — leave alone.
return src
}