"use client" import * as React from "react" import { ChevronDown, ChevronRight, FileText, Radio, Shield, Upload, X } from "lucide-react" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from "@/components/ui/drawer" import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible" import { ScrollArea } from "@/components/ui/scroll-area" import { DocCodeBlock, DocCollapsibleSection, DocEndpointHeader, DocErrorList, DocInfoBanner, DocSectionHeading, getMethodColor, } from "@/components/database/api-doc-shared" import type { TableMetadata } from "@/lib/api" import { getApiBaseUrl } from "@/lib/api" interface TableDocsDrawerProps { table: TableMetadata open: boolean onClose: () => void } export function TableRecordDocsDrawer({ table, open, onClose }: TableDocsDrawerProps) { const entityName = table.schema.name const isAuthEntity = table.schema.type === "auth" const hasFileFields = table.schema.fields?.some((f) => f.type === "file" || f.type === "files") ?? false return (
API Documentation — {entityName}
Entity record API, realtime subscriptions{isAuthEntity ? ", authentication, API keys, and OAuth" : ""}.

Credentials: send a JWT from login/refresh or an API key (mb_sk_...) as{" "} Authorization: Bearer <token>. Not every route requires auth — access depends on each entity's rules ( public,{" "} auth,{" "} custom, or admin-only empty mode). Response envelope: JSON endpoints return{" "} {`{ "status", "data", "error" }`}.

Records {table.schema.type !== "view" && ( <> )} {hasFileFields && } {isAuthEntity && } Realtime
) } function AuthDocsSection({ entityName }: { entityName: string }) { const baseUrl = getApiBaseUrl() const authPrefix = `/api/v1/auth/${entityName}` return ( <> Authentication API Keys OAuth } title="OAuth login & account linking" description="Only available when auth.oauth is true (see GET /methods). Browser redirect flow (PKCE) and account linking." >
GET {authPrefix}/oauth/authorize/{"{provider}"}

Start OAuth login — redirects the browser to the provider authorization URL. Optional{" "} redirect_uri query param; defaults to the server callback route.

GET {authPrefix}/oauth/callback/{"{provider}"}

OAuth callback — handles code,{" "} state, and provider error query params. Returns JWT and user record on success.

OAuth providers are registered by admins via{" "} /api/v1/sys/oauth/providers and enabled per entity via{" "} /api/v1/sys/oauth/entity-config.

) } function FilesDocCard({ entityName }: { entityName: string }) { const baseUrl = getApiBaseUrl() const exampleUrl = `${baseUrl}/api/v1/files/${entityName}/uploads/photo.jpg` return ( } title="File uploads" description="Serve uploaded files from file/files fields. Access follows the entity get access rule." >
GET /api/v1/files/{entityName}/{"{file}"}

Returns the stored file binary. The file path segment may include subdirectories (e.g. uploads/photo.jpg).

For create/update with file fields, send multipart/form-data{" "} instead of JSON. Non-file fields are sent as form fields alongside file parts.

) } function RealtimeDocCard({ entityName }: { entityName: string }) { const baseUrl = getApiBaseUrl() const wsBase = baseUrl.replace(/^http/, "ws") const sampleRowId = "019c1b81-364b-7000-8120-b5416b2c42c2" const sseConnectExample = `# SSE — subscribe to this entity and/or a specific row curl -N -H "Authorization: Bearer YOUR_TOKEN" \\ "${baseUrl}/api/v1/realtime?topics=${entityName},${entityName}:${sampleRowId}"` const sseUpdateExample = `# Update topics for an existing SSE session (client_id from the "connected" event) curl -X POST "${baseUrl}/api/v1/realtime" \\ -H "Authorization: Bearer YOUR_TOKEN" \\ -H "Content-Type: application/json" \\ -d '{ "client_id": "sse_1769987962000_0abc1", "topics": ["${entityName}", "${entityName}:${sampleRowId}"] }' # Clear topics to disconnect curl -X POST "${baseUrl}/api/v1/realtime" \\ -H "Authorization: Bearer YOUR_TOKEN" \\ -H "Content-Type: application/json" \\ -d '{"client_id": "sse_1769987962000_0abc1", "topics": []}'` const wsExample = `# WebSocket alternative (disabled when MB_REALTIME_WS=false) # Connect, then send JSON messages to subscribe/unsubscribe wscat -c "${wsBase}/api/v1/realtime/ws" \\ -H "Authorization: Bearer YOUR_TOKEN" # After connecting, send: {"topics": ["${entityName}", "${entityName}:${sampleRowId}"]} # Clear subscriptions: {"topics": []}` const changeEventExample = JSON.stringify( { action: "update", entity: entityName, row_id: sampleRowId, topic: `${entityName}:${sampleRowId}`, timestamp: 1737014400, data: { id: sampleRowId, title: "Updated value" }, }, null, 2, ) return ( <> } title="Server-Sent Events (SSE)" description="Long-lived HTTP stream. Disabled when MB_REALTIME_SSE=false. Topic = entity name (list access) or entity:row_id (get access)." >
Connect
Update topics
Event types
connected Sent once when the stream opens; includes client_id and topics.
ping Keep-alive sent periodically.
change Database change with action, entity, row_id, and data payload.
change event payload

In browsers, EventSource cannot send Authorization headers — use fetch() with the same URL and read the body as a stream, or use the WebSocket endpoint below.

} title="WebSocket" description="Alternative to SSE at WS /api/v1/realtime/ws. Disabled when MB_REALTIME_WS=false. Same change payload shape as SSE." >

