Files
supabase/apps/studio/components/interfaces/Functions/FunctionLogsNavigation.platform.test.tsx
Alaister YoungandAlaister Young 477e2c136f [FE-5109] (part 6) chore(studio): remove next/router shims, aliases, and test mocks (#54058)
Part 6 (final) of a 6-PR stack migrating all `next/router` and
`next/compat/router` imports in `apps/studio` onto TanStack Router hooks
and removing the router shims.

| Part | PR | Scope |
| --- | --- | --- |
| 1 | #54053 | Core navigation helpers, `hooks/**`, `lib/**`,
`data/prefetchers/**` |
| 2 | #54054 | `components/ui/**` |
| 3 | #54055 | `components/layouts/**` and `state/tabs.tsx` |
| 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer,
SQL Editor, Storage, Table Editor |
| 5 | #54057 | Remaining `components/interfaces/**` and
`QueryInsightsTable` router events |
| **6** | **#54058 ← this PR** | **Remove `next/router` &
`next/compat/router` shims, `_router-events.ts`, Vite aliases, and test
mocks** |

Now that no files in `apps/studio` (or `packages/**`) import
`next/router` or `next/compat/router`, deletes the router shims,
`_router-events.ts`, their Vite aliases, and the obsolete router test
mocks. `RouteValidationWrapper` is intentionally left for FE-3107.

**Removed:**

- `apps/studio/compat/next/router.ts`,
`apps/studio/compat/next/compat/router.ts`, and
`apps/studio/compat/next/_router-events.ts`
- `'next/router'` and `'next/compat/router'` entries from `nextShims` in
`apps/studio/vite.config.ts`
- Global `vi.mock('next/router', ...)` and
`vi.mock('next/compat/router', ...)` in
`apps/studio/tests/vitestSetup.ts`, `mockNextRouter` in
`apps/studio/tests/lib/route-aware-hooks.ts`, and the unused
`vi.mock('next/router')` in `tests/features/logs/LogTable.test.tsx`
- Obsolete shim tests and test helpers: `compat/next/router.test.ts`,
`compat/next/router-navigation.test.tsx`, `tests/config/router.tsx`, and
`tests/config/router.test.tsx`

**Changed:**

- Simplified `createNavigationHandler` in
`apps/studio/lib/navigation.ts` (and `navigation.test.ts`) to accept
TanStack's `UseNavigateResult<string>` only, dropping the `NextRouter`
union branch
- Updated `compat/next/link-basepath-navigation.test.tsx` (renamed from
`router-basepath-navigation.test.tsx`), `lib/router-url-shape.test.tsx`,
and `tests/lib/route-render.test.tsx` to exercise TanStack Router hooks
directly instead of the removed router shim
- Cleaned up stale `next/router` comments in `compat/next/link.tsx`,
`lib/internal-url.ts`, `router.tsx`, and `tests/lib/route-mock.ts`

**Simplified:**

- Removed `routerMock` setup from about 19 tests that no longer read it.
`next-router-mock` stays for now, because the test `FrameworkProvider`
still feeds `useParams` from it.
- `AGENTS.md` and the `vite.config.ts` error text now say only
`next/link` and `next/script` are shimmed
- Renamed `compat/next/router-basepath-navigation.test.tsx` to
`link-basepath-navigation.test.tsx`, and removed stale router-shim
references from comments

Addresses
[FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks)

## To test

- [ ] Confirm `git grep -E "next/(compat/)?router|_router-events"
apps/studio` returns no code or config imports (only the prose guideline
in `apps/studio/AGENTS.md`)
- [ ] Confirm `pnpm --filter studio run typecheck`, `pnpm --filter
studio run lint`, `pnpm --filter studio run build`, Knip, and the full
Studio Vitest suite pass
- [ ] Spot-check basePath navigation (`next/link` + `navigateToUrl`) and
multi-line query param URLs in Studio

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 15:04:27 +08:00

220 lines
8.0 KiB
TypeScript

import { QueryClient } from '@tanstack/react-query'
import { useLocation, useNavigate } from '@tanstack/react-router'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { FeatureFlagContext, LOCAL_STORAGE_KEYS } from 'common'
import { HttpResponse } from 'msw'
import { useCallback } from 'react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { useFunctionLogsMigration } from './useFunctionLogsMigration'
import { useFunctionsDetailShortcuts } from './useFunctionsDetailShortcuts'
import { FeaturePreviewContextProvider } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import type { EdgeFunction } from '@/data/edge-functions/edge-function-query'
import { navigateToUrl } from '@/lib/navigation'
import { Route as FunctionInvocationsRoute } from '@/routes/project/$ref/functions/$functionSlug/invocations'
import { Route as FunctionLogsRoute } from '@/routes/project/$ref/functions/$functionSlug/logs'
import { customRender, CustomWrapper } from '@/tests/lib/custom-render'
import { addAPIMock } from '@/tests/lib/msw'
import { renderRoute } from '@/tests/lib/route-render'
vi.unmock('common')
vi.mock('@/components/interfaces/UnifiedLogs/UnifiedLogs', () => ({
UnifiedLogs: () => <div>Unified logs</div>,
}))
const featureFlags = {
configcat: {
otelLegacyLogs: true,
pipelineCreationWizard: false,
platformWebhooks: false,
jitDbAccess: false,
explorer: false,
storageVersioningPrivateAlpha: false,
sqlEditorManualSaveForced: false,
},
posthog: {},
hasLoaded: true,
}
const FunctionPageProviders = ({
children,
queryClient,
}: {
children: React.ReactNode
queryClient?: QueryClient
}) => (
<CustomWrapper queryClient={queryClient}>
<FeatureFlagContext.Provider value={featureFlags}>
<FeaturePreviewContextProvider>{children}</FeaturePreviewContextProvider>
</FeatureFlagContext.Provider>
</CustomWrapper>
)
beforeEach(() => {
localStorage.setItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS, 'true')
})
afterEach(() => {
localStorage.removeItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS)
})
it('forwards an invocation bookmark with its selected log, message, and time range to Logs', async () => {
const legacy = new URLSearchParams({
its: '2026-03-20T10:00:00Z',
ite: '2026-03-20T11:00:00Z',
log: 'selected-invocation',
s: 'delivery failed',
})
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/functions/:function_slug',
response: () =>
HttpResponse.json<EdgeFunction>({
id: 'function-id',
name: 'Send email',
slug: 'send-email',
status: 'ACTIVE',
version: 1,
created_at: 1774000800000,
updated_at: 1774000800000,
}),
})
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const { router } = await renderRoute(FunctionInvocationsRoute, {
routeId: '/project/$ref/functions/$functionSlug/invocations',
url: `/project/default/functions/send-email/invocations?${legacy}`,
renderOptions: {
wrapper: ({ children }) => (
<FunctionPageProviders queryClient={queryClient}>{children}</FunctionPageProviders>
),
},
})
await waitFor(() =>
expect(router.state.location.pathname).toBe('/project/default/functions/send-email/logs')
)
const params = new URLSearchParams(router.state.location.searchStr)
expect(params.get('id')).toBe('selected-invocation')
expect(params.get('filter')).toBe('event_message:ilike:delivery failed')
expect(params.get('date')).toBe('1774000800000-1774004400000')
})
function FunctionLogNavigation({ isEnabled = true, isLoading = false }) {
const asPath = useLocation({ select: (location) => location.href })
const navigate = useNavigate()
const onReplace = useCallback(
(url: string) => void navigateToUrl(navigate, url, { replace: true }),
[navigate]
)
const state = useFunctionLogsMigration({
asPath,
onReplace,
projectRef: 'default',
functionSlug: 'send-email',
isEnabled,
isLoading,
})
return <div>{state.shouldUseLegacyLogs ? 'Legacy logs' : 'Unified logs'}</div>
}
it('waits for preview initialization and leaves preview opt-outs on their original bookmark', async () => {
const bookmark = '/project/default/functions/send-email/logs?log=legacy-log'
const { router, rerender } = customRender(<FunctionLogNavigation isLoading />, {
initialUrl: bookmark,
})
expect(router.state.location.href).toBe(bookmark)
rerender(<FunctionLogNavigation isEnabled={false} />)
expect(router.state.location.href).toBe(bookmark)
rerender(<FunctionLogNavigation />)
await waitFor(() => expect(router.state.location.search).toMatchObject({ id: 'legacy-log' }))
})
it('migrates a new legacy Logs bookmark during client-side navigation', async () => {
const { router } = customRender(<FunctionLogNavigation />, {
initialUrl: '/project/default/functions/send-email/logs',
})
await act(async () => {
await navigateToUrl(router.navigate, '/project/default/functions/send-email/logs?log=first')
})
await waitFor(() => expect(router.state.location.search).toMatchObject({ id: 'first' }))
await act(async () => {
await navigateToUrl(router.navigate, '/project/default/functions/send-email/logs?log=second')
})
await waitFor(() => expect(router.state.location.search).toMatchObject({ id: 'second' }))
})
it('retains the old function log filters when their meaning cannot migrate to unified filters', () => {
const filter = encodeURIComponent(JSON.stringify({ severity: { error: true } }))
const bookmark = `/project/default/functions/send-email/logs?f=${filter}`
const { router } = customRender(<FunctionLogNavigation />, { initialUrl: bookmark })
expect(screen.getByText('Legacy logs')).toBeVisible()
expect(router.state.location.href).toBe(bookmark)
})
function FunctionDetailNavigation({ hasInvocationsTab }: { hasInvocationsTab: boolean }) {
useFunctionsDetailShortcuts({
projectRef: 'default',
functionSlug: 'send-email',
canReadFunctions: true,
isPlatform: true,
hasInvocationsTab,
onOpenTest: () => {},
onOpenDownload: () => {},
onCopyUrl: () => {},
})
return <div>Function navigation</div>
}
it('disables the hidden Invocations shortcut while preserving Logs navigation', async () => {
const user = userEvent.setup()
const { router, rerender } = customRender(
<FunctionDetailNavigation hasInvocationsTab={false} />,
{ initialUrl: '/project/default/functions/send-email' }
)
await user.keyboard('2')
expect(router.state.location.href).toBe('/project/default/functions/send-email')
await user.keyboard('3')
await waitFor(() =>
expect(router.state.location.href).toBe('/project/default/functions/send-email/logs')
)
rerender(<FunctionDetailNavigation hasInvocationsTab />)
await user.keyboard('2')
await waitFor(() =>
expect(router.state.location.href).toBe('/project/default/functions/send-email/invocations')
)
})
it('opens a selected log from an old Logs bookmark using the unified time range', async () => {
const legacy = new URLSearchParams({
its: '2026-03-20T10:00:00Z',
ite: '2026-03-20T11:00:00Z',
log: 'runtime-message',
})
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/functions/:function_slug',
response: () =>
HttpResponse.json<EdgeFunction>({
id: 'function-id',
name: 'Send email',
slug: 'send-email',
status: 'ACTIVE',
version: 1,
created_at: 1774000800000,
updated_at: 1774000800000,
}),
})
const { router } = await renderRoute(FunctionLogsRoute, {
routeId: '/project/$ref/functions/$functionSlug/logs',
url: `/project/default/functions/send-email/logs?${legacy}`,
renderOptions: { wrapper: FunctionPageProviders },
})
expect(await screen.findByText('Unified logs')).toBeVisible()
const params = new URLSearchParams(router.state.location.searchStr)
expect(params.get('id')).toBe('runtime-message')
expect(params.get('date')).toBe('1774000800000-1774004400000')
expect(params.get('log')).toBeNull()
})