mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
docs/tutorial-template
34
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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>
|
||
|
|
b6c391a058 |
[FE-5114] (part 1) – refactor(studio): add native API helpers & routes (#54028)
## Problem Studio's `routes/api/**` server routes still run legacy Next Pages Router handlers through the `toWebHandler` shim in `compat/next/api.ts`. Part 1 of 7 for [FE-5114](https://linear.app/supabase/issue/FE-5114/rewrite-api-routes-as-native-tanstack-start-handlers-and-remove-the) adds native TanStack Start (`Request` → `Response`) helpers and migrates the top-level utility routes so we can remove the adapter at the end of the stack. ## Solution **Added:** - `createApiHandlers` in `lib/api/apiWrapper.ts`: wraps native TanStack Start route handlers with optional platform JWT auth, JSON `400` (`{ error: { message: 'Invalid JSON' } }`) on `InvalidJsonError`, Sentry capture + generic `500` on unexpected throws, and an `ANY` handler that returns `405` with an `Allow` header derived from the registered methods. Exports `ApiHandler` / `ApiHandlerContext` (`params` is `Record<string, string>`) - `authenticateRequest` in `lib/api/apiAuthenticate.ts` (Web `Request` counterpart of `apiAuthenticate`, same error messages) - `InvalidJsonError` and `parseJsonBody` in `lib/api/apiHelpers.ts` - `callRoute(route, request, params)` test helper in `tests/lib/server-route.ts` - Unit tests for `createApiHandlers` (exercising real `authenticateRequest` through MSW in `lib/api/createApiHandlers.test.ts`), `authenticateRequest`, `parseJsonBody`, `/api/generate-attachment-url`, and `/api/integrations/stripe-sync` **Changed:** - Updated `getRouteHandler` in `tests/lib/server-route.ts` to mirror TanStack Start's `HEAD` → `GET` → `ANY` dispatch order - Migrated 11 top-level API routes (`check-cname`, `cli-release-version`, `content/graphql`, `edge-functions/test`, `enabled-features-overrides`, `generate-attachment-url`, `get-deployment-commit`, `get-ip-address`, `get-s3-keys`, `get-utc-time`, `integrations/stripe-sync`) to native handlers - Added `withAuth: true` to `check-cname`, `content/graphql`, and `integrations/stripe-sync`, and updated `check-cname-mutation.ts` and `data/graphql/execute.ts` to attach `constructHeaders()` - Reused `withAuth` `claims` in `generate-attachment-url` to avoid a duplicate GoTrue lookup in platform mode - Converted `tests/routes/api/get-deployment-commit.test.ts` to `callRoute` **Removed:** - Removed 2 unused routes (`routes/api/connect/index.ts` and `routes/api/parse-query.ts`), dropped `/parse-query` from `lib/hosted-api-allowlist.ts`, removed Nitro's `traceDeps: ['libpg-query*']` in `vite.config.ts` (no server runtime route imports `libpg-query` anymore), and regenerated `routeTree.gen.ts` **Behavior changes vs master:** - Methods a route doesn't register now get a JSON `405` with an `Allow` header (previously they fell through to the SSR app). `HEAD` requests that TanStack Start dispatches to a `GET` handler also get `405`, matching master's method switches - `InvalidJsonError` returns JSON `{ error: { message: 'Invalid JSON' } }` (`400`) instead of plain text - `check-cname`, `content/graphql`, and `integrations/stripe-sync` now verify the platform JWT via `withAuth: true` - Unexpected throws return a generic `500` with `{ error: { message: 'Internal Server Error' } }` - Unused `/api/connect` and `/api/parse-query` routes have been removed ## Review instructions 1. Run `pnpm --filter studio exec vitest run lib/api/apiAuthenticate.test.ts lib/api/apiHelpers.test.ts lib/api/apiWrappers.test.ts lib/api/createApiHandlers.test.ts tests/routes/api/ scripts/__tests__/server-source-maps.test.ts`. 2. Smoke-test `/api/get-deployment-commit`, `/api/check-cname`, `/api/content/graphql`, `/api/generate-attachment-url`, and `/api/edge-functions/test` in Studio and confirm unsupported HTTP methods return `405` with an `Allow` header. ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide) --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
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> |
||
|
|
d98f706b7c |
[FE-5109] (part 1) refactor(studio): migrate core hooks, lib, and prefetchers off next/router (#54053)
Part 1 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 ← this PR** | **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 | Remove `next/router` & `next/compat/router` shims, `_router-events.ts`, Vite aliases, and test mocks | Introduces the shared TanStack navigation helpers needed across the stack and migrates `hooks/**`, `lib/**`, and `data/prefetchers/**` off `next/router`. **Added:** - `navigateToUrl` in `apps/studio/lib/navigation.ts` (plus unit tests in `lib/navigation.test.ts`): shared helper for navigating to internal string URLs via TanStack's `useNavigate` (splitting pathname, search params, and hash via `splitInternalUrl`, and handling external/protocol-relative URLs) - `useRoutePattern` in `apps/studio/hooks/misc/useRoutePattern.ts` (plus `useRoutePattern.test.tsx`): returns the active matched TanStack route template (e.g. `/project/$ref/editor/$id`) as the replacement for Next's `router.pathname` **Changed:** - Migrated `hooks/misc/*` (`useHydratedQuery`, `useStudioCommandMenuTelemetry`, `useTableEditorFiltersSort`, `withAuth`) and `hooks/use-check-latest-deploy.tsx` to TanStack's `useLocation`, `useNavigate`, `useRoutePattern`, and `useParams` from `common` - Migrated `lib/profile.tsx` and `lib/telemetry/track.ts` off `next/router` - Migrated `data/prefetchers/project.$ref.tsx`, `project.$ref.editor.tsx`, and `project.$ref.editor.$id.tsx` to `useRouter().preloadRoute` - Wrapped `ReactQueryTestConfig` in `apps/studio/tests/helpers.tsx` with `RouterContextProvider` and updated hook/navigation tests (`useTableEditorFiltersSort*.test.*`, `useFilterLifeCycle.navigation.test.tsx`, `useTableFilter.navigation.test.tsx`, `useInboundBranding.test.ts`, `state/tabs.test.ts`) **Simplified:** - `navigateToUrl` passes `replace` straight through and documents that `url` must be an app-relative path or an external URL. `StudioFrameworkProvider`'s `push` now reuses it. - `useRoutePattern` reads matches and location in a single `useRouterState` subscription - `useTrack` and `useStudioCommandMenuTelemetry` take the pathname from `useFramework()`, the same source as pageviews, so custom events and pageviews always send the same pattern (e.g. `/project/[ref]/sql/[id]`). New tests pin the strings sent, and `toRoutePattern` now has its own unit tests. - Removed `useCurrentPath` (a one-line wrapper with one consumer): `OrganizationSettingsLayout` calls `useLocation` directly - Dropped the no-op `.catch(() => {})` on `preloadRoute` in the prefetchers (`preloadRoute` never rejects) - `useTableEditorFiltersSort` builds the next search with a spread instead of a delete loop - Added `createTestRouter()` to `tests/lib/custom-render.tsx`, and `customRender`/`customRenderHook` now return the `router`. The rest of the stack uses these instead of hand-copied `createRouter` setups. Addresses [FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks) ## To test - [ ] Auth redirect flow (`withAuth`) still preserves `returnTo` query parameters when redirecting unauthenticated users to `/sign-in` - [ ] Table Editor sort and filter URL sync (`useTableEditorFiltersSort`) persists and clears `?sort=` / `?filter=` across table switches - [ ] Hovering project and table editor links still triggers route/data prefetching without console errors - [ ] Page view and command menu telemetry still records route patterns and paths accurately --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
953e508a3e |
[FE-5110] refactor(studio): replace next/navigation with TanStack (#54041)
Moves the remaining `next/navigation` imports in Studio onto TanStack
Router hooks (and `useParams` from `common`), finishes migrating the
remaining `next/link` and `next/router` usages in the touched
components, and removes the `compat/next/navigation.ts` shim and its
Vite alias. Shared packages (`packages/**`) no longer import
`next/navigation`, so the alias can be dropped now.
**Removed:**
- `apps/studio/compat/next/navigation.ts` and the `'next/navigation'`
entry in `apps/studio/vite.config.ts`
- Global `next/navigation` mock in `apps/studio/tests/vitestSetup.ts`
and the obsolete `apps/studio/tests/lib/route-mock.test.tsx`
**Changed:**
- Replaced `usePathname` (12 files) and `useSearchParams` (3 files) with
`useLocation({ select })` from `@tanstack/react-router`
- Replaced `useRouter` in Storage bucket tables, SQL Editor commands,
and `SignInMfaForm` with `useNavigate` from `@tanstack/react-router`,
and updated `createNavigationHandler` in `lib/navigation.ts` to accept
either `NextRouter` or TanStack's `useNavigate`
- Replaced remaining `next/link` imports in touched components
(`SignInMfaForm`, `Restriction`, `DownloadLogsButton`,
`DownloadResultsButton`, `AuthEmailsLayout`, `AuthProvidersLayout`,
`JWTKeysLayout`, `StorageBucketsLayout`) with TanStack Router's `Link`
- Replaced `useParams` in `CreatePublishableAPIKeyDialog` with
`useParams` from `common` (matching `CreateSecretAPIKeyDialog`)
- Wrapped `CustomWrapper` (`tests/lib/custom-render.tsx`) in a default
TanStack `RouterContextProvider` (with optional `router` / `initialUrl`
overrides) and updated affected component tests to drop their
`next/navigation` mocks
Addresses
[FE-5110](https://linear.app/supabase/issue/FE-5110/replace-the-nextnavigation-shim-with-tanstack-router-hooks)
## To test
1. Check active tab highlighting and navigation across Auth Emails, Auth
Providers, JWT Keys, Storage Buckets, and Editor layouts
2. Verify clicking, Cmd/Ctrl-clicking, middle-clicking, and pressing
Enter on Storage bucket rows (Files, Analytics, Vector) navigates as
before
3. Run "Query a table..." and open SQL snippets from the Command Menu
and confirm `/project/$ref/sql/$id` opens with multi-line SQL preserved
in `?content=`
4. In the MFA sign-in flow, verify the recovery code link and
`forgot-password` completion preserve query params (`returnTo`,
`context=forgot-password`), and Cancel signs out and replaces history
with `/sign-in`
5. Confirm Table Editor sort/filter URL sync persists filters per table
without leaking across table switches
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
|
||
|
|
d6e4089b1a |
feat(common): add FrameworkProvider and remove next imports (#53905)
Introduces a lightweight `FrameworkProvider` React context in `packages/common` (`Link`, `Image`, `pathname`, `asPath`, `isReady`, `params`, `push`), wires it up in the consuming apps, and removes the `next` dependency from `packages/common`. **Added:** - `FrameworkProvider`, `useFramework`, `FrameworkLink`, and `FrameworkImage` in `packages/common/framework.tsx`, with plain HTML defaults (`DefaultFrameworkLink` / `DefaultFrameworkImage`). `useFramework().push` always exists and falls back to `window.location.assign` - App-level framework providers wiring `next/link`, `next/image`, and router state in `www` (App + Pages routers), `docs`, `design-system`, `learn`, and `ui-library`, and native TanStack Router bindings in `studio` (`StudioFrameworkProvider`) - `StudioFrameworkProvider` reuses the common defaults (its image only applies the basePath) and reports `isReady` once the first route load commits, so the first page view carries the final route after any redirect - Unit tests for `StudioFrameworkProvider` (`useParams`, `FrameworkLink`, `FrameworkImage`, query/hash-only navigation, `isReady`) and for `PageTelemetry` route-change sends and the `TelemetryTagManager` consent gate **Changed:** - `common/hooks/useParams.ts`: read params from `useFramework()` instead of `next/compat/router` - `common/telemetry.tsx`: replace `next/script` in `TelemetryTagManager` with `useEffect` script injection, and read route state from `useFramework()` in `PageTelemetry` - `common/MetaFavicons/app-router.ts`: drop type-only `Metadata` import from `next` - Moved `MetaFaviconsPagesRouter` to `apps/www/components/MetaFaviconsPagesRouter.tsx` (its sole consumer) - Studio: `toRoutePattern` and `applyBasePath` now live once in `lib/internal-url.ts`, shared by the provider and the `compat/next` shims - `PageTelemetry` throws outside production when no `FrameworkProvider` is mounted, since it would otherwise send only the landing pageview. `useFramework()` itself still falls back to the defaults - `ui-library`: renamed its code-sample framework context to `FrameworkPreferenceProvider` / `useFrameworkPreference` so `FrameworkProvider` only means the `common` one **Removed:** - `learn`'s unused copy of that context (`useCourse` had no callers) - `next` from `packages/common/package.json` peerDependencies App Router adapters set `asPath` to the pathname only, same as the `usePathname`-based telemetry on master (reading search params at the root would opt static pages out of static rendering). ## To test - Run `packages/common` tests and typecheck, and `apps/studio` `StudioFrameworkProvider` / `route-render` / `telemetry` tests - Navigate between routes in Studio, Docs, and WWW and confirm page telemetry fires once per navigation (and does not duplicate on hash-only changes) - Load Studio at `/` (which redirects) and confirm the first page event has the final route - Verify URL params (`useParams`) continue resolving route and search params in Studio --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
960cf92854 |
[FE-5150] fix(studio): make router hooks follow renderRoute's URL in tests (#53660)
In Studio's vitest setup, `useParams` from `common` is mocked globally
to return `{ ref: 'default' }`, and `next/router`, `next/compat/router`
and `next/navigation` are mocked with `next-router-mock`. `renderRoute`
mounts a real TanStack memory router, but nothing connected it to those
mocks. So components under a route test never saw the route's path or
search params, and `router.push` from legacy code never moved the
TanStack router. Route tests worked around this by hand-mocking
`useParams` to repeat their URL.
Inside `renderRoute`, these hooks now defer to the app's own
`compat/next` shims, which read the memory router, so they match
runtime: kebab-case keys are camelCased, repeated keys collapse to the
first value, and the hooks follow in-test navigation. All other tests
keep the static mocks.
**Changed:**
- `tests/vitestSetup.ts`: the `common` `useParams`, `next/router`,
`next/compat/router` and `next/navigation` mocks are route-aware.
- `tests/lib/route-render.tsx`: the root route provides a
`RenderedRouteContext` marker. The switch keys off this marker rather
than any TanStack router context, because some component tests mount
their own `RouterContextProvider` or mock `@tanstack/react-router`.
- Route tests that relied on the old behavior:
- The EdgeFunctionOverview self-hosted test, `new/$slug` and
`logs/index.platform` now assert on `router.state.location` instead of
`next-router-mock`.
- The `logs` test's `useSignOut` mock is now stable, like the real hook;
an unstable mock made the redirect effect push in a loop.
- The EdgeFunctionOverview periods test now seeds the function detail
under its real slug instead of `undefined`.
- Removed the hand-written `useParams` mocks from the `authorize`,
Stripe `login`, `sign-in-mfa`, Vercel `new-project` and storage
`vectors` route tests; their URLs carry the params now.
**Added:**
- `tests/lib/route-aware-hooks.ts`: `routeAwareHook` and
`mockNextRouter`.
- `tests/lib/route-render.test.tsx`: renders a route at
`/project/abc/probe?query-tab=logs&id=1&id=2`, asserts what
`useParams()`, `useRouter().query` and `usePathname()` return, then
navigates and asserts again.
Addresses
[FE-5150](https://linear.app/supabase/issue/FE-5150/useparams-in-routes-tests-doesnt-return-any-querystring-params)
## To test
- [ ] `pnpm --filter studio exec vitest --run
tests/lib/route-render.test.tsx` passes.
- [ ] With `tests/vitestSetup.ts`, `tests/lib/route-render.tsx` and
`tests/lib/route-aware-hooks.ts` reverted to `master`, the same test
fails with `expected { ref: 'default' } to deeply equal { ref: 'abc',
queryTab: 'logs', id: '1' }`.
- [ ] Regression checks: `pnpm --filter studio exec vitest --run
tests/routes components/interfaces/Functions
components/interfaces/Database/Replication
components/interfaces/Account/Preferences` passes. These include route
tests and the component tests that mount their own TanStack router or
mock `next/router`.
---------
Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
|
||
|
|
d2eb58a0e7 |
[FE-3106] (part 3) – refactor(studio): move account and top-level page bodies (#53212)
Moves the account and top-level app page bodies (`/account/*`, `/organizations`, `/new`, `/new/$slug`, `/join`, `/claim-project`, `/aws-marketplace-onboarding`, `/stripe-atlas-application`, `/support/new`, `/support/link`, `/integrations/github|vercel/*`) from `pages/**` into their TanStack route files and deletes the pages. Part of the final pass of the TanStack migration (FE-3106). Part 3 of the stack, and the first page-move PR. **Depends on:** #53202 **Changed:** - `routes/_app/account/**`, `routes/_app/{organizations,new/index,support/*}.tsx`, `routes/{new/$slug,join,claim-project,aws-marketplace-onboarding,stripe-atlas-application}.tsx`, `routes/integrations/**` – page bodies inlined. `next/router`/`next/link`/`next/head` → `useNavigate`, `Link`, `<Navigate>` and inline `<title>`. `getLayout` dropped; every old `getLayout` was checked against the route tree and matches - `routes/aws-marketplace-onboarding.tsx` – reads `buyer_id` through `validateSearch` + `Route.useSearch()` - `tests/lib/route-render.tsx` – new `renderRoute(Route, { routeId, url })` helper that mounts a file route in a memory router (with the app's search serializers) so route components can be tested; used by the moved tests - `tests/lib/route-mock.ts` – the `next/router` mock now derives its dynamic-route patterns from `routes/**` instead of globbing `pages/**`, so tests keep parsing params as pages disappear - `tests/routes/**` – page tests moved from `tests/pages/**` and rendered through the route - `.github/CODEOWNERS` – `pages/new/index.tsx` owner moved to `routes/_app/new/index.tsx` **Removed:** - 19 files under `pages/account/**`, `pages/new/**`, `pages/support/{new,link}.tsx`, `pages/integrations/**` and the top-level pages listed above Addresses [FE-3106](https://linear.app/supabase/issue/FE-3106/move-page-bodies-into-route-files-and-delete-pages). ## To test - Open `/account/me`, `/account/security`, `/account/tokens`, `/account/audit` – same Account layout, header title and sidebar as before - Open an old email-change link (`/account/me#message=...`) – lands on `/account/security` with the hash - `/account/tokens/scoped` – redirects to `/account/tokens` - `/organizations` and `/new/<org>` – render with the same layout; "New organization" links work - Vercel install/marketplace flows – navigation keeps `?…` params --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
1854331fb6 |
[FE-3106] (part 2) – refactor(studio): move api handlers into route files (#53202)
Moves every `pages/api/**` handler into its TanStack server route under `routes/api/**` and deletes `pages/api/**`, part of the final pass of the TanStack Start migration (FE-3106). Handlers move verbatim and still run through `toWebHandler`, so auth (`apiWrapper`), response shapes and headers are unchanged. Part 2 of the stack. **Depends on:** #53199 **Changed:** - `routes/api/**` – each route now holds its handler (formerly the `pages/api` default export) as a local `nextHandler`/named function. Next-only `config`/`maxDuration` exports are dropped: `vite.config.ts` already sets the function `maxDuration`, and `toWebHandler` parses bodies itself - `routes/api/ai/docs.ts` – Web-native handler inlined, `NextRequest` → `Request` - `lib/api/apiHelpers.ts` – `getPgMetaRedirectUrl` moved here from the old `tables` handler, which the other pg-meta routes imported it from - `eslint.config.cjs`, `.github/CODEOWNERS` – `pages/api` paths → `routes/api` - `tests/routes/api/**`, `lib/api/{generate-v4,rate}.test.ts`, `scripts/__tests__/server-source-maps.test.ts` – call the route's registered handler with a Web `Request` (`tests/lib/server-route.ts`); the MCP query-validation cases now run against the native route **Removed:** - `pages/api/**` (102 files), including the Next twins of the already-native `routes/api/mcp/index.ts` and `functions/$slug/body.ts` - unused `ProjectSettings` types and the `node-mocks-http` dev dependency Parity: every route registers the same methods its handler serves. The exceptions are `check-cname`, `get-ip-address`, `get-utc-time`, `get-s3-keys`, `get-deployment-commit`, `cli-release-version` and `connect`: in Next they answered any method, and their routes register `GET` only, as before this PR. Addresses [FE-3106](https://linear.app/supabase/issue/FE-3106/move-page-bodies-into-route-files-and-delete-pages). ## To test - Load the table editor, SQL editor and Auth users on a self-hosted build – `/api/platform/**` and `/api/v1/**` respond as before - Use the Assistant and the docs search – `/api/ai/**` streams as before - `GET /api/get-deployment-commit` – same JSON and `Cache-Control` Ran typecheck, ESLint, lint ratchet, knip, Prettier, the TanStack build and the full Studio vitest suite: all pass except `lib/server/configcat.test.ts`, which also fails on `master` in an environment with ConfigCat env vars set. Self-hosted E2E is CI-only. --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
de63769998 |
feat(studio): add ability to purge CDN cache to storage UI (#52777)
## Problem Users should be able to purge the CDN cache for an individual object or entire bucket via the UI. This feature is only available for Pro+ customers. Free tier customers should be encouraged to upgrade to get access. ## Solution - Add a _Purge CDN cache_ action to the bucket menu. Prompt users on Free plan to upgrade if needed. <img width="182" height="149" alt="image" src="https://github.com/user-attachments/assets/b665c8d0-b540-400e-a328-85c48ddafee0" /> <img width="534" height="242" alt="image" src="https://github.com/user-attachments/assets/15dfd3d3-c8a9-4ad7-9046-0929fd715511" /> <img width="538" height="211" alt="image" src="https://github.com/user-attachments/assets/3e29644e-9335-4b1d-b321-49303c2e8476" /> - Add a _Purge CDN cache_ action to the bucket item menu. Prompt users on Free plan to upgrade if needed. <img width="283" height="313" alt="image" src="https://github.com/user-attachments/assets/a801297e-04b5-46c7-aaf7-4569e66e4714" /> <img width="541" height="249" alt="image" src="https://github.com/user-attachments/assets/b58d264b-76ba-43d4-9579-6c07be9cb684" /> <img width="537" height="207" alt="image" src="https://github.com/user-attachments/assets/132b37bd-3a29-48b5-aa7e-7df29abcbfe6" /> ## Notes - Refactored the _Edit bucket_ menu so that only one modal is allowed - Fixed focus management related to the modals displayed by the _Edit bucket_ menu items - Introduced a way to mock the authenticated users in tests ## Review instructions - On an org on at least _Pro_ plan - Open a bucket _Edit bucket_ menu and click _Purge CDN cache_ - Confirming should call the `/platform/storage/{ref}/cdn/purge-bucket` API endpoint - Open a bucket item menu and click _Purge CDN cache_ - Confirming should call the `/platform/storage/{ref}/cdn/purge-object` API endpoint - On an org on _Free_ plan - Open a bucket _Edit bucket_ menu and click _Purge CDN cache_ - You should be prompted to upgrade - Open a bucket item menu and click _Purge CDN cache_ - You should be prompted to upgrade --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
7bc32a82fd |
feat(studio): gate api keys settings UI on api-keys grants (#52724)
Part 2 of 4 in a stack for [FE-4694](https://linear.app/supabase/issue/FE-4694/pilot-split-api-keys-queries-and-add-first-refinement-reveal-variant). Based on #52723. ## Stack 1. #52723 Reveal refinement and split api-keys queries 2. 👉 #52724 API keys settings UI and command menu 3. #52727 Database and edge functions consumers that reveal secret keys 4. #52728 Storage, cron, and Realtime consumers; remove the transitional reveal path ## Changes Moves the API keys settings UI off the V2 permission checks and onto `useGrant('GET /v1/projects/{ref}/api-keys')` with the new query options: - `PublishableAPIKeys`, `SecretAPIKeys`, `Project/APIKeys`, and the api-keys settings page use a plain grant. They never requested revealed keys; individual secrets still come from the per-key endpoint. - The command menu's API keys commands use the `reveal` grant, since they copy secret key values. - Each consumer renders loading, denied (`NoPermission`), permission-check error (`AlertError`), and the existing data states. `Project/APIKeys` now shows `NoPermission` when denied instead of a skeleton that never resolved. ## Testing - Migrates `PublishableAPIKeys.test.tsx`, `CommandMenu/ApiKeys.test.tsx`, and the api-keys settings page test to MSW and `customRender`, without mocking the data module or the V2 permissions hook. - Adds `PublishableAPIKeys.platform.test.tsx` and `CommandMenu/ApiKeys.platform.test.tsx` for granted, denied, and error states. The denied test waits for the denied grant before asserting that no api-keys request was made. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
d727bb0081 |
feat(studio): add reveal refinement for api-keys and split queries (#52723)
Part 1 of 4 in a stack for [FE-4694](https://linear.app/supabase/issue/FE-4694/pilot-split-api-keys-queries-and-add-first-refinement-reveal-variant). Later PRs migrate the api-keys consumers onto grants. ## Stack 1. 👉 Reveal refinement and split api-keys queries 2. #52724 API keys settings UI and command menu 3. #52727 Database and edge functions consumers that reveal secret keys 4. #52728 Storage, cron, and Realtime consumers; remove the transitional reveal path ## Changes - Adds a `reveal` variant for `GET /v1/projects/{ref}/api-keys` in `lib/fga-refinements.ts`. It requires `api_gateway_keys_secret_read` on top of the base annotation, and owns the `reveal` query param: the fetch wrapper sets it to `'true'` for a reveal grant and `'false'` otherwise (including `unguarded`), so passing `reveal` by hand is a type error. - Splits the query into `apiKeysQueryOptions` (plain grant) and `revealedApiKeysQueryOptions` (reveal grant). Both use `skipToken` without a grant, and the grant stays out of the query key. - `useAPIKeysQuery` and `useAPIKeys` stay as deprecated transitional hooks that mint the matching grant with `useGrant`. They can't use `unguarded.migrating`: with `reveal` owned by the wrapper, that would silently return unrevealed keys to consumers that need secrets. - Marks the variant type parameter `const` in `getGrant`, `useGrant`, `ensureGrant`, and `testGrant`. Adding a second refinement with variants widened inference of the branch variants to a union. - Adds `tests/lib/project-grant-mocks.ts` for component tests that need `useGrant` to resolve, and updates tests that partially mocked the V2 permissions hook. ## Testing Adds the type and runtime tests deferred from FE-4689 to `data/guarded-fetch.test.ts`: type equality with the raw client for plain and reveal grants, `reveal` rejected as a caller-supplied param, a reveal grant rejected on an endpoint without that variant, brand invariance, `guardMethod` setting `reveal` from the grant, and `assertGrant` throwing on an unknown variant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
df742bdb3b |
refactor(studio): rename ResponseError to StudioError (#52707)
## What
Moves the `ResponseError` class (`types/base.ts`) and the classified
error classes (`types/api-errors.ts`) into
`lib/errors/studio-errors.ts`, and renames `ResponseError` to
`StudioError`.
## Why
Studio's error classification is being expanded to cover errors that
don't come from API responses (thrown network failures, aborted
requests, unexpected client errors). The API-specific name and location
no longer fit. Landing the rename on its own keeps the follow-up PR,
which introduces the classified error model, small and reviewable.
## Notes for reviewers
- Mechanical change, no behavior change. Most of the diff is a one-line
import change per file plus import re-sorting by Prettier.
- Files that only use the type now use `import type { StudioError }`.
- `ResponseError` is no longer re-exported from `@/types`; there are no
compatibility shims at the old paths.
- Unrelated identifiers like `QueryResponseError` and
`parseResponseErrors` are unchanged.
|
||
|
|
7ce15123ab |
feat(studio): grant infra for production and development branch variants (#52372)
Part 1 of 7 in a stack that splits #52331 into reviewable pieces. Resolves part of [FE-4693](https://linear.app/supabase/issue/FE-4693/pilot-migrate-branches-to-grants-8-endpoints-createbranchmodal). There are no functional changes beyond #52331, and the top of the stack is identical to it. See #52331 for the full rationale. ## Stack 1. 👉 #52372 Grant infra for branch variants 2. #52373 Branches list query 3. #52374 Page gates on the list grant 4. #52375 Branch creation 5. #52376 Branch read, delete, reset, and restore 6. #52377 Branch update and push 7. #52378 Branch diff and merge ## Changes Adds `lib/fga-refinements.ts` entries: `production`/`development` variants for the 8 single-branch endpoints, with a new `variantRequired` flag. The fetch wrapper and `assertGrant` reject a grant without a variant. Also adds the `production` variant for `POST /v1/projects/{ref}/branches` when the body sets `is_default` or `with_data`. Adds `GrantForVariants`, the `useBranchGrant` hook, and shared fixtures in `tests/lib/branch-test-utils.ts`. Behavior-neutral: existing branch calls still use `unguarded.migrating`, which skips these checks. ## Testing `guarded-fetch.test.ts` and `useBranchGrant.test.ts`. |
||
|
|
080b888e6b |
feat(studio): slim edge function detail layout and move header to Overview (#50955)
The edge function detail layout is now breadcrumbs plus tabs (`PageNav`), without the page header, so tabs like Logs and Code get the full height below the tabs. The function name, invoke URL and last deploy details move into a header on the Overview tab, which also holds the chart period selector. Both the new and legacy Overview render it, and both now default to a 1 hour period instead of 15 minutes. The Overview sections (invocations, errors, performance and usage) now sit in one default-width `PageContainer` instead of each nesting a full-width one, and the invocations chart moves into a chart card. Invocations has no section heading, since it's the headline metric right below the page header. Both overview versions use the same chart periods. Sparse chart data is filled only between returned API buckets, avoiding synthetic zeros outside the reported range. Chart navigation uses the full rolling period, including a full day for the 1 day option. The selector shows a checkmark for the selected period, and the header announces loaded details. Self-hosted Studio retains a Copy URL action in the detail toolbar because it has no Overview tab. This layer doesn't depend on the logs changes below it. **Heads-up:** the header now only appears on Overview. Code, Details, Invocations and Logs show breadcrumbs and tabs only. This change isn't behind a flag. ### How to test 1. Open an edge function's Overview. The header shows the name, URL (with copy) and last deploy hover card, and the period selector sits in the header with 1 hour selected. 2. Switch through the other tabs. Breadcrumbs and tabs stay sticky, and there's no header. 3. With the `edgeFunctionsOverview` flag off, the legacy Overview renders with the same header. ### Validation - 104 focused tests pass with retries disabled and shuffled order (seed 50968). New tests cover both overview versions, period changes, empty results, header loading and copying, and self-hosted URL copying. Test names describe observable behavior. - 12 targeted regression mutations were detected and restored; the selected-indicator mutation was repeated after the visual alignment fix. - Browser QA on the staging preview for `3d055c0dc4` covers the header and deploy details, copied URL, period changes, all detail tabs, sticky navigation, the legacy overview, and empty results. Temporary local flag overrides were removed. The final test-only commit `5af6a2896b` has identical production code; its matching preview also passed header, URL-copy, period-switching, and Settings smoke checks. - Independent code review and changed-file formatting checks pass. All 40 executed CI checks pass on `5af6a2896b`, including TypeScript/lint, unit tests, Next.js and TanStack E2E tests, and builds. All six review threads are resolved. ### Stack Merge in order: 1. #50953 — reusable logs table building blocks 2. #50954 — function-scoped unified logs queries 3. #50955 — slimmer function detail layout, header on Overview 4. #50957 — Invocations merged into a function-scoped Logs tab 5. #50958 — Overview errors in the shared logs table 6. #52281 — remove the legacy Overview --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Jordi Enric <jordi.err@gmail.com> |
||
|
|
9391f60ec9 |
test(studio): add shared permissions mocks and testGrant helper (#52312)
## Problem Components and fetchers are moving to endpoint-bound FGA grants, so more tests need to mock `/platform/profile/permissions/v2` and mint grants. Each test file currently defines its own permissions response type and mock, and `testGrant` lives inside `guarded-fetch.test.ts`. Resolves [FE-4692](https://linear.app/supabase/issue/FE-4692/test-infra-global-msw-handler-for-v2-permissions-and-testgrant). ## Solution * `tests/lib/permissions-fixtures.ts`: shared `PermissionsV2Response` type, `ALL_FGA_PERMISSIONS`, `allPermissionsFor(slugs)` (grants everything at the org level), and `NO_PERMISSIONS`. * `tests/lib/msw-permissions.ts`: `mockPermissions(response)` and `mockPermissionsError({ status, message })` on top of `addAPIMock`. * `tests/lib/test-grant.ts`: `testGrant(endpoint, { variant, organizationSlug, projectRef, permissionsProjectRef })` for unit tests of fetchers and query options, moved out of `guarded-fetch.test.ts`. * Existing tests that mocked the v2 endpoint now use the shared helpers. `IndirectTaxDeclarationModal.test.tsx` keeps its own `addAPIMock` because a test asserts the request was served. * Documented in `apps/studio/tests/README.md` and the `studio-mock-api-tests` skill. |
||
|
|
090e5bceff |
feat(studio): filter organization usage by branch FE-4153 (#49257)
## Summary Customers could see a branch-driven egress overage in their organization total but could not select the branch on the Usage page. This adds a branch filter next to the parent project selector and uses the selected branch's project ref for usage requests. - Validate bookmarked branch refs before displaying usage. Show loading and API errors explicitly, and disclose when an unavailable branch falls back to its parent. - Keep the filter, notice, and usage requests on the same project ref. Allow returning to the parent even when the branches response omits its main row. - Find the selected branch's disk usage beyond the first page of organization projects and explain that deleted branches still contribute to organization totals. - Correct the branching and egress documentation to explain separate branch usage. ## Scope This is the branch-selector improvement proposed in FE-4153's discussion. It does not provide the original ticket's reconciled per-project egress table or historical rows for deleted branches. The current daily-usage API contract supports a single project filter, but does not return project-grouped usage. Keep the full reconciliation work open. ## Validation All 47 focused Vitest tests pass across six files, including nine MSW page tests covering usage request refs, direct branch links, pending/failed lookups, deleted-branch fallback, invalid-project recovery, and denied subscription permissions. Disk tests cover selection beyond the first 96 projects and pagination failures. Deterministic shuffled runs with seeds `4153` and `49257` pass with retries disabled (`--retry=0`). Four focused production mutants were killed by behavioral assertions; original source bytes were restored and verified after every probe. Studio TypeScript, Prettier on all PR paths, and focused lint checks pass; inherited `any` warnings remain. Browser QA on the matching `be17d77` Vercel preview passed parent usage (0.213 GB), searching for `dev-test`, branch selection, return to main, invalid-project recovery, stale-branch fallback, and returning to organization totals. The selected branch showed 0 GB, so nonzero branch overage was not verified. Browser network traffic was not captured; request-ref coverage comes from MSW. Three existing auth/router/platform module-mock scaffolds remain as a test-harness limitation; strict no-module-mock compliance is not claimed. All Studio unit-test and E2E shards passed on be17d77801; CI report jobs are finishing. Related: FE-4153 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Filter organization usage by project branch with searchable branch selection. Usage details reflect the selected branch where available, including branches found on later project-list pages. * See whether usage is scoped to a branch, the main branch, or a project, and switch to organization-wide totals. Billing and quota totals include all branches, including deleted branches that are no longer selectable. * **Documentation** * Clarified how non-compute usage is recorded per branch, included in organization totals, and viewed; it isn’t itemized by branch on invoices. * Clarified that Preview branch Egress counts toward organization totals, not the parent project’s usage, and how to view it. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
944d7730cd |
chore: Disable the msw logs in Github actions (#50365)
<!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Tests** - Reduced diagnostic logging during automated CI test runs. - Request, mock, and request-handling details remain available in non-CI environments for troubleshooting. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
737b8595f2 |
Update API types (#50234)
## Problem platform, v1 and v2 have been already completely migrated and introduced some changes. Some types have been renamed, some outputs and inputs updated. ## Solution - Update the API types - Fix the TS errors ## Update Taking this over to unblock #50134, which needs the new scoped token permission ids from the regenerated types. - Merged `master`. - Regenerated `api-v2.d.ts` from the production spec. The previous files came from a local API that exposed a webhook events endpoint production doesn't have yet. Production has since added standardized 400 error responses on the v2 organization endpoints. `api-v1.d.ts` and `platform.d.ts` already matched production. - Fixed `verify-production-types`. It formatted the regenerated files in a temp directory outside the repository, so Prettier fell back to its defaults and the comparison could never match the committed files. It now passes the repository config explicitly. `pnpm api:verify-types` passes on this branch. - Verified locally: `pnpm typecheck`, `pnpm api:verify-types`, Studio unit tests. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Preserved descriptions when saving, sharing, moving, or unsharing notebooks, reports, SQL snippets, and saved queries. * Improved handling of empty or null values across notebook descriptions, billing usage, pooler settings, and infrastructure fields. * Improved read-replica connection handling, including read-only connection strings. * Updated storage configuration and capability handling to match current settings. * **API and Compatibility** * Updated organization, project, storage, OAuth, billing, and infrastructure data handling to match current API responses. * OAuth app creation and updates now require scopes. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
e57aae3c83 |
feat(design-system): document disabled controls and add focusableWhenDisabled (#50068)
## What kind of change does this PR introduce? Docs update, with supporting `ui` and Studio changes. ## What is the current behaviour? Disabled buttons with tooltips use native `disabled`, which removes them from the tab order. Keyboard users cannot focus the control or read the tooltip explaining why an action is blocked. The design system also lacked guidance on keeping disabled actions discoverable and explaining why they are unavailable. ## What is the new behaviour? - Adds a **Disabled controls** section to the accessibility docs, with live examples for a focusable disabled button and visible page-level context - Adds `focusableWhenDisabled` to `Button`, keeping `disabled` as the semantic state while using `aria-disabled`, retaining keyboard focus, and guarding click handlers - Updates Studio's `ButtonTooltip` to make disabled buttons with tooltip text focusable automatically Also includes earlier design-system fixes on this branch: - Centralises `BASE_PATH` with a `/design-system` fallback so asset URLs work without a local `.env` file - Fixes sidebar hover and active tokens in design-system and ui-library, aligned with Studio's `InnerSideMenuItem` ## To test **Design system** 1. Open the [accessibility preview](https://design-system-git-fix-design-system-docs-and-nav-fixes-supabase.vercel.app/design-system/docs/accessibility) 2. Scroll to **Disabled controls** 3. Tab to the **disabled-focusable** example. Confirm the button remains focusable, looks disabled, and shows its tooltip on focus 4. Confirm the **disabled-unavailable-with-notice** example shows the admonition and focusable disabled button pattern **Studio (optional, requires a High Availability project)** 5. Go to Settings → General → **Pause project**. Tab to the button and confirm it remains focusable, looks disabled, and shows the HA tooltip on focus 6. Go to Database → Backups and find **Restore** on a scheduled backup row. Confirm the same behaviour |
||
|
|
b917b0e1bf |
feat(billing): adds non-dismissable modal for indirect tax declaration (#49643)
### Summary This PR adds a blocking dashboard modal for affected Australian customers to confirm their GST registration and business use of Supabase. KPMG requires us to collect this declaration from certain existing Australian customers. The backend now identifies organizations that still need to respond using `requires_indirect_tax_declaration` and stores their `yes` or `no` response in Orb customer metadata. It also supports email links with `submit_indirect_tax_declaration=true` and shows a dismissible confirmation when the organization has already responded. ### Testing #### Manual testing - Confirmed the modal appears for an affected organization without an existing response and cannot be dismissed. - Submitted both `yes` and `no` and confirmed the modal remains closed after a refresh. - Confirmed the declaration is stored without changing the customer's Tax ID. - Confirmed the modal does not appear for non admins/owners or organizations that do not require a declaration. - Confirmed the email-link parameter shows the already-submitted confirmation only for organizations that have responded, and is removed when dismissed. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added an indirect tax declaration dialog for eligible Australian organizations. * Users with billing permissions can select “Yes” or “No” and submit their declaration. * Added a dismissible confirmation for declarations submitted through a linked prompt. * The dialog requires an explicit response and provides guidance when no option is selected. * **Bug Fixes** * Declaration prompts remain visible through submission confirmation and close when dismissed. * Users without billing permissions do not see the dialog. * Success notifications no longer overlap with the confirmation dialog. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Julian Domke <68325451+juleswritescode@users.noreply.github.com> |
||
|
|
26e89b36c3 |
chore: Regenerate API types and fix all issues (#49646)
A bunch of small issues have showed up where the API types are breaking the FE repo: - Regenerate the API types. - For the removed Response types, use the return types from the operations instead. - Fix some types which now have a suffix `_Output`. - Add `requires_indirect_tax_declaration` property to Organization instances in mocks. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Refactor** * Updated Studio and shared type references to use generated API definitions consistently. * Improved typing for SSO configuration creation and updates. * Aligned telemetry lint categories with API-provided values. * Marked the legacy API type re-export as deprecated. * **Tests** * Updated test fixtures and response types to reflect current API contracts. * Added indirect tax declaration data to organization test scenarios. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
dfb0603a36 |
Joshenlim/fe 4063 set up incremental default opt in for database connections (#49132)
## Context As per PR title - sets up incremental default opt in for the Database Connections feature preview Database Connections preview banner should still only show up if it's never been dismissed before, but the CTA's changed to "Explore" rather than "Enable" if the user's default opted in Related discussion here: https://github.com/orgs/supabase/discussions/48639 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Database Connections preview is now enabled by default. * Added clearer handling for preview state and initialization. * Banner actions open Database Connections when enabled, or the feature preview when disabled. * **Bug Fixes** * Improved banner and menu visibility while preview settings initialize. * Preserved banner dismissal behavior after a previous preference change. * Improved navigation consistency across Database Connections entry points. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
4c8ed105d2 |
feat(studio): logs SQL execution wiring + source-aware run gestures (#48414)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Feature (SQL editor: execution wiring for logs-source snippets). Part of the stacked SQL-editor "Database vs Logs" query-source series. ## What is the current behavior? The SQL editor only ever runs queries against the user's Postgres database. There is no execution path for a logs (`log_sql`) snippet, and the run-button telemetry event carries no backend discriminator. ## What is the new behavior? - `useRunSource(id)` derives the run backend from the snippet type; a `log_sql` snippet resolves to `{ type: 'logs', dateRange }`, pairing the run with its session time range (default: last hour). - `useLogsSqlExecution` runs a promoted `SafeLogSqlFragment` against the analytics OTEL (ClickHouse) endpoint with the resolved time range as `iso_timestamp_start`/`iso_timestamp_end` request params. The endpoint is **pinned to OTEL** — a snippet's dialect must not flip with org migration. - The run gestures (toolbar button and Cmd+Enter) branch on the source and promote with the matching `acceptUntrusted*` right at the user action, preserving the auditable promotion-at-gesture boundary. pg intellisense is gated off for logs snippets. - The `sql_editor_query_run_button_clicked` telemetry event gains a required `{ source: 'database' | 'logs' }` property, fired from both execution paths. - Capability guard: a `log_sql` snippet is reachable by direct URL regardless of the (later) entry-point flag gating, so `executeLogsQuery` short-circuits when `otelLegacyLogs` is off — recording a clear "not available yet" result message instead of firing a request that would only return an opaque backend error on a non-ClickHouse project. This is a guard on the gesture, not endpoint selection. - Tests: `useRunSource` routing, `useLogsSqlExecution` endpoint/range/structured-error/capability-guard, and a reusable `flags` option on `renderSqlEditorHook`. No UI entry points are added — the feature runs dark until the flag-gated creation/nav PRs later in the stack. ## Additional context Stacked on the query-source series; base branch is `master` now that PR 4 (log date range domain + session state, #48401) is merged. Follow-ups in the stack add the toolbar/creation UI (with a run-affordance gate on `otelLegacyLogs`), nav section, AI dialect support, and reports guard. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for running log queries directly from the SQL editor. * Log query results, errors, and time ranges are now handled within the editor session. * Added automatic selection between database and log query execution, including support for custom date ranges. * SQL assistance is disabled while editing log queries where database definitions do not apply. * **Tests** * Added coverage for log query execution, date ranges, feature availability, and execution source selection. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
fa5eb17277 |
feat(studio): discriminated snippet union + source-aware writes (#48313)
Stacked on #48305. ## What PR 3 of the stacked SQL-editor query-source series (Database vs Logs). Stacked on the PR 2 branch `charislam/log-sql-content-shape`. Turns `SnippetWithContent` into a discriminated union on `type` and makes all snippet writes source-aware: - `data/content/sql-folders-query.ts`: `SnippetWithContent` is now `{ type: 'sql'; content?: SqlSnippets.Content } | { type: 'log_sql'; content?: LogSqlSnippets.Content } | { type: 'report'; content?: never }`. `report` is kept (the content endpoints' wire type carries it) but has no SQL content — its body is `Dashboards.Content`, loaded through the separate `Content` union. - `setSql` brands per type (`untrustedLogSql` vs `untrustedSql`). - `buildUpsertPayload` persists `snippet.type` (no longer hardcoded `'sql'`). - `createSqlSnippetSkeletonV2({ source })` emits the matching type + content shape with the `as any` cast removed. - New `components/interfaces/SQLEditor/querySource.ts`: `SqlSnippetSource` + `getSnippetSource`. - `seedSnippet` test helper gains a `source` arg. - New `remapWireSnippet` boundary helper in `content-remap.ts` concentrates the single wire->domain assertion, so `content-id-query` / `content-upsert-mutation` call sites are cast-free (no `as unknown as`). - Collateral: query result types aligned to the union; `updateSnippet` no longer accepts `type` (source is immutable); db-only editor read paths narrow away `log_sql`. ## Why Impossible-states-impossible typing: a snippet's brand follows its content type, so logs SQL and database SQL can never cross execution paths. No behavior change for existing database snippets. ## Testing - \`pnpm typecheck\` — clean - \`pnpm --filter studio run lint:ratchet\` — no new warnings - \`pnpm test:studio\` (data/content, SQLEditor, state/sql-editor) — passing, including new tests for \`getSnippetSource\`, source-aware \`setSql\`, type-aware \`buildUpsertPayload\`, and both skeleton shapes. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added source-aware creation for SQL editor snippets, including log-based SQL snippets. * Introduced backend source mapping so log snippets are treated as log_sql. * **Bug Fixes** * Improved SQL retrieval/prettification so log snippets no longer use the wrong fallback content. * Ensured log snippets are sanitized and preserve correct type, content, identifiers, and statuses during save/upsert flows. * **Tests** * Expanded unit and integration coverage for log snippet creation, source mapping, editing, prettification, and upsert payloads. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
4d793a708e |
test(sql-editor): shared renderHook harness with in-memory editor port (#48209)
## Summary - Add `renderSqlEditorHook()` test harness that eliminates mocking Monaco by injecting a real, deterministic in-memory editor port (EditorController/DiffController backed by plain JS state) - Include `createInMemoryEditor()`, `resetSqlEditorStores()`, and `setupSqlEditorMocks()` utilities to provide isolation and mock-free network testing via MSW handlers - Export `CustomWrapper` from custom-render and add optional `editor`/`diff` injection points to SQLEditorProvider (production unaffected via null-coalesce fallback) This is **Step 3** of an in-progress SQL editor testability refactor (Step 2 finished EditorController/DiffController port; this harness has no consumers yet — hook tests land in a follow-up step). ## Test plan - [x] `pnpm --filter studio typecheck` passes (already verified) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Tests** * Added reusable SQL Editor test utilities for in-memory editing, selections, error highlighting, snippets, and diff content. * Added helpers for resetting editor state, configuring API mocks, and rendering SQL Editor hooks in a complete test environment. * Enabled SQL Editor providers to accept optional controller overrides for isolated testing. * Exported the shared test wrapper for reuse across test suites. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
6236ee9ef9 |
POC: bring back MSW to remove the pattern of vi.mock (#46439)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Right now our tests for API mocking is using vi.mock and mocking that query or fetch handler. This is not the right approach IMO, 2 years ago @jordienr added MSW with some very powerful helpers. The idea is to move component test that rely on API using MSW within ViteTest. Principles are simple: - Mock API responses - Mount your component that uses API responses - Tests and assert on UI - Added Skill for Clanker This pattern is 100 times better than what we have <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Tests** * Expanded and strengthened test suites for secrets, org lookup, support flows, OAuth auth, and onboarding; mocks now use contract-backed responses for more realistic coverage. * **Documentation** * Added a comprehensive guide describing a standardized pattern for component tests that mock network requests. * **Chores** * Improved test helpers, typing for API mocks, and test runner configuration for more reliable and maintainable tests. <!-- review_stack_entry_start --> [](https://app.coderabbit.ai/change-stack/supabase/supabase/pull/46439?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <alaister@users.noreply.github.com> Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
e8df67d5d5 |
chore: migrate shortcuts to new hooks API (#44955)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Cleanup shortcuts with new hooks <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Refactor** * Centralized keyboard shortcut system for consistent shortcut behavior across the app and moved preference toggles to a unified registry. * **New Features** * Added explicit shortcuts for Command Menu, AI Assistant, Inline Editor, and result copy/download actions. * Hotkey preferences UI now renders dynamically from the centralized shortcut list. * **Tests** * Test helpers updated to include the command menu provider for accurate shortcut behavior in tests. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
205cbe7d26 | chore(studio}: enforce import order, remove bare import specifiers (#44585) | ||
|
|
f5ff10e195 |
refactor,tests(support form) (#39410)
* refactor: refactor support form Refactor support form to make it easier to maintain: - Split up large components into smaller components and hooks - Lift state up so we don't have to do complex child/parent state-syncing via useEffect - Use nuqs parsing for consistent serialization/deserialization of support form prefilled fields * test: support form Add comprehensive tests for support form * fix(support form): project and org empty state * Nit clean up * More clean up * cleannnn * fix(support form): allow case-insensitive category in url * clean(support form tests): remove unused param * fix(support form): incorrect logic for sending affected services in payload * clean(support form): use NO_ORG_MARKER and NO_PROJECT_MARKER instead of strings * fix(support form): don't show upgrade cta if already on enterprise --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
d6fe8476f3 |
Refactor EditSecretModal to use shadcn components (#37258)
* chore: Refactor `NewAccessTokenButton` to use shadcn components This brings `NewAccessTokenButton` into conformance with the latest UI patterns of using shadcn based components, zod schemas, and react-hook-form for form submission. I based this refactor on the implementation of `CreateSecretAPIKeyDialog`, which already made use of the above. * add success and failure toasts * add smoke test for `NewAccessTokenButton`, fix vitest config This adds a minimal test for `NewAccessTokenButton` but more importantly fixes a critical bug in the vitest configuration for `studio`. Because `restoreMocks: true` was set in the config, this meant that the mock implementation for `window.matchMedia` defined in the `tests/vitestSetup.ts` file was being **reset** to an empty function before each test suite was run. While this didn't appear to be a problem before, that appears to be because none of the existing tests had `motion.div` in their component trees. Since `motion.div` calls `addListener` on a media query as part of it's lifecycle, that meant that any test which included it would fail as `addListener` would be undefined in this situation. Removing `restoreMocks: true` from the config results in the desired mocking behavior. This change is necessary in order to test any component that has the `FormItemLayout` component, as it uses `framer-motion` to animate in error messages for input elements. * add warning comment in case of future config regression * update test cases, reset form on dialog close, testing setup fixes This fixes an issue with the polyfills for the testing environment, where a call to `useMutation` would fail as a result of `TransformStream` being set to `null`. Basic tests for access token creation and form resetting added. Adds `@faker-js/faker` to the studio app devDependencies to generate mock data for `msw` endpoint response. Adds `shx` to the docs app devDependencies to ensure that the `codegen:examples` script runs cross-platform. * ensure mocked date is a string * update testing setup, pollyfills and add rich type support to addAPIMock * add missing changes * Move `EditSecretModal` to be child of `SecretRow` In the accompanying PR for `DeleteSecretModal`, that one will also be moved over to `SecretRow` * Update studio testing setup files Improves API mocking type safety and polyfills browser APIs necessary to run tests with framer-motion components * chore: Refactor `NewAccessTokenButton` to use shadcn components This brings `NewAccessTokenButton` into conformance with the latest UI patterns of using shadcn based components, zod schemas, and react-hook-form for form submission. I based this refactor on the implementation of `CreateSecretAPIKeyDialog`, which already made use of the above. * add success and failure toasts * add smoke test for `NewAccessTokenButton`, fix vitest config This adds a minimal test for `NewAccessTokenButton` but more importantly fixes a critical bug in the vitest configuration for `studio`. Because `restoreMocks: true` was set in the config, this meant that the mock implementation for `window.matchMedia` defined in the `tests/vitestSetup.ts` file was being **reset** to an empty function before each test suite was run. While this didn't appear to be a problem before, that appears to be because none of the existing tests had `motion.div` in their component trees. Since `motion.div` calls `addListener` on a media query as part of it's lifecycle, that meant that any test which included it would fail as `addListener` would be undefined in this situation. Removing `restoreMocks: true` from the config results in the desired mocking behavior. This change is necessary in order to test any component that has the `FormItemLayout` component, as it uses `framer-motion` to animate in error messages for input elements. * update test cases, reset form on dialog close, testing setup fixes This fixes an issue with the polyfills for the testing environment, where a call to `useMutation` would fail as a result of `TransformStream` being set to `null`. Basic tests for access token creation and form resetting added. Adds `@faker-js/faker` to the studio app devDependencies to generate mock data for `msw` endpoint response. Adds `shx` to the docs app devDependencies to ensure that the `codegen:examples` script runs cross-platform. * ensure mocked date is a string * update testing setup, pollyfills and add rich type support to addAPIMock * add missing changes * Move `EditSecretModal` to be child of `SecretRow` In the accompanying PR for `DeleteSecretModal`, that one will also be moved over to `SecretRow` * fix imports * Update test, fix rebase errors * remove unnecessary code * resolve type errors * fix missing listen call for msw, resolve test type error * fix imports * Update studio testing setup files Improves API mocking type safety and polyfills browser APIs necessary to run tests with framer-motion components * fix missing listen call for msw, resolve test type error * fix imports * remove duplicate test * update testing setup * implement requested changes * cleanup unnecessary conditional logic for undefined `secret` prop * remove unused import * remove unnecessary code * cleanup, replace lodash import with JS * add required router mock * fix broken lockfile --------- Co-authored-by: Terry Sutton <saltcod@gmail.com> |
||
|
|
57cd26ac77 |
Move non-layout Storage components to components/interfaces (#37381)
* Update studio testing setup files Improves API mocking type safety and polyfills browser APIs necessary to run tests with framer-motion components * fix missing listen call for msw, resolve test type error * fix imports * Update studio testing setup files Improves API mocking type safety and polyfills browser APIs necessary to run tests with framer-motion components * fix missing listen call for msw, resolve test type error * fix imports * Move non-layout Storage related components to `components/interfaces` * Fix paths --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
3c588294a6 |
Improve Integration Test Setup and re-add LogPreviewer tests (#35358)
* fix logs previewer and msw * refactor api mocking for better dx * update readme * comment out error handler for vitest * rm unnecessary tests * fix custom render nuqs type * add logs search test * rm unnecessary import * update readme with customRender and customRednerHook * rm unnecessary api handler * Move the NODE_ENV to the studio build command in turbo.json. * Update apps/studio/tests/README.md Co-authored-by: Joshen Lim <joshenlimek@gmail.com> * add cursor rule --------- Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com> Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
f1394f7080 |
Update Nuqs to v2 (#34230)
* update pckgs * add adapter * update nuqs implementation for v2, add some helpers for testing * rm render with nuqs, not needed * fix type |