1 import type { OpenAPI } from "types"
2 import { resolveApiRefDocUrl } from "@/utils/resolve-doc-url"
3 import generateSchemaExamples from "@/utils/generate-schema-examples"
4 import schemaToMarkdown from "./schema-to-markdown"
5 import { MarkdownContext, absolutizeLink, oneLine } from "./shared"
6
7 export type OperationToMarkdownOptions = MarkdownContext & {
8 endpointPath: string
9 method: string
10 baseSpecs?: OpenAPI.ExpandedDocument
11 }
12
13 const firstContentSchema = (
14 content?: Record<string, { schema?: OpenAPI.SchemaObject }>
15 ): { media: string; schema?: OpenAPI.SchemaObject } | undefined => {
16 if (!content) {
17 return undefined
18 }
19 const media = Object.keys(content)[0]
20 if (!media) {
21 return undefined
22 }
23 return { media, schema: content[media]?.schema }
24 }
25
26 const renderParameters = (
27 parameters: OpenAPI.Parameter[],
28 ctx: MarkdownContext
29 ): string => {
30 const groups: { in: string; title: string }[] = [
31 { in: "path", title: "Path Parameters" },
32 { in: "query", title: "Query Parameters" },
33 { in: "header", title: "Header Parameters" },
34 ]
35
36 return groups
37 .map(({ in: location, title }) => {
38 const groupParams = parameters.filter((param) => param.in === location)
39 if (!groupParams.length) {
40 return ""
41 }
42
43 const syntheticSchema: OpenAPI.SchemaObject = {
44 type: "object",
45 properties: groupParams.reduce(
46 (acc, param) => {
47 acc[param.name] = {
48 ...(param.schema || {}),
49 description: param.description || param.schema?.description,
50 example: param.example ?? param.schema?.example,
51 examples: param.examples ?? param.schema?.examples,
52 } as OpenAPI.SchemaObject
53 return acc
54 },
55 {} as Record<string, OpenAPI.SchemaObject>
56 ),
57 required: groupParams
58 .filter((param) => param.required)
59 .map((param) => param.name),
60 }
61
62 return `### ${title}\n\n${schemaToMarkdown(syntheticSchema, ctx)}`
63 })
64 .filter(Boolean)
65 .join("\n\n")
66 }
67
68 const renderResponses = (
69 responses: OpenAPI.ResponsesObject,
70 ctx: MarkdownContext
71 ): string => {
72 const parts: string[] = ["### Responses"]
73
74 Object.entries(responses).forEach(([code, response]) => {
75 const content = firstContentSchema(response.content)
76 const header = `#### ${code}${response.description ? ` ${response.description}` : ""}`
77 if (!content?.schema) {
78 parts.push(`${header}\n\nEmpty response`)
79 return
80 }
81 parts.push(
82 `${header}\n\nContent type: \`${content.media}\`\n\n${schemaToMarkdown(
83 content.schema,
84 ctx
85 )}`
86 )
87 })
88
89 return parts.join("\n\n")
90 }
91
92 // Normalize `x-codeSamples` language names to Markdown code-fence identifiers.
93 const FENCE_LANG: Record<string, string> = {
94 javascript: "js",
95 typescript: "ts",
96 shell: "bash",
97 bash: "bash",
98 }
99 const fenceLang = (lang?: string): string => {
100 const normalized = (lang || "").toLowerCase()
101 return FENCE_LANG[normalized] ?? normalized
102 }
103
104 // Render an event payload. The OAS payload is usually already a fenced code
105 // block (```ts ...```), so emit it as-is rather than double-wrapping it.
106 const renderEventPayload = (payload?: string): string => {
107 const trimmed = payload?.trim()
108 if (!trimmed) {
109 return ""
110 }
111 return trimmed.startsWith("```")
112 ? `\n\n${trimmed}`
113 : `\n\n\`\`\`ts\n${trimmed}\n\`\`\``
114 }
115
116 const renderEvents = (events: OpenAPI.OasEvents[]): string => {
117 const parts: string[] = ["### Emitted Events"]
118 events.forEach((event) => {
119 const flags = [
120 event.deprecated ? "deprecated" : "",
121 event.since ? `since v${event.since}` : "",
122 ]
123 .filter(Boolean)
124 .join(", ")
125 parts.push(
126 `#### \`${event.name}\`${flags ? ` (${flags})` : ""}${
127 event.description ? `\n\n${oneLine(event.description)}` : ""
128 }${renderEventPayload(event.payload)}`
129 )
130 })
131 return parts.join("\n\n")
132 }
133
134 const renderCodeSamples = (samples: OpenAPI.Code[]): string => {
135 const parts: string[] = ["### Code Samples"]
136 samples.forEach((sample) => {
137 parts.push(
138 `**${sample.label || sample.lang}**\n\n\`\`\`${fenceLang(sample.lang)}\n${
139 sample.source
140 }\n\`\`\``
141 )
142 })
143 return parts.join("\n\n")
144 }
145
146 /**
147 * Converts a single OpenAPI operation to full-fidelity Markdown, mirroring the
148 * rendered `Tags/Operation` page (heading, method+path, description, workflow,
149 * related guide, security, parameters, request body, all responses, emitted
150 * events, code samples, and an example of the primary success response).
151 */
152 export default function operationToMarkdown(
153 operation: OpenAPI.Operation,
154 options: OperationToMarkdownOptions
155 ): string {
156 const { endpointPath, method, baseSpecs } = options
157 const ctx: MarkdownContext = {
158 area: options.area,
159 baseUrl: options.baseUrl,
160 basePath: options.basePath,
161 }
162 const parts: string[] = []
163
164 // Heading + inline metadata.
165 const headingFlags = [
166 operation.deprecated ? "deprecated" : "",
167 operation["x-since"] ? `since v${operation["x-since"]}` : "",
168 operation["x-featureFlag"]
169 ? `feature flag: ${operation["x-featureFlag"]}`
170 : "",
171 ...(operation["x-badges"]?.map((badge) => badge.text) || []),
172 ].filter(Boolean)
173 parts.push(
174 `## ${operation.summary || operation.operationId}${
175 headingFlags.length ? ` (${headingFlags.join(", ")})` : ""
176 }`
177 )
178
179 parts.push(`\`${method.toUpperCase()} ${endpointPath}\``)
180
181 // Custom badges carry an explanatory description (shown in a tooltip on the
182 // page); keep it — it often links to a plugin/guide.
183 operation["x-badges"]?.forEach((badge) => {
184 if (badge.description) {
185 parts.push(`> **${badge.text}:** ${oneLine(badge.description)}`)
186 }
187 })
188
189 if (operation["x-deprecated_message"]) {
190 parts.push(
191 `> **Deprecated:** ${oneLine(operation["x-deprecated_message"])}`
192 )
193 }
194
195 if (operation.description) {
196 parts.push(operation.description)
197 }
198
199 if (operation["x-workflow"]) {
200 parts.push(
201 `Workflow: [${operation["x-workflow"]}](${ctx.baseUrl}/resources/references/medusa-workflows/${operation["x-workflow"]})`
202 )
203 }
204
205 if (operation.externalDocs) {
206 const href = absolutizeLink(
207 resolveApiRefDocUrl(operation.externalDocs.url, ctx.area),
208 ctx
209 )
210 parts.push(
211 `Related guide: [${operation.externalDocs.description || "Read More"}](${href})`
212 )
213 }
214
215 // Security / authorization.
216 if (operation.security?.length) {
217 const displayNames = operation.security
218 .map((requirement) => {
219 const schemeName = Object.keys(requirement)[0]
220 const scheme = baseSpecs?.components?.securitySchemes?.[schemeName]
221 return scheme && !("$ref" in scheme)
222 ? (scheme as OpenAPI.SecuritySchemeObject)["x-displayName"]
223 : undefined
224 })
225 .filter(Boolean)
226 if (displayNames.length) {
227 parts.push(`**Authorization:** ${displayNames.join(" or ")}`)
228 }
229 }
230
231 if (operation.parameters?.length) {
232 const rendered = renderParameters(
233 operation.parameters as OpenAPI.Parameter[],
234 ctx
235 )
236 if (rendered) {
237 parts.push(rendered)
238 }
239 }
240
241 const requestContent = firstContentSchema(operation.requestBody?.content)
242 if (requestContent?.schema) {
243 parts.push(
244 `### Request Body\n\nContent type: \`${requestContent.media}\`\n\n${schemaToMarkdown(
245 requestContent.schema,
246 ctx
247 )}`
248 )
249 }
250
251 if (operation.responses) {
252 parts.push(renderResponses(operation.responses, ctx))
253 }
254
255 if (operation["x-events"]?.length) {
256 parts.push(renderEvents(operation["x-events"]))
257 }
258
259 if (operation["x-codeSamples"]?.length) {
260 parts.push(renderCodeSamples(operation["x-codeSamples"]))
261 }
262
263 // Example of the primary success response (200/201), matching the code column.
264 const successEntry = operation.responses
265 ? Object.entries(operation.responses).find(
266 ([code]) => code === "200" || code === "201"
267 )
268 : undefined
269 const successContent = successEntry
270 ? Object.values(successEntry[1].content || {})[0]
271 : undefined
272 if (successContent?.schema) {
273 const examples = generateSchemaExamples({
274 schema: successContent.schema,
275 schemaExample: successContent.example,
276 })
277 if (examples[0]?.content) {
278 parts.push(`### Example\n\n\`\`\`json\n${examples[0].content}\n\`\`\``)
279 }
280 }
281
282 return parts.join("\n\n")
283 }