Files
supabase/apps/studio/routes/api/ai/docs.ts
Alaister YoungandAlaister Young 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>
2026-11-11 22:24:43 +09:00

132 lines
3.4 KiB
TypeScript

import { SupabaseClient } from '@supabase/supabase-js'
import { createFileRoute } from '@tanstack/react-router'
import { ApplicationError, clippy, UserError } from 'ai-commands/edge'
import OpenAI from 'openai'
const openAiKey = process.env.OPENAI_API_KEY
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
async function handler(req: Request) {
if (!openAiKey) {
return new Response(
JSON.stringify({
error: 'No OPENAI_API_KEY set. Create this environment variable to use AI features.',
}),
{
status: 500,
headers: { 'Content-Type': 'application/json' },
}
)
}
if (!supabaseUrl) {
return new Response(
JSON.stringify({
error:
'No NEXT_PUBLIC_SUPABASE_URL set. Create this environment variable to use AI features.',
}),
{
status: 500,
headers: { 'Content-Type': 'application/json' },
}
)
}
if (!supabaseServiceKey) {
return new Response(
JSON.stringify({
error:
'No NEXT_PUBLIC_SUPABASE_ANON_KEY set. Create this environment variable to use AI features.',
}),
{
status: 500,
headers: { 'Content-Type': 'application/json' },
}
)
}
const { method } = req
switch (method) {
case 'POST':
return handlePost(req)
default:
return new Response(
JSON.stringify({ data: null, error: { message: `Method ${method} Not Allowed` } }),
{
status: 405,
headers: { 'Content-Type': 'application/json', Allow: 'POST' },
}
)
}
}
async function handlePost(request: Request) {
const openai = new OpenAI({ apiKey: openAiKey })
const body = await (request.json() as Promise<{
messages: { content: string; role: 'user' | 'assistant' }[]
}>)
const { messages } = body
if (!messages) {
throw new UserError('Missing messages in request data')
}
const supabaseClient = new SupabaseClient(supabaseUrl!, supabaseServiceKey!)
try {
const response = await clippy(openai, supabaseClient, messages)
// Proxy the streamed SSE response from OpenAI
return new Response(response.body, {
headers: {
'Content-Type': 'text/event-stream',
},
})
} catch (error: unknown) {
console.error(error)
if (error instanceof UserError) {
return new Response(
JSON.stringify({
error: error.message,
data: error.data,
}),
{
status: 400,
headers: { 'Content-Type': 'application/json' },
}
)
} else if (error instanceof ApplicationError) {
// Print out application errors with their additional data
console.error(`${error.message}: ${JSON.stringify(error.data)}`)
} else {
// Print out unexpected errors as is to help with debugging
console.error(error)
}
console.log('Returning generic 500 ApplicationError to client')
// TODO: include more response info in debug environments
return new Response(
JSON.stringify({
error: 'There was an error processing your request',
}),
{
status: 500,
headers: { 'Content-Type': 'application/json' },
}
)
}
}
export const Route = createFileRoute('/api/ai/docs')({
server: {
handlers: {
POST: ({ request }) => handler(request),
},
},
})