Files
supabase/apps/studio/tests/lib/custom-render.tsx
Alaister YoungandAlaister Young 0c97b9789b [FE-3107] chore(studio): remove remaining Next.js references (#54426)
Removes the remaining Next.js dependencies, compatibility shims, test
mocks, ESLint/TypeScript presets, and webpack/Next workarounds from
Studio following the TanStack Start migration.

Addresses FE-3107.

**Removed:**

- `next` and `next-router-mock` from `apps/studio/package.json` (and
updated `pnpm-lock.yaml`)
- Orphaned `apps/studio/compat/next/script.tsx` shim, `script.test.tsx`,
`compat/**` knip entry, and `nextCompat()` / `ssr.noExternal` `/^next/`
plumbing from `apps/studio/vite.config.ts`
- `apps/studio/tests/lib/route-mock.ts` and all `next-router-mock`
setup/imports across `tests/vitestSetup.ts`,
`tests/lib/custom-render.tsx`, and 12 test files
- `apps/studio/tests/pages/` directory (moved the 3 remaining tests to
`components/interfaces/Organization/Organization.utils.test.ts` and
`apps/studio/tests/routes/`)
- Unused `'use client'` directives across 23 Studio files
- Next.js/webpack workarounds: `graphiqlViteWorkers()` in
`vite.config.ts`, webpack `import.meta.glob` `try/catch` fallback in
`ConnectStepsSection.tsx`, shell `NODE_ENV=test` override in
`vite.config.ts` / root `package.json` / `studio-e2e-test.yml`, Next
`getPathMatch` and `_next` passthrough in `redirects.shared.*`,
`window.next?.router` check in `monaco-graphiql-coexistence.spec.ts`,
and unused `ANALYZE` env var in `apps/studio/turbo.jsonc`
- Next-only Sentry/chunk-load filters (`NEXT_NOT_FOUND`,
`NEXT_REDIRECT`, Next `/org/[slug]/` regex, `/app:\/\//`, dead
`includeThirdPartyErrorFilter` plumbing, webpack chunk error regex) and
stale Next/Pages Router comments, docs, and `#__next` CSS selector

**Changed:**

- `apps/studio/eslint.config.cjs`: switched from
`eslint-config-supabase/next` to the new `eslint-config-supabase/react`
preset (dropping `@next/next/no-img-element: off`, keeping `.next` /
`next-env.d.ts` ignored for local checkouts with stale pre-migration
build artifacts)
- `apps/studio/tsconfig.json`: extends `tsconfig/base.json` directly
instead of `tsconfig/nextjs.json` (identical resolved compiler options)
- `apps/studio/.github/eslint-rule-baselines.json`: pruned 33 stale
`pages/...` and `types/next.ts` entries without changing any rule
thresholds
- `apps/studio/tests/lib/custom-render.tsx`: backed
`TestFrameworkProvider` with TanStack Router instead of
`next-router-mock`
-
`apps/studio/components/interfaces/Integrations/GraphQL/GraphiQLTab.tsx`:
imports `graphiql/setup-workers/vite` directly
- `apps/studio/styles/globals.css`: replaced `@source
'../pages/**/*.{js,ts,jsx,tsx}'` with `@source
'../routes/**/*.{js,ts,jsx,tsx}'`
- `apps/studio/turbo.jsonc`: declared `"NEXT_PUBLIC_*"` in
`tasks.build.env` now that Turborepo infers `nitro` instead of `nextjs`
-
`apps/studio/components/interfaces/Organization/Organization.utils.ts`:
narrowed `buildOrgUrl`'s `slug` parameter to `string[] | undefined`

**Added:**

- `packages/eslint-config-supabase/shared.js` and
`packages/eslint-config-supabase/react.js` (plus `presets.test.ts`),
decoupling non-Next React apps from `eslint-config-next` with verified
zero non-`@next/*` rule drift while keeping
`eslint-config-supabase/next` unchanged for the Next.js apps

## To test

- Run `pnpm --filter eslint-config-supabase run test` and confirm preset
parity tests pass
- Run `pnpm --filter studio run lint`, `pnpm --filter studio run
lint:ratchet`, `pnpm --filter studio run typecheck`, `pnpm knip
--workspace apps/studio`, and `pnpm --filter studio run test`
- Run `pnpm --filter studio run build` and verify the production build,
prerendered routes, chunk-cycle check, and GraphiQL web workers succeed
- Smoke-test Studio locally (`pnpm dev:studio`): verify GraphiQL loads
cleanly, ConnectSheet framework steps render, and Tailwind styles on
route pages are intact

---------

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

269 lines
7.8 KiB
TypeScript

import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import {
createMemoryHistory,
createRootRoute,
createRouter,
Link as TanStackLink,
RouterContextProvider,
useRouter as useTanStackRouter,
useRouterState,
type AnyRoute,
type AnyRouter,
} from '@tanstack/react-router'
import { render, renderHook, type RenderOptions } from '@testing-library/react'
import {
AuthContext,
AuthContext as AuthContextType,
DefaultFrameworkImage,
DefaultFrameworkLink,
FrameworkProvider,
resolveStaticImageSrc,
type FrameworkContextValue,
type FrameworkImageProps,
type FrameworkLinkProps,
} from 'common'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
import { forwardRef, useMemo, type ForwardedRef } from 'react'
import { TooltipProvider } from 'ui'
import { CommandProvider } from 'ui-patterns/CommandMenu'
// End of third-party imports
import { applyBasePath, isAbsoluteUrl, splitInternalUrl, toRoutePattern } from '@/lib/internal-url'
import { navigateToUrl } from '@/lib/navigation'
import { ProfileContext, type ProfileContextType } from '@/lib/profile'
import { parseSearch, stringifySearch } from '@/lib/router-search-params'
type AdapterProps = Partial<Parameters<typeof NuqsTestingAdapter>[0]>
function normalizeParams(
search: Record<string, unknown> | undefined,
params: Record<string, unknown> | undefined
): Record<string, string | string[] | undefined> {
const merged = { ...search, ...params }
const normalized: Record<string, string | string[] | undefined> = {}
for (const [key, value] of Object.entries(merged)) {
if (typeof value === 'string') {
normalized[key] = value
} else if (Array.isArray(value)) {
normalized[key] = value.map(String)
} else if (value !== undefined && value !== null) {
normalized[key] = String(value)
}
}
return normalized
}
function resolveSearchOrHashOnlyTarget(
target: string,
currentPathname: string,
currentSearch: string
): string {
if (target.startsWith('?')) {
return `${currentPathname}${target}`
}
if (target.startsWith('#')) {
return `${currentPathname}${currentSearch}${target}`
}
return target
}
const TestFrameworkLink = forwardRef(function TestFrameworkLink(
props: FrameworkLinkProps,
ref: ForwardedRef<HTMLAnchorElement>
) {
const { href, prefetch, replace, scroll: _scroll, shallow: _shallow, children, ...rest } = props
const currentPathname = useRouterState({
select: (state) => (state.resolvedLocation ?? state.location).pathname,
})
const currentSearch = useRouterState({
select: (state) => (state.resolvedLocation ?? state.location).searchStr,
})
const resolvedHref = resolveSearchOrHashOnlyTarget(href, currentPathname, currentSearch)
const { to, search, hash } = splitInternalUrl(resolvedHref)
if (isAbsoluteUrl(to)) {
return <DefaultFrameworkLink ref={ref} {...props} />
}
const preload = prefetch === false ? false : prefetch ? 'intent' : undefined
return (
<TanStackLink<AnyRouter, string>
to={to}
search={search as never}
hash={hash}
replace={replace}
preload={preload}
ref={ref}
{...rest}
>
{children}
</TanStackLink>
)
})
function TestFrameworkImage({ src, ...props }: FrameworkImageProps) {
return <DefaultFrameworkImage {...props} src={applyBasePath(resolveStaticImageSrc(src))} />
}
export const createTestRouter = (
initialUrl = '/',
routeTree: AnyRoute = createRootRoute()
): AnyRouter =>
createRouter({
routeTree,
history: createMemoryHistory({ initialEntries: [initialUrl] }),
parseSearch,
stringifySearch,
})
const TestRouterProvider = ({
children,
router,
initialUrl = '/',
}: {
children: React.ReactNode
router?: AnyRouter
initialUrl?: string
}) => {
const activeRouter = useMemo(() => router ?? createTestRouter(initialUrl), [router, initialUrl])
return <RouterContextProvider router={activeRouter}>{children}</RouterContextProvider>
}
const TestFrameworkProvider = ({ children }: { children: React.ReactNode }) => {
const router = useTanStackRouter()
const location = useRouterState({
select: (state) => state.resolvedLocation ?? state.location,
})
const stateMatches = useRouterState({
select: (state) => state.matches,
})
const value = useMemo<FrameworkContextValue>(() => {
const matches = stateMatches.length > 0 ? stateMatches : router.matchRoutes(location)
const leafMatch = matches[matches.length - 1]
const leafRouteId =
leafMatch && leafMatch.routeId !== '__root__' ? leafMatch.routeId : location.pathname
const pathname = toRoutePattern(leafRouteId)
const asPath = location.href
const routeParams = leafMatch?.params as Record<string, unknown> | undefined
const searchParams =
(leafMatch?.search as Record<string, unknown> | undefined) ??
(location.search as Record<string, unknown> | undefined)
const params = normalizeParams(searchParams, routeParams)
return {
Link: TestFrameworkLink,
Image: TestFrameworkImage,
pathname,
asPath,
isReady: true,
params,
push: async (path: string) => {
await navigateToUrl(
router.navigate,
resolveSearchOrHashOnlyTarget(path, location.pathname, location.searchStr)
)
},
}
}, [location, router, stateMatches])
return <FrameworkProvider value={value}>{children}</FrameworkProvider>
}
export const CustomWrapper = ({
children,
queryClient,
nuqs,
profileContext,
authContext,
router,
initialUrl,
}: {
children: React.ReactNode
queryClient?: QueryClient
nuqs?: AdapterProps
profileContext?: ProfileContextType
authContext?: AuthContext
router?: AnyRouter
initialUrl?: string
}) => {
const _queryClient =
queryClient ??
new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
let content = (
<TestRouterProvider router={router} initialUrl={initialUrl}>
<TestFrameworkProvider>
<QueryClientProvider client={_queryClient}>
<NuqsTestingAdapter {...nuqs}>
<TooltipProvider>
<CommandProvider openKey="">{children}</CommandProvider>
</TooltipProvider>
</NuqsTestingAdapter>
</QueryClientProvider>
</TestFrameworkProvider>
</TestRouterProvider>
)
if (profileContext) {
content = <ProfileContext.Provider value={profileContext}>{content}</ProfileContext.Provider>
}
if (authContext) {
content = <AuthContext.Provider value={authContext}>{content}</AuthContext.Provider>
}
return content
}
type CustomRenderOpts = RenderOptions & {
queryClient?: QueryClient
nuqs?: AdapterProps
profileContext?: ProfileContextType
authContext?: AuthContextType
router?: AnyRouter
initialUrl?: string
}
export const customRender = (component: React.ReactElement, renderOptions?: CustomRenderOpts) => {
const router = renderOptions?.router ?? createTestRouter(renderOptions?.initialUrl)
const result = render(component, {
wrapper: ({ children }) =>
CustomWrapper({
queryClient: renderOptions?.queryClient,
nuqs: renderOptions?.nuqs,
profileContext: renderOptions?.profileContext,
authContext: renderOptions?.authContext,
router,
children,
}),
...renderOptions,
})
return { ...result, router }
}
export const customRenderHook = <T,>(hook: () => T, renderOptions?: CustomRenderOpts) => {
const router = renderOptions?.router ?? createTestRouter(renderOptions?.initialUrl)
const result = renderHook(hook, {
wrapper: ({ children }) =>
CustomWrapper({
children,
queryClient: renderOptions?.queryClient,
nuqs: renderOptions?.nuqs,
profileContext: renderOptions?.profileContext,
authContext: renderOptions?.authContext,
router,
}),
...renderOptions,
})
return { ...result, router }
}