"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" }`}.
)
}
function AuthDocsSection({ entityName }: { entityName: string }) {
const baseUrl = getApiBaseUrl()
const authPrefix = `/api/v1/auth/${entityName}`
return (
<>
AuthenticationAPI KeysOAuth}
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.
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.