mirror of
https://github.com/supabase/supabase.git
synced 2026-10-05 17:35:10 +03:00
Post-merge fixes for the TanStack Start migration (#46424) — things that broke on the TanStack build as master evolved under the migration branches. Kept on their own branch off master rather than piling onto the E2E-matrix PR (#47119); all land on master and cascade up to S6 + the big PR. Common theme: a master PR changed something the Next pipeline handles via `next/font` / `pages/_app.tsx` / `next.config.ts`, but the hand-rolled TanStack equivalent (`routes/__root.tsx`, `styles/fonts.css`, `vercel.ts`) wasn't updated to match — invisible on the Next deploy, broken only on TanStack. --- ## 1. Monaco loader path (#47182) #47182 re-nested the served Monaco assets from a flat `public/monaco-editor/` layout into `public/monaco-editor/vs/` and updated `pages/_app.tsx`, but `routes/__root.tsx` still pointed `loader.config` at the old path, so `loader.js` 404'd and **no Monaco editor mounted anywhere in the TanStack build**. Now mirrors the Next config (`${origin}${BASE_PATH}/monaco-editor/vs`, window-guarded for SSR). Was failing the whole `tanstack` E2E shard on #47119. ## 2. Inter + Manrope fonts (#47306) #47306 renamed Tailwind's sans var `--font-custom` → `--font-sans` and added `--font-heading` (Manrope), set via `next/font` on Next. `fonts.css` still only set the now-ignored `--font-custom`, so the body fell back to the theme's system chain (`Circular, custom-font, Helvetica…`) at weight 450 — that's the "Inter weights look wrong". Manrope was missing entirely. - Wire `--font-sans` (Inter) + `--font-heading` (Manrope) to match `next/font`. - **Vendor all three families** (Inter, Manrope, Source Code Pro) via `@font-face` so nothing depends on the Google Fonts CDN — matches `next/font` self-hosting, and (see below) `font-src` doesn't allow `fonts.gstatic.com` anyway. Verified in-browser: computed `body` → `Inter`, headings → `Manrope`, all loading from local `/assets/*.woff2`. ## 3. Security headers / CSP (next.config.ts `headers()`) The Next build sets X-Frame-Options / X-Content-Type-Options / HSTS / **Content-Security-Policy** / Referrer-Policy via `next.config.ts`. The TanStack build never carried these over — `vercel.ts` only set cache-control, so **the deployed TanStack dashboard shipped with no CSP at all**. The TanStack deploy serves a static shell (no server to attach headers), so they go in the Vercel config: - `security-headers.ts` — shared source of truth, reuses `getCSP()`, env-gated exactly like next.config. - `vercel.ts` — apply to every response (all base-path prefixes): full `getCSP()` + HSTS on platform. - `scripts/serve.js` — the non-platform set (`frame-ancestors 'none'`) for the self-hosted server. **Tested the policy in a real browser** (temporarily enforced it on the TanStack build via /test-supabase-local): everything passed except one real gap — `font-src` was missing `data:`, so GraphiQL's bundled Monaco codicon font and Stripe's payment-element fonts (both data: URIs) were blocked (37 violations on a cold load). Added `data:` to `font-src` in `csp.ts` → violations drop to zero, SQL editor Monaco renders clean. That gap affects the Next build too. --- ## 4. `node:path` import crashing `/project/[ref]/merge` Found by a full-site click-through of the TanStack build (all product areas, ongoing — see below). `useEdgeFunctionsDiff.ts` + `EdgeFunctionsDiffPanel.tsx` did `import { basename } from 'path'` in client code. Webpack (Next) polyfills `path` in the browser; Vite externalizes it, so the whole `/merge` route crashed with "Module \"path\" has been externalized for browser compatibility". Replaced the two `basename` call sites with a string helper. Verified in-browser: `/merge` renders. ## 5. URL shape — Next-style search-param semantics + shim fixes The dashboard produced malformed URLs vs the Next build (strange query params, trailing slashes, `##` hashes). Root cause + audit verified empirically against `@tanstack/react-router@1.170.10`; all fixed with unit tests and browser-verified: - **`createRouter` used TanStack's default JSON search codec** — `?flag=true` became `?flag=%22true%22` via links, repeated `?filter=…&filter=…` collapsed into a JSON array (breaking multi-filter/sort table-editor URLs and the account-page round-trip, which double-encoded), and search values arrived as numbers/booleans where the app expects strings. New `lib/router-search-params.ts` (Next-style: strings in, strings out, repeated keys → string[]) wired into the router. - **Link shim** (`compat/next/link.tsx`): `URL.hash` includes the leading `#` while TanStack's `hash` prop adds its own → every `href="…#section"` navigated to `##section` (hash-scroll broke); `Object.fromEntries(searchParams)` dropped repeated query params. Both fixed. - **Trailing slash injected before the query** on every `?`-only relative navigation (`/auth/providers/?provider=…`): fixed in the compat router (prefix current pathname) and via a custom nuqs adapter (`lib/nuqs-tanstack-adapter.tsx`) replacing the stock tanstack-router adapter, whose `navigate({ to: '?…' })` writes hit the same TanStack behavior (123 files use nuqs). - **Pathname-less `router.push({ query })` leaked path params** — Next re-consumes `ref`/`id` from `query` into the path pattern; the shim didn't, yielding `/editor/17597?schema=public&ref=<ref>&id=17597&filter=…` from table-editor filter/sort, linter panels, and advisor shortcuts. The shim now defaults the pathname to the current route pattern and backfills omitted params. - **Redirects dropped query + hash** (Next's `redirects()` preserves them): `__root.tsx` `matchRedirect` and `routes/index.tsx` now carry incoming params/hash through (consumed rule params excluded, destination's own params win). `/?next=new-project&projectName=zzz` → `/new/new-project?projectName=zzz`; `/sql/quickstarts?template=x#frag` → `/sql/examples?template=x#frag`. Browser-verified post-fix: advisors `?preset=WARN`, providers `?provider=Google`, `?schema=auth` — all clean (no `/?`, no leaks); repeated `filter` params survive hydration; `=true` unquoted; single `#`. ## 6. TanStack `navigate` corrupting query values (Logs Explorer SQL newline loss) TanStack router-core treats a query string embedded in `navigate({ to })` as part of the *path*: `decodePath` percent-decodes it and `sanitizePathSegment` strips control characters, silently deleting every `%0A`. Logs Explorer's SQL (`s` param) lost its newlines on Run/reload — `order by timestamp desc` / `limit 5` glued into `desclimit 5`, which then failed the LIMIT lint. Pre-existing on the TanStack build (the stock nuqs adapter had the same shape); Next unaffected. Fixed by never embedding query strings in `to`: the nuqs adapter and the compat `router.push`/`replace`/`prefetch` (plus the `next/navigation` shim) now pass search as an object through the app codec (`splitInternalUrl` hoisted to `lib/internal-url.ts`). Guard test drives a real `createRouter` with multi-line SQL through both producers. Browser-verified: newlines survive the full Run → reload → re-Run cycle. ## 7. Integration overview markdown never loaded (all integrations) `MarkdownContent` used a template-literal dynamic import (``import(`@/static-data/integrations/${id}/overview.md`)``) — webpack builds a context module for that, Vite can't analyze it, so every integration detail page threw `Failed to resolve module specifier` and rendered no overview text. Fixed with an explicit lazy registry of literal imports (`static-data/integrations/overviews.ts`, drift-guarded by a test) plus an `mdRawLoader()` Vite plugin mirroring next.config's turbopack raw-loader rule. Both runtimes keep working; md stays out of the main bundle. ## 8. GraphiQL editor never mounted (`exports is not defined`) Our `umdAmdShortCircuit()` Vite plugin (which disarms Monaco's global AMD loader for deps like papaparse) rewrote `typeof define === 'function' && define.amd` to `false` inside `monaco-editor`'s bundled copy of marked — whose UMD relies on its own *local* `define` shim — so the whole optimized monaco chunk failed to evaluate and GraphiQL's editor pane stayed blank. The check now only short-circuits when `define` is the global AMD loader. Browser-verified: all four GraphiQL Monaco panes mount, queries execute. (Known follow-up: GraphiQL's Monaco workers fall back to the main thread under Vite — functional, worker wiring is Next-specific `setup-workers/webpack`.) ## 9. `@sentry/nextjs` bundling Next internals — built TanStack bundle crashed (caught by E2E) The E2E suite against the **built** TanStack bundle (not the dev server) found lazy chunks like `table-editor-*.js` dead on arrival: `@sentry/nextjs` (imported by ~25 client files) drags in `next/dist/shared/lib/constants`, whose module scope evaluates `process?.features?.typescript` — optional chaining doesn't guard an undeclared `process` in the browser, so the whole chunk failed at load with `ReferenceError: process is not defined`. Dev shims `process`, which is why weeks of dev-server testing never saw it. Fixed by aliasing `@sentry/nextjs` → `compat/sentry-nextjs.ts` (re-exports `@sentry/react`, same deduped 10.59.0, plus explicit stand-ins for the three Next-only APIs) in the Vite build only. Verified: fresh build has zero Next-internals markers in any chunk; table editor loads clean; full E2E suite run against the built bundle. Note for the stack: `alaister/tanstack-start` / the E2E-matrix branch already carried a different fix for the same crash (a `next/constants` shim) that never made it to master — the cherry-pick onto those branches keeps **both** (the shim covers any other transitive importer; the alias keeps Next internals out of the client bundle entirely). **Follow-up found while fixing:** Sentry is never *initialized* in the TanStack runtime — `instrumentation-client.ts` / `sentry.server.config.ts` are Next-convention files nothing imports under TanStack, so `captureException` calls are silent no-ops. Needs an `@sentry/react` init (+ `tanstackRouterBrowserTracingIntegration`) wired into the TanStack client entry as its own PR. ## 10. GraphiQL Monaco workers + edge-function Deno typings (Vite-only gaps) - **GraphiQL's Monaco workers ran on the main thread** under Vite ("Could not create web worker(s)…" — `setup-workers/webpack`'s `new URL(...)` form isn't rewritten by Vite). A `graphiqlViteWorkers()` plugin resolves the import to graphiql's own `setup-workers/vite` variant for client builds (SSR untouched, Next untouched); the setup-workers chain is `optimizeDeps.exclude`d because the Rolldown optimizer can't load `?worker` ids. - **Edge-function editors silently lost their Deno typings** — `AIEditor` loaded `public/deno/*.d.ts` via `/* @vite-ignore */` imports that always failed at runtime under Vite. The `.md` raw loader is generalized into `rawTextLoader` (exact-path allowlist for the two typings files, served as virtual string modules so the dep scanner never parses `.d.ts` syntax), and the imports are now static-analyzable literals that both bundlers handle (turbopack's raw-loader rules match them on the Next side). ## Split out for reviewability App-level fixes that reproduce on the Next build too (DOM-nesting hydration errors, the ghost deleted-snippet nav, the recurring pg-meta `migrations` 400) moved to their own PR: #47667. Sentry initialization for the TanStack runtime (captures were silent no-ops) is #47666, stacked on this PR. ## Full-site test campaign Drove every dashboard product area on the local TanStack build (Playwright, human-style) hunting migration regressions: redirects/404/catch-alls, org, account, project home/branches/merge, table editor CRUD, SQL editor (Monaco/run/save/templates/AI), all database pages, all auth pages, storage CRUD, edge functions + realtime, logs/observability, advisors, settings, integrations hub incl. nested routes, global UI (palette/connect/switchers/theme/fonts), and a cross-cutting sweep (document titles, back/forward chain, hard-refresh hydration on deep URLs, trailing-slash active state). Every failure found is fixed above and re-verified in-browser; remaining console quirks were cross-checked against the deployed Next build and are pre-existing (tracked separately). ## To test Most fixes are already browser-verified + covered by unit tests and the self-hosted E2E suite; the last two landed after the final browser pass and still need an in-browser check: 1. **GraphiQL Monaco workers** — restart the dev server (clear `apps/studio/node_modules/.vite` once first — the optimizer cache may hold a stale prebundle of the worker chain). Open `/project/<ref>/integrations/graphiql/graphiql` with the console open: the `Could not create web worker(s). Falling back to loading web worker code in main thread` warning must be gone, and DevTools → Sources → Threads shows the three workers (json, editor, graphql). Autocomplete in the query editor stays responsive. 2. **Edge-function Deno typings** — `/project/<ref>/functions/new`: no "Failed to load … typings" console error, and typing `Deno.` in the editor offers typed completions (e.g. `Deno.env`). Spot-checks for the rest (all previously verified): - `/project/<ref>/merge` renders (no "Module path" crash). - Multi-line SQL in Logs Explorer survives Run → reload (no `desclimit` gluing, no LIMIT-lint false failure); `s` param keeps `%0A`. - `/auth/providers` → open a provider → `?provider=…` with no trailing slash before `?`; table-editor filter/sort URLs carry no leaked `ref`/`id` params; `/?next=new-project&projectName=x` lands on `/new/new-project?projectName=x`. - Integration detail pages (cron/queues/vault/data_api) show their overview prose; GraphiQL query editor mounts. - Built bundle (`MODE=test vite build` + `start:tanstack`): table editor loads with no `process is not defined`. - `curl -sI` any page on a platform deploy: `X-Content-Type-Options: nosniff` (was the invalid `no-sniff`). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Centralized integration overview markdown loading with registry-based lookup. * Improved Monaco loading/asset path handling for smoother editor startup. * **Bug Fixes** * Next-style navigation/search handling now preserves pathname, hash, repeated query keys, and special characters (including newlines). * Redirects now reliably carry over query and hash with correct precedence. * **Security/Configuration** * Updated CSP font sourcing and unified security headers delivery across environments; conditional HSTS behavior. * Refreshed font CSS variables and font-face definitions to match the theme. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- ### Review feedback: non-prod favicon (Joshen) The TanStack `__root.tsx` hardcoded the prod favicon; local + hosted staging now use the white staging favicon (`/favicon/staging`), matching what `pages/_app.tsx` passes to `MetaFaviconsPagesRouter` for non-prod. Rather than pull the pages-router component into the TanStack head, it reuses the same synchronous `NEXT_PUBLIC_ENVIRONMENT` signal the file already uses for `IS_DEV_TOOLBAR_ENABLED` (the `head()` route option isn't a React component, so it can't run `_app`'s async CLI check — but the env signal covers the reported local/staging case). --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
480 lines
21 KiB
TypeScript
480 lines
21 KiB
TypeScript
import {
|
|
useLocation,
|
|
useMatches,
|
|
useParams,
|
|
useSearch,
|
|
useRouter as useTanStackRouter,
|
|
type AnyRouter,
|
|
} from '@tanstack/react-router'
|
|
import { useMemo } from 'react'
|
|
|
|
import { getRouterEventsProxy } from './_router-events'
|
|
import { splitInternalUrl } from '@/lib/internal-url'
|
|
|
|
// 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.
|
|
function toNextPathPattern(routeId: 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(/\/$/, '')
|
|
}
|
|
|
|
// Normalise TanStack's `router.basepath` to Next's `router.basePath`
|
|
// shape: '' for "no basePath" or '/path' for "configured" (leading
|
|
// slash, no trailing slash).
|
|
function toNextBasePath(tanstackBasepath: string | undefined): string {
|
|
if (!tanstackBasepath || tanstackBasepath === '/') return ''
|
|
const withLeading = tanstackBasepath.startsWith('/') ? tanstackBasepath : `/${tanstackBasepath}`
|
|
return withLeading.endsWith('/') ? withLeading.slice(0, -1) : withLeading
|
|
}
|
|
|
|
type QueryValue = string | number | boolean | string[] | undefined | null
|
|
type UrlObject = {
|
|
pathname?: string
|
|
query?: Record<string, QueryValue> | string
|
|
hash?: string
|
|
search?: string
|
|
}
|
|
|
|
function serializeQuery(query: UrlObject['query']): string {
|
|
if (!query) return ''
|
|
if (typeof query === 'string') return query.startsWith('?') ? query : `?${query}`
|
|
const params = new URLSearchParams()
|
|
for (const [key, raw] of Object.entries(query)) {
|
|
if (raw == null) continue
|
|
if (Array.isArray(raw)) {
|
|
for (const item of raw) if (item != null) params.append(key, String(item))
|
|
} else {
|
|
params.set(key, String(raw))
|
|
}
|
|
}
|
|
const s = params.toString()
|
|
return s ? `?${s}` : ''
|
|
}
|
|
|
|
// Next's pages-router fills dynamic segments in a UrlObject's `pathname` from
|
|
// `query`, then drops the consumed keys from the query string — e.g.
|
|
// `push({ pathname: '/project/[ref]/editor/[id]', query: { ref, id, foo } })`
|
|
// resolves to `/project/<ref>/editor/<id>?foo=...`. `router.pathname` here is
|
|
// the bracketed route *pattern* (see toNextPathPattern) and callers like
|
|
// useUrlState push it back verbatim, so without this a sort/filter update on a
|
|
// dynamic route would navigate TanStack to a LITERAL `/project/[ref]/...`,
|
|
// which matches no project (ref === '[ref]') and bounces to a "project not
|
|
// found" redirect. Mirrors Next's behaviour so those pushes stay on-page.
|
|
function interpolatePathname(
|
|
pathname: string,
|
|
query: Record<string, QueryValue>
|
|
): { pathname: string; query: Record<string, QueryValue> } {
|
|
if (!pathname.includes('[')) return { pathname, query }
|
|
const consumed = new Set<string>()
|
|
const encodeValue = (v: QueryValue) =>
|
|
v == null
|
|
? ''
|
|
: Array.isArray(v)
|
|
? v.map((item) => encodeURIComponent(String(item))).join('/')
|
|
: encodeURIComponent(String(v))
|
|
const interpolated = pathname
|
|
// optional + required catch-all: `[[...name]]` / `[...name]`
|
|
.replace(/\[\[?\.\.\.([^\]]+)\]?\]/g, (_match, name: string) => {
|
|
consumed.add(name)
|
|
return encodeValue(query[name])
|
|
})
|
|
// single dynamic segment: `[name]`
|
|
.replace(/\[([^\]]+)\]/g, (_match, name: string) => {
|
|
consumed.add(name)
|
|
return encodeValue(query[name])
|
|
})
|
|
if (consumed.size === 0) return { pathname: interpolated, query }
|
|
const rest: Record<string, QueryValue> = {}
|
|
for (const [key, value] of Object.entries(query)) {
|
|
if (!consumed.has(key)) rest[key] = value
|
|
}
|
|
return { pathname: interpolated, query: rest }
|
|
}
|
|
|
|
// TanStack resolves a `?`- or `#`-only relative `to` by *appending* it to the
|
|
// current path, injecting a trailing slash: navigating to `?preset=x` from
|
|
// `/advisors/security` lands on `/advisors/security/?preset=x`. Next resolved
|
|
// these against the current pathname. Prefix it explicitly (trailing slash
|
|
// stripped; root stays `/`) so `push({ query })` with no pathname stays on
|
|
// the exact current path.
|
|
// Exported for unit tests (see router.test.ts) — not part of the Next surface.
|
|
export function resolveSearchOrHashOnlyTarget(to: string, currentPathname: string): string {
|
|
if (!to.startsWith('?') && !to.startsWith('#')) return to
|
|
let base = currentPathname || '/'
|
|
if (base.length > 1 && base.endsWith('/')) base = base.slice(0, -1)
|
|
return `${base}${to}`
|
|
}
|
|
|
|
// Next resolves a pathname-less UrlObject against the *current route
|
|
// pattern*, re-consuming dynamic params from `query` into the path — e.g.
|
|
// `push({ query: { ...router.query, preset } })` on `/project/[ref]/advisors`
|
|
// stays on `/project/<ref>/advisors?preset=…`. Because the shim's
|
|
// `router.query` merges path params in (Next shape), skipping this would leak
|
|
// `ref`/`id` into the query string. Params the caller didn't include are
|
|
// backfilled from the current route's params (minus TanStack's `_splat`,
|
|
// which no bracket segment can consume) so partial `{ query }` pushes stay
|
|
// on-page instead of producing empty path segments.
|
|
// Exported for unit tests (see router.test.ts) — not part of the Next surface.
|
|
export function withDefaultPathname(
|
|
url: string | UrlObject,
|
|
currentPathPattern: string,
|
|
currentParams: Record<string, QueryValue>
|
|
): string | UrlObject {
|
|
if (typeof url === 'string' || url.pathname != null) return url
|
|
if (!url.query || typeof url.query !== 'object') return url
|
|
const { _splat, ...paramsWithoutSplat } = currentParams
|
|
return {
|
|
...url,
|
|
pathname: currentPathPattern,
|
|
query: { ...paramsWithoutSplat, ...url.query },
|
|
}
|
|
}
|
|
|
|
// Exported for unit tests (see router.test.ts) — not part of the Next surface.
|
|
export function resolveUrl(url: string | UrlObject): string {
|
|
if (typeof url === 'string') return url
|
|
let pathname = url.pathname ?? ''
|
|
let query = url.query
|
|
// Interpolate named params into the path when query is a record — a raw query
|
|
// string can't fill `[param]` placeholders, so leave it untouched.
|
|
if (query && typeof query === 'object') {
|
|
const interpolated = interpolatePathname(pathname, query)
|
|
pathname = interpolated.pathname
|
|
query = interpolated.query
|
|
}
|
|
const search = url.search ?? serializeQuery(query)
|
|
const hash = url.hash ? (url.hash.startsWith('#') ? url.hash : `#${url.hash}`) : ''
|
|
return `${pathname}${search}${hash}`
|
|
}
|
|
|
|
// Studio code occasionally constructs `router.push` targets via
|
|
// `new URL().toString()` (e.g. `buildTableEditorUrl`), producing fully
|
|
// qualified `http://localhost:8082/dashboard/project/.../editor/123?...`
|
|
// strings — origin + basePath + path. Next's router tolerated both by
|
|
// treating same-origin absolute URLs as relative paths AND understanding
|
|
// basePath was already in the input.
|
|
//
|
|
// TanStack Router needs `to` to be basepath-relative — given
|
|
// `basepath: '/dashboard'` and `to: '/foo'`, it produces `/dashboard/foo`.
|
|
// So we strip the origin AND the basePath when present; otherwise
|
|
// `router.push('/dashboard/...')` would double-prefix to
|
|
// `/dashboard/dashboard/...`. Mirrors the equivalent logic in
|
|
// `splitInternalUrl` (@/lib/internal-url). Cross-origin URLs pass through
|
|
// untouched so TanStack hands them to the browser as external.
|
|
const NEXT_PUBLIC_BASE_PATH = process.env.NEXT_PUBLIC_BASE_PATH ?? ''
|
|
|
|
// Strip a leading basePath segment from a path-shape URL (no origin).
|
|
// Mirrors what Next's pages-router does for `asPath`. Used by both
|
|
// `useRouter().asPath` and the push/replace path-normalisation pipeline.
|
|
function stripBasePath(pathish: string): string {
|
|
if (!NEXT_PUBLIC_BASE_PATH) return pathish
|
|
if (pathish === NEXT_PUBLIC_BASE_PATH) return '/'
|
|
if (pathish.startsWith(`${NEXT_PUBLIC_BASE_PATH}/`)) {
|
|
return pathish.slice(NEXT_PUBLIC_BASE_PATH.length)
|
|
}
|
|
return pathish
|
|
}
|
|
|
|
function toRelativeSameOrigin(url: string): string {
|
|
let pathname: string
|
|
let search = ''
|
|
let hash = ''
|
|
if (url.startsWith('http://') || url.startsWith('https://')) {
|
|
if (typeof window === 'undefined' || !window.location) return url
|
|
try {
|
|
const parsed = new URL(url)
|
|
if (parsed.origin !== window.location.origin) return url
|
|
pathname = parsed.pathname
|
|
search = parsed.search
|
|
hash = parsed.hash
|
|
} catch {
|
|
return url
|
|
}
|
|
} else {
|
|
// Relative input — split on the first `?` / `#` so we can strip a
|
|
// basePath segment from the pathname only.
|
|
const queryIdx = url.indexOf('?')
|
|
const hashIdx = url.indexOf('#')
|
|
const splitIdx =
|
|
[queryIdx, hashIdx].filter((i) => i >= 0).sort((a, b) => a - b)[0] ?? url.length
|
|
pathname = url.slice(0, splitIdx)
|
|
const rest = url.slice(splitIdx)
|
|
const qEnd = rest.indexOf('#')
|
|
if (rest.startsWith('?')) {
|
|
search = qEnd >= 0 ? rest.slice(0, qEnd) : rest
|
|
hash = qEnd >= 0 ? rest.slice(qEnd) : ''
|
|
} else if (rest.startsWith('#')) {
|
|
hash = rest
|
|
}
|
|
}
|
|
return `${stripBasePath(pathname)}${search}${hash}`
|
|
}
|
|
|
|
// Next's pages-router passes a TransitionOptions bag as the 3rd arg to
|
|
// push/replace. We accept the shape but ignore every field — TanStack has
|
|
// no direct equivalent for any of them (shallow, locale, scroll,
|
|
// unstable_skipClientCache). Notably `shallow` is a no-op here, NOT a
|
|
// push-vs-replace signal: callers pass `push(url, as, { shallow: true })`
|
|
// expecting a normal history push (e.g. useUrlState, MonacoEditor). Whether
|
|
// a navigation replaces is decided solely by which method is called
|
|
// (push vs replace) via the internal `_replace` flag below.
|
|
type TransitionOptions = {
|
|
shallow?: boolean
|
|
locale?: string | false
|
|
scroll?: boolean
|
|
unstable_skipClientCache?: boolean
|
|
}
|
|
|
|
type PrefetchOptions = {
|
|
priority?: boolean
|
|
locale?: string | false
|
|
unstable_skipClientCache?: boolean
|
|
}
|
|
|
|
export function useRouter() {
|
|
const router = useTanStackRouter()
|
|
const location = useLocation()
|
|
const matches = useMatches()
|
|
const params = useParams({ strict: false })
|
|
const search = useSearch({ strict: false })
|
|
|
|
return useMemo(() => {
|
|
const leafRouteId = matches[matches.length - 1]?.routeId ?? location.pathname
|
|
const pathPattern = toNextPathPattern(leafRouteId)
|
|
|
|
// Both push and replace accept Next's (url, as?, options?) signature.
|
|
// `as` is the legacy alias path (mostly obsolete in modern Next; ignored
|
|
// here — the resolved `url` is what we navigate to). Returns
|
|
// Promise<boolean> matching Next; TanStack's navigate doesn't surface
|
|
// a success boolean so we always resolve to true.
|
|
const navigate = async (
|
|
url: string | UrlObject,
|
|
_as?: string | UrlObject,
|
|
// `_replace` is an internal flag set by the `replace()` method below.
|
|
// It's intentionally not part of Next's public TransitionOptions.
|
|
options?: TransitionOptions & { _replace?: boolean }
|
|
): Promise<boolean> => {
|
|
// `location.pathname` is already basepath-stripped by TanStack, so the
|
|
// prefixed target stays basepath-relative like every other `to`.
|
|
const target = resolveSearchOrHashOnlyTarget(
|
|
// `useParams({ strict: false })` types as possibly-undefined; treat
|
|
// "no params" as an empty record for backfilling.
|
|
toRelativeSameOrigin(resolveUrl(withDefaultPathname(url, pathPattern, params ?? {}))),
|
|
location.pathname
|
|
)
|
|
// Never embed `?query`/`#hash` inside TanStack's `to` — router-core
|
|
// runs the whole string through path interpolation, which percent-
|
|
// decodes it and strips control characters (dropping `%0A` newlines
|
|
// from values like the Logs Explorer's `s` SQL param). Split into
|
|
// { to, search, hash } instead; the target is already relative and
|
|
// basepath-stripped, so splitInternalUrl's own origin/basePath
|
|
// normalisation is a no-op here. `search: {}` clears the query,
|
|
// matching Next's push-without-query semantics; same for `hash: ''`.
|
|
//
|
|
// The `<AnyRouter, string>` type arguments opt out of the registered
|
|
// route tree's strict typing: Next-style hrefs are free-form strings
|
|
// that can't satisfy the route-path union at compile time.
|
|
const { to, search, hash } = splitInternalUrl(target)
|
|
await router.navigate<AnyRouter, string>({
|
|
to,
|
|
search: search ?? {},
|
|
hash: hash ?? '',
|
|
replace: options?._replace,
|
|
})
|
|
return true
|
|
}
|
|
|
|
return {
|
|
// ---- state ----
|
|
pathname: pathPattern,
|
|
// Next's pages-router exposes `route` and `pathname` as the same value
|
|
// — the route pattern with bracketed dynamic segments. Some studio
|
|
// code (e.g. AppLayout/BranchLink, AppLayout/ProjectDropdown) reads
|
|
// `router.route` specifically; without this it's `undefined` and
|
|
// downstream `.split('/')` calls crash.
|
|
route: pathPattern,
|
|
// Route params take precedence over search params of the same name,
|
|
// matching Next's pages-router req.query merge order.
|
|
query: { ...search, ...params },
|
|
// Next's pages-router `asPath` is path + query + hash *without* the
|
|
// origin and *without* the configured `basePath`
|
|
// (https://nextjs.org/docs/pages/api-reference/functions/use-router).
|
|
// Studio code relies on the no-basePath shape — e.g.
|
|
// OrganizationSettingsLayout compares `currentPath === '/org/<slug>/
|
|
// general'` for the side-nav active state, with section hrefs that
|
|
// never include `/dashboard`. Returning a basepath-prefixed value
|
|
// breaks every such strict-equality check.
|
|
asPath: stripBasePath(location.href),
|
|
// Mirror Next's pages-router contract for `basePath`:
|
|
// - no basePath configured → '' (empty string)
|
|
// - configured → '/dashboard' (leading slash, no trailing)
|
|
//
|
|
// TanStack stores the raw `basepath` option without normalising:
|
|
// `undefined` becomes '/' (its internal default), 'dashboard' stays
|
|
// 'dashboard', '/dashboard/' stays '/dashboard/'. Studio code then
|
|
// does `${router.basePath}/img/...` and trips on every non-Next
|
|
// shape ('/' → '//img/...' protocol-relative; 'dashboard' →
|
|
// 'dashboard/img/...' relative-to-current-path; '/dashboard/' →
|
|
// '/dashboard//img/...' double slash).
|
|
basePath: toNextBasePath(router.basepath),
|
|
// TanStack resolves params/search synchronously on render, so the
|
|
// pages-router "is the dynamic param ready yet?" flag is always
|
|
// true here. (In Next this can be false during the very first
|
|
// render of a dynamic page.)
|
|
isReady: true,
|
|
// No equivalent under TanStack — surface as static `false` so call
|
|
// sites that read these don't crash. Next-only features.
|
|
isFallback: false,
|
|
isPreview: false,
|
|
isLocaleDomain: false,
|
|
// i18n routing isn't wired through TanStack here. Return undefined
|
|
// for the active locale and an empty list for the rest — matches
|
|
// a Next app that has no i18n config.
|
|
locale: undefined as string | undefined,
|
|
locales: undefined as string[] | undefined,
|
|
defaultLocale: undefined as string | undefined,
|
|
domainLocales: undefined as Array<{ domain: string; defaultLocale: string }> | undefined,
|
|
|
|
// ---- navigation ----
|
|
push: (url: string | UrlObject, as?: string | UrlObject, options?: TransitionOptions) =>
|
|
navigate(url, as, options),
|
|
replace: (url: string | UrlObject, as?: string | UrlObject, options?: TransitionOptions) =>
|
|
navigate(url, as, { ...options, _replace: true }),
|
|
reload: () => {
|
|
if (typeof window !== 'undefined') window.location.reload()
|
|
},
|
|
back: () => {
|
|
if (typeof window !== 'undefined') window.history.back()
|
|
},
|
|
forward: () => {
|
|
if (typeof window !== 'undefined') window.history.forward()
|
|
},
|
|
prefetch: async (
|
|
url: string,
|
|
_asPath?: string,
|
|
_options?: PrefetchOptions
|
|
): Promise<void> => {
|
|
try {
|
|
// Split like navigate() above so a query string in the href
|
|
// preloads the real target instead of a path-mangled one.
|
|
// `<string, string>` (TFrom, TTo) loosens `to` to a plain string
|
|
// for the same free-form-href reason as `navigate` above.
|
|
const { to, search, hash } = splitInternalUrl(toRelativeSameOrigin(url))
|
|
await router.preloadRoute<string, string>({
|
|
to,
|
|
search: search ?? {},
|
|
hash: hash ?? '',
|
|
})
|
|
} catch {
|
|
// Next's prefetch is fire-and-forget; swallow resolution errors
|
|
// (e.g. unknown route) so callers don't have to guard.
|
|
}
|
|
},
|
|
// Next-only escape hatch for popstate handling. Not wired up; accept
|
|
// and discard the callback so call sites compile and run without
|
|
// throwing. Callers that *rely* on this (none currently in studio)
|
|
// would need a real implementation.
|
|
beforePopState: (_cb: (state: unknown) => boolean) => {},
|
|
|
|
// ---- events ----
|
|
events: getRouterEventsProxy(router),
|
|
}
|
|
}, [router, location.href, location.pathname, matches, params, search])
|
|
}
|
|
|
|
// Normalise an optional-catch-all route's params across both frameworks.
|
|
//
|
|
// Next's `[[...name]]` surfaces the trailing path as `query.name: string[]`,
|
|
// while TanStack's splat (`$`) surfaces it as `query._splat: string`. The
|
|
// shim can't rename `_splat` to the Next param name on its own — that name
|
|
// only exists in the Next page filename and never reaches the router — so
|
|
// the caller passes it. Returns the trailing path as a string[] plus the
|
|
// remaining query params (with the catch-all keys stripped) for building
|
|
// query strings. Shared by every migrated catch-all page so the logic lives
|
|
// in one place.
|
|
export function parseCatchAllRoute(
|
|
query: Record<string, string | string[] | undefined>,
|
|
paramName: string
|
|
): {
|
|
segments: string[] | undefined
|
|
queryParams: Record<string, string | string[] | undefined>
|
|
} {
|
|
const { [paramName]: raw, _splat, ...queryParams } = query
|
|
const segments = Array.isArray(raw)
|
|
? raw
|
|
: typeof _splat === 'string' && _splat
|
|
? _splat.split('/')
|
|
: undefined
|
|
return { segments, queryParams }
|
|
}
|
|
|
|
// Module-scope singleton — Next exposes the same proxy via
|
|
// `import router from 'next/router'`. We have one consumer
|
|
// (Support/DiscordCTACard) that reads `router.basePath` at render time
|
|
// outside of a hook context, so we surface the env-derived basePath
|
|
// directly. Push/replace/etc. fall through to `window.location` to keep
|
|
// future module-scope navigations safe; nothing in studio uses them
|
|
// today.
|
|
const singletonBasePath = toNextBasePath(
|
|
// Read both the TanStack and Next env names — TanStack also reads
|
|
// VITE_BASE_URL but the studio config writes NEXT_PUBLIC_BASE_PATH.
|
|
process.env.NEXT_PUBLIC_BASE_PATH
|
|
)
|
|
|
|
const singletonRouter = {
|
|
basePath: singletonBasePath,
|
|
pathname: '',
|
|
route: '',
|
|
query: {} as Record<string, string | string[] | undefined>,
|
|
asPath: '',
|
|
isReady: true,
|
|
isFallback: false,
|
|
isPreview: false,
|
|
isLocaleDomain: false,
|
|
push: async (url: string | UrlObject): Promise<boolean> => {
|
|
if (typeof window !== 'undefined') window.location.assign(resolveUrl(url))
|
|
return true
|
|
},
|
|
replace: async (url: string | UrlObject): Promise<boolean> => {
|
|
if (typeof window !== 'undefined') window.location.replace(resolveUrl(url))
|
|
return true
|
|
},
|
|
reload: () => {
|
|
if (typeof window !== 'undefined') window.location.reload()
|
|
},
|
|
back: () => {
|
|
if (typeof window !== 'undefined') window.history.back()
|
|
},
|
|
forward: () => {
|
|
if (typeof window !== 'undefined') window.history.forward()
|
|
},
|
|
prefetch: async () => {},
|
|
beforePopState: (_cb: (state: unknown) => boolean) => {},
|
|
events: {
|
|
on: () => {},
|
|
off: () => {},
|
|
emit: () => {},
|
|
},
|
|
}
|
|
|
|
// eslint-disable-next-line no-restricted-exports
|
|
export default singletonRouter
|