Files
supabase/apps/studio/lib/chunk-load-error.test.ts
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

281 lines
9.7 KiB
TypeScript

import { afterEach, describe, expect, test, vi } from 'vitest'
import {
CHUNK_LOAD_RELOAD_GUARD_MS,
CHUNK_LOAD_RELOAD_MAX_PER_TAB,
CHUNK_LOAD_RELOAD_STORAGE_KEY,
claimChunkLoadReload,
getChunkLoadReloadDecision,
isChunkLoadError,
peekChunkLoadReload,
shouldReloadForChunkError,
} from './chunk-load-error'
function createStorage(initial: Record<string, string> = {}) {
const values = new Map(Object.entries(initial))
return {
values,
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => {
values.set(key, value)
},
}
}
function reloadState(at: number, count = 1) {
return JSON.stringify({ at, count })
}
function chunkError() {
return new TypeError(
'Failed to fetch dynamically imported module: https://supabase.com/dashboard/assets/database-abc123.js'
)
}
describe('isChunkLoadError', () => {
test.each([
[
'Chrome',
new TypeError(
'Failed to fetch dynamically imported module: https://supabase.com/dashboard/assets/a.js'
),
],
[
'Firefox',
new TypeError(
'error loading dynamically imported module: https://supabase.com/dashboard/assets/a.js'
),
],
['Safari / WebKit', new TypeError('Importing a module script failed.')],
[
'Safari / WebKit CORS-denied module',
new TypeError('Cross-origin script load denied by Cross-Origin Resource Sharing policy.'),
],
['Vite CSS preload', new Error('Unable to preload CSS for /dashboard/assets/a.css')],
['ChunkLoadError name', Object.assign(new Error('something else'), { name: 'ChunkLoadError' })],
['plain object', { message: 'Importing a module script failed.' }],
])('detects %s', (_label, error) => {
expect(isChunkLoadError(error)).toBe(true)
})
test.each([
['generic error', new Error('Cannot read properties of undefined')],
['network fetch', new TypeError('Failed to fetch')],
[
'CORS-denied fetch',
new TypeError('Origin https://example.com is not allowed by Access-Control-Allow-Origin.'),
],
['DOM error', new Error("Failed to execute 'removeChild' on 'Node'")],
['string', 'Importing a module script failed.'],
['null', null],
['undefined', undefined],
['non-string message', { message: 42 }],
])('ignores %s', (_label, error) => {
expect(isChunkLoadError(error)).toBe(false)
})
})
describe('shouldReloadForChunkError', () => {
const now = 1_700_000_000_000
test.each([
['no previous reload', null, true],
['reload just now', now, false],
['reload inside the window', now - CHUNK_LOAD_RELOAD_GUARD_MS + 1, false],
['reload exactly at the window edge', now - CHUNK_LOAD_RELOAD_GUARD_MS, true],
['reload long ago', now - 60 * 60 * 1000, true],
['reload in the future (clock skew)', now + 5_000, false],
])('%s', (_label, lastReloadAt, expected) => {
expect(shouldReloadForChunkError({ now, lastReloadAt })).toBe(expected)
})
test('respects a custom window', () => {
expect(shouldReloadForChunkError({ now, lastReloadAt: now - 1_000, guardMs: 500 })).toBe(true)
})
})
describe('claimChunkLoadReload', () => {
const now = 1_700_000_000_000
test('reloads and records the time when there is no previous reload', () => {
const storage = createStorage()
expect(claimChunkLoadReload(chunkError(), { storage, now })).toBe(true)
expect(storage.values.get(CHUNK_LOAD_RELOAD_STORAGE_KEY)).toBe(reloadState(now, 1))
})
test('does not reload for non-chunk errors and leaves storage alone', () => {
const storage = createStorage()
expect(claimChunkLoadReload(new Error('boom'), { storage, now })).toBe(false)
expect(storage.values.size).toBe(0)
})
test('falls through to the error UI when a reload happened within the window', () => {
const storage = createStorage({ [CHUNK_LOAD_RELOAD_STORAGE_KEY]: reloadState(now - 1_000) })
expect(claimChunkLoadReload(chunkError(), { storage, now })).toBe(false)
expect(storage.values.get(CHUNK_LOAD_RELOAD_STORAGE_KEY)).toBe(reloadState(now - 1_000))
})
test('reloads again for the same message once the window has passed', () => {
const storage = createStorage()
const safariError = () => new TypeError('Importing a module script failed.')
expect(claimChunkLoadReload(safariError(), { storage, now })).toBe(true)
expect(claimChunkLoadReload(safariError(), { storage, now: now + 1_000 })).toBe(false)
expect(
claimChunkLoadReload(safariError(), { storage, now: now + CHUNK_LOAD_RELOAD_GUARD_MS })
).toBe(true)
})
test.each([
['not JSON', 'not-a-number'],
['wrong shape', JSON.stringify({ at: 'yesterday', count: 1 })],
['negative count', JSON.stringify({ at: 0, count: -1 })],
])('treats a malformed stored value (%s) as no previous reload', (_label, raw) => {
const storage = createStorage({ [CHUNK_LOAD_RELOAD_STORAGE_KEY]: raw })
expect(claimChunkLoadReload(chunkError(), { storage, now })).toBe(true)
expect(storage.values.get(CHUNK_LOAD_RELOAD_STORAGE_KEY)).toBe(reloadState(now, 1))
})
test('counts reloads and stops at the per-tab cap, even outside the window', () => {
const storage = createStorage()
let time = now
for (let i = 1; i <= CHUNK_LOAD_RELOAD_MAX_PER_TAB; i++) {
expect(claimChunkLoadReload(chunkError(), { storage, now: time })).toBe(true)
expect(storage.values.get(CHUNK_LOAD_RELOAD_STORAGE_KEY)).toBe(reloadState(time, i))
time += CHUNK_LOAD_RELOAD_GUARD_MS
}
expect(claimChunkLoadReload(chunkError(), { storage, now: time + 60 * 60 * 1000 })).toBe(false)
})
test('does not reload when storage silently drops the write', () => {
const storage = { getItem: () => null, setItem: vi.fn() }
expect(claimChunkLoadReload(chunkError(), { storage, now })).toBe(false)
expect(storage.setItem).toHaveBeenCalledTimes(1)
})
test('does not reload when storage cannot be read', () => {
const storage = {
getItem: () => {
throw new Error('SecurityError')
},
setItem: vi.fn(),
}
expect(claimChunkLoadReload(chunkError(), { storage, now })).toBe(false)
expect(storage.setItem).not.toHaveBeenCalled()
})
test('does not reload when the guard cannot be written', () => {
const storage = {
getItem: () => null,
setItem: () => {
throw new Error('QuotaExceededError')
},
}
expect(claimChunkLoadReload(chunkError(), { storage, now })).toBe(false)
})
test('does not reload without storage (SSR)', () => {
expect(claimChunkLoadReload(chunkError(), { storage: undefined, now })).toBe(false)
})
})
describe('peekChunkLoadReload', () => {
const now = 1_700_000_000_000
test('agrees with claimChunkLoadReload without writing to storage', () => {
const storage = createStorage()
const setItem = vi.spyOn(storage, 'setItem')
expect(peekChunkLoadReload(chunkError(), { storage, now })).toBe(true)
expect(peekChunkLoadReload(chunkError(), { storage, now })).toBe(true)
expect(setItem).not.toHaveBeenCalled()
expect(claimChunkLoadReload(chunkError(), { storage, now })).toBe(true)
expect(peekChunkLoadReload(chunkError(), { storage, now: now + 1_000 })).toBe(false)
expect(
peekChunkLoadReload(chunkError(), { storage, now: now + CHUNK_LOAD_RELOAD_GUARD_MS })
).toBe(true)
})
test.each([
['non-chunk error', new Error('boom'), createStorage()],
['missing storage', chunkError(), undefined],
[
'unreadable storage',
chunkError(),
{
getItem: () => {
throw new Error('SecurityError')
},
setItem: vi.fn(),
},
],
[
'per-tab cap reached',
chunkError(),
createStorage({
[CHUNK_LOAD_RELOAD_STORAGE_KEY]: reloadState(0, CHUNK_LOAD_RELOAD_MAX_PER_TAB),
}),
],
])('is false for %s', (_label, error, storage) => {
expect(peekChunkLoadReload(error, { storage, now })).toBe(false)
})
})
describe('getChunkLoadReloadDecision', () => {
afterEach(() => {
vi.unstubAllGlobals()
vi.useRealTimers()
})
test('returns false on the server', () => {
expect(typeof window).toBe('undefined')
expect(getChunkLoadReloadDecision(chunkError())).toBe(false)
})
test('returns the same decision for the same error object and claims the guard once', () => {
vi.useFakeTimers()
vi.setSystemTime(1_700_000_000_000)
const storage = createStorage()
const setItem = vi.spyOn(storage, 'setItem')
vi.stubGlobal('window', { sessionStorage: storage })
const error = chunkError()
expect(getChunkLoadReloadDecision(error)).toBe(true)
expect(getChunkLoadReloadDecision(error)).toBe(true)
expect(setItem).toHaveBeenCalledTimes(1)
// A different error inside the window is guarded
expect(getChunkLoadReloadDecision(chunkError())).toBe(false)
})
test('re-evaluates a refused error object once the window has passed', () => {
vi.useFakeTimers()
vi.setSystemTime(1_700_000_000_000)
vi.stubGlobal('window', { sessionStorage: createStorage() })
expect(getChunkLoadReloadDecision(chunkError())).toBe(true)
// A retry rethrows the same error object (React.lazy caches the rejection)
const retried = chunkError()
expect(getChunkLoadReloadDecision(retried)).toBe(false)
expect(getChunkLoadReloadDecision(retried)).toBe(false)
vi.advanceTimersByTime(CHUNK_LOAD_RELOAD_GUARD_MS)
expect(getChunkLoadReloadDecision(retried)).toBe(true)
})
test('returns false when sessionStorage access throws', () => {
vi.stubGlobal('window', {
get sessionStorage() {
throw new Error('SecurityError')
},
})
expect(getChunkLoadReloadDecision(chunkError())).toBe(false)
})
test('returns false for non-object errors', () => {
expect(getChunkLoadReloadDecision('Importing a module script failed.')).toBe(false)
})
})