After the WebSocket upgrade, send JSON messages with a topics array. Change events arrive as JSON messages using the same RealtimeChangeEvent shape as SSE change events.

) } function SimpleEndpointDoc({ method, endpoint, description, requestExample, responseExample, errors, nested = false, }: { method: string endpoint: string description: string requestExample: string responseExample: string errors?: Array<{ code: string; message: string }> nested?: boolean }) { const [isOpen, setIsOpen] = React.useState(false) const content = ( <>
{!nested && } {nested && (
{method} {endpoint} {isOpen ? : }
)} {nested &&

{description}

}
Request Example
Response Example
{errors && errors.length > 0 && }
) if (nested) { return ( {content} ) } return ( {content} ) } function ApiEndpointCard({ method, endpoint, description, table, operation, hasFileFields = false, }: { method: string endpoint: string description: string table: TableMetadata operation: string hasFileFields?: boolean }) { const [isOpen, setIsOpen] = React.useState(false) const baseUrl = getApiBaseUrl() const generateRequestExample = () => { let url = `${baseUrl}${endpoint}` if (operation === "list") { const filter = encodeURIComponent(JSON.stringify({ status: "active" })) url += `?limit=50&after=last_record_id&filter=${filter}` } let example = `curl -X ${method} "${url}"` if (method !== "GET") { example += ` \\\n -H "Content-Type: application/json"` } example += ` \\\n -H "Authorization: Bearer YOUR_TOKEN"` if (operation === "create" || operation === "update") { const sampleData: Record = {} table.schema.fields?.forEach((field) => { if (field.name === "id" || field.name === "created" || field.name === "updated") return if (field.type === "file" || field.type === "files") return if (field.name === "email") { sampleData[field.name] = "user@example.com" } else if (field.name === "password") { sampleData[field.name] = "securepassword" } else { sampleData[field.name] = `sample_${field.name}` } }) example += ` \\\n -d '${JSON.stringify(sampleData, null, 2)}'` if (hasFileFields) { example += `\n\n# Or use multipart/form-data for file fields:\n# curl -X ${method} "${baseUrl}${endpoint}" \\\n# -H "Authorization: Bearer YOUR_TOKEN" \\\n# -F "title=My post" \\\n# -F "avatar=@/path/to/photo.jpg"` } } return example } const generateResponseExample = () => { const sampleRecord: Record = {} table.schema.fields?.forEach((field) => { if (field.name === "id") { sampleRecord[field.name] = "019c1b81-364b-7000-8120-b5416b2c42c2" } else if (field.name === "created" || field.name === "updated") { sampleRecord[field.name] = "2026-01-15T10:00:00Z" } else if (field.name === "email") { sampleRecord[field.name] = "user@example.com" } else if (field.name === "password") { return } else if (field.type === "file") { sampleRecord[field.name] = "uploads/photo.jpg" } else if (field.type === "files") { sampleRecord[field.name] = "uploads/photo.jpg,uploads/doc.pdf" } else { sampleRecord[field.name] = `sample_${field.name}` } }) if (operation === "list") { return JSON.stringify( { status: 200, data: { items: [sampleRecord], items_count: 1, limit: 50, has_more: false, cursor: null, }, error: "", }, null, 2, ) } if (operation === "delete") { return JSON.stringify({ status: 200, data: null, error: "" }, null, 2) } const status = operation === "create" ? 201 : 200 return JSON.stringify({ status, data: sampleRecord, error: "" }, null, 2) } const requestExample = generateRequestExample() const responseExample = generateResponseExample() const errors: Array<{ code: string; message: string }> = [ { code: "400", message: "Bad Request — invalid input data" }, { code: "401", message: "Unauthorized — invalid or missing token" }, { code: "403", message: "Forbidden — access denied by entity rules" }, { code: "500", message: "Internal Server Error" }, ] if (operation === "get" || operation === "update" || operation === "delete") { errors.splice(3, 0, { code: "404", message: "Not Found — record does not exist" }) } return (
{operation === "list" && (

Query params: limit (1–500, default 50),{" "} after (cursor — id of last item from previous page),{" "} filter (URL-encoded JSON object of field equality filters). Results ordered by id ascending.

)}
Request Example
Response Example
) }