1 import { addExtraToMd } from "docs-utils"
2 import { unstable_cache } from "next/cache"
3 import { notFound } from "next/navigation"
4 import { NextRequest, NextResponse } from "next/server"
5 import { PostHog } from "posthog-node"
6 import type { OpenAPI } from "types"
7 import { getBaseSpecs } from "@/lib"
8 import getPathsOfTag from "@/utils/get-paths-of-tag"
9 import getSchemaContent from "@/utils/get-schema-content"
10 import { getPathForEnv } from "@/utils/get-path-for-env"
11 import { getIntroSection, getTagBySlug, isArea } from "@/utils/area"
12 import introToMarkdown from "@/utils/markdown/intro-to-markdown"
13 import tagToMarkdown from "@/utils/markdown/tag-to-markdown"
14 import operationToMarkdown from "@/utils/markdown/operation-to-markdown"
15 import schemaSectionToMarkdown from "@/utils/markdown/schema-section-to-markdown"
16 import { MarkdownContext } from "@/utils/markdown/shared"
17
18 export const dynamic = "force-dynamic"
19
20 type Params = {
21 params: Promise<{ slug?: string[] }>
22 }
23
24 const HTTP_METHODS: OpenAPI.OpenAPIV3.HttpMethods[] = [
25 "get",
26 "post",
27 "put",
28 "patch",
29 "delete",
30 "head",
31 "options",
32 ] as OpenAPI.OpenAPIV3.HttpMethods[]
33
34 const SCHEMA_SEGMENT = "schema"
35
36 /** Resolve a tag's associated schema (`$ref`) to a dereferenced schema object. */
37 async function fetchAssociatedSchema(
38 ref: string,
39 area: OpenAPI.Area
40 ): Promise<OpenAPI.SchemaObject | null> {
41 const name = ref
42 .replace("#/components/schemas/", "")
43 .replaceAll("./components/schemas/", "")
44
45 const r2Base = process.env.SPECS_R2_BASE_URL
46 const baseSchemasUrl = getPathForEnv(
47 r2Base || process.cwd(),
48 "specs",
49 area,
50 "components",
51 "schemas"
52 )
53 const schemaUrl = getPathForEnv(baseSchemasUrl, name)
54
55 try {
56 const { dereferencedDocument, originalSchema } = await getSchemaContent(
57 schemaUrl,
58 baseSchemasUrl
59 )
60 return (
61 (dereferencedDocument.components?.schemas
62 ? (Object.values(
63 dereferencedDocument.components.schemas
64 )[0] as OpenAPI.SchemaObject)
65 : originalSchema) || null
66 )
67 } catch {
68 return null
69 }
70 }
71
72 /** Build the Markdown for the requested path, or null when not found. */
73 async function resolveMarkdown_(
74 slug: string[],
75 ctx: MarkdownContext
76 ): Promise<string | null> {
77 const { area } = ctx
78
79 // /{area}
80 if (slug.length === 1) {
81 return introToMarkdown(area)
82 }
83
84 const [, section] = slug
85
86 // /{area}/{section-or-tag}
87 if (slug.length === 2) {
88 if (getIntroSection(area, section)) {
89 return introToMarkdown(area, section)
90 }
91
92 const baseSpecs = await getBaseSpecs(area)
93 const tag = getTagBySlug(baseSpecs, section)
94 if (!tag) {
95 return null
96 }
97 const doc = await getPathsOfTag(section, area)
98 return tagToMarkdown(tag, doc.paths, ctx)
99 }
100
101 // /{area}/{tag}/{operation-or-schema}
102 if (slug.length === 3) {
103 const [, tagSlug, last] = slug
104
105 if (last === SCHEMA_SEGMENT) {
106 const baseSpecs = await getBaseSpecs(area)
107 const tag = getTagBySlug(baseSpecs, tagSlug) as
108 | OpenAPI.TagObject
109 | undefined
110 const ref = tag?.["x-associatedSchema"]?.$ref
111 if (!tag || !ref) {
112 return null
113 }
114 const schema = await fetchAssociatedSchema(ref, area)
115 return schema ? schemaSectionToMarkdown(schema, tag.name, ctx) : null
116 }
117
118 const [baseSpecs, doc] = await Promise.all([
119 getBaseSpecs(area),
120 getPathsOfTag(tagSlug, area),
121 ])
122 for (const [endpointPath, pathItem] of Object.entries(doc.paths)) {
123 for (const method of HTTP_METHODS) {
124 const operation = pathItem?.[method]
125 if (operation && operation["x-slug"] === last) {
126 return operationToMarkdown(operation, {
127 ...ctx,
128 endpointPath,
129 method,
130 baseSpecs,
131 })
132 }
133 }
134 }
135 return null
136 }
137
138 return null
139 }
140
141 // The inner spec fetches are already individually cached; this
142 // additionally memoizes the conversion output (including the intro's `getCleanMd`
143 // pipeline) so repeat requests skip regeneration.
144 const resolveMarkdown = unstable_cache(
145 async (slug: string[], ctx: MarkdownContext) => resolveMarkdown_(slug, ctx),
146 ["api-ref-md-content"],
147 {
148 revalidate: 3600,
149 }
150 )
151
152 async function captureAgentRequest(req: NextRequest) {
153 const client = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
154 host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
155 })
156
157 const urlObj = new URL(req.url)
158 const url = `${process.env.NEXT_PUBLIC_BASE_URL || ""}${process.env.NEXT_PUBLIC_BASE_PATH || ""}${urlObj.pathname}`
159
160 client.capture({
161 distinctId: "anonymous",
162 event: "md_content_requested_agents",
163 properties: {
164 $current_url: url,
165 $raw_user_agent: req.headers.get("user-agent") || undefined,
166 $ip:
167 req.headers.get("cf-connecting-ip") ||
168 req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
169 undefined,
170 },
171 })
172
173 await client.shutdown()
174 }
175
176 export async function GET(req: NextRequest, { params }: Params) {
177 const { slug: rawSlug } = await params
178 const slug = rawSlug?.filter(Boolean) ?? []
179
180 if (slug.length === 0 || !isArea(slug[0])) {
181 return notFound()
182 }
183
184 const ctx: MarkdownContext = {
185 area: slug[0] as OpenAPI.Area,
186 baseUrl: process.env.NEXT_PUBLIC_BASE_URL || new URL(req.url).origin,
187 basePath: process.env.NEXT_PUBLIC_BASE_PATH || "/api",
188 }
189
190 const markdown = await resolveMarkdown(slug, ctx)
191 if (!markdown) {
192 return notFound()
193 }
194
195 const acceptHeader = req.headers.get("accept") || ""
196 if (
197 acceptHeader.includes("text/plain") ||
198 acceptHeader.includes("text/markdown")
199 ) {
200 await captureAgentRequest(req)
201 }
202
203 return new NextResponse(
204 addExtraToMd(markdown, {
205 baseUrl: process.env.NEXT_PUBLIC_BASE_URL || "",
206 basePath: process.env.NEXT_PUBLIC_BASE_PATH || "",
207 }),
208 {
209 headers: {
210 "Content-Type": "text/markdown",
211 "Cache-Control": "public, max-age=3600, must-revalidate",
212 },
213 status: 200,
214 }
215 )
216 }