1 import { addExtraToMd, getCleanMd, workerCompatibleFetch } 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 path from "path"
6 import { addUrlToRelativeLink } from "remark-rehype-plugins"
7 import type { Plugin } from "unified"
8 import * as Icons from "@medusajs/icons"
9 import * as HookValues from "@/specs/hook-values"
10 import { colors as allColors } from "@/config/colors"
11 import { PostHog } from "posthog-node"
12 import { fetchFromAssetsBinding } from "../../../utils/fetch-from-assets-binding"
13
14 type Params = {
15 params: Promise<{ slug?: string[] }>
16 }
17
18 export async function GET(req: NextRequest, { params }: Params) {
19 const { slug: rawSlug } = await params
20 const slug = rawSlug?.filter(Boolean) ?? []
21
22 const origin = process.env.NEXT_PUBLIC_BASE_URL || new URL(req.url).origin
23 const basePath = process.env.NEXT_PUBLIC_BASE_PATH || ""
24
25 const rawMdxUrl = `${origin}${basePath}/raw-mdx/${[...slug, "page.mdx"].join("/")}`
26 const fileContent =
27 (await fetchFromAssetsBinding(rawMdxUrl)) ??
28 (await workerCompatibleFetch<string | null>({
29 url: rawMdxUrl,
30 responseTransformer: async (res) => {
31 return res.ok ? res.text() : null
32 },
33 fallbackAction: async () => {
34 try {
35 const { promises: fs } = await import("fs")
36 return await fs.readFile(
37 path.join(process.cwd(), "app", ...slug, "page.mdx"),
38 "utf-8"
39 )
40 } catch {
41 return null
42 }
43 },
44 useRemote: !!process.env.CLOUDFLARE_ENV,
45 }))
46
47 if (!fileContent) {
48 return notFound()
49 }
50
51 const specsR2Base = process.env.UI_SPECS_R2_BASE_URL
52
53 const cleanMdContent = await getCleanMd_(
54 fileContent,
55 {
56 examplesPath: specsR2Base
57 ? `${specsR2Base}/specs/examples`
58 : path.join(process.cwd(), "specs", "examples"),
59 specsPath: specsR2Base
60 ? `${specsR2Base}/specs/components`
61 : path.join(process.cwd(), "specs", "components"),
62 },
63 {
64 after: [
65 [addUrlToRelativeLink, { url: process.env.NEXT_PUBLIC_BASE_URL }],
66 ] as unknown as Plugin[],
67 }
68 )
69
70 const acceptHeader = req.headers.get("accept") || ""
71 if (
72 acceptHeader.includes("text/plain") ||
73 acceptHeader.includes("text/markdown")
74 ) {
75 const client = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
76 host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
77 })
78
79 const urlObj = new URL(req.url)
80 const url = `${process.env.NEXT_PUBLIC_BASE_URL || ""}${process.env.NEXT_PUBLIC_BASE_PATH || ""}${urlObj.pathname}`
81
82 client.capture({
83 distinctId: "anonymous",
84 event: "md_content_requested_agents",
85 properties: {
86 $current_url: url,
87 $raw_user_agent: req.headers.get("user-agent") || undefined,
88 $ip:
89 req.headers.get("cf-connecting-ip") ||
90 req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
91 undefined,
92 },
93 })
94
95 await client.shutdown()
96 }
97
98 return new NextResponse(
99 addExtraToMd(cleanMdContent, {
100 baseUrl: process.env.NEXT_PUBLIC_BASE_URL || "",
101 basePath: process.env.NEXT_PUBLIC_BASE_PATH || "",
102 }),
103 {
104 headers: {
105 "Content-Type": "text/markdown",
106 "Cache-Control": "public, max-age=3600, must-revalidate",
107 },
108 status: 200,
109 }
110 )
111 }
112
113 const getCleanMd_ = unstable_cache(
114 async (
115 content: string,
116 parserOptions: {
117 examplesPath: string
118 specsPath: string
119 },
120 plugins?: { before?: Plugin[]; after?: Plugin[] }
121 ) => {
122 const iconNames = Object.keys(Icons).filter((name) => name !== "default")
123
124 return getCleanMd({
125 file: content,
126 type: "content",
127 plugins,
128 parserOptions: {
129 ComponentExample: {
130 examplesBasePath: parserOptions.examplesPath,
131 },
132 ComponentReference: {
133 specsPath: parserOptions.specsPath,
134 },
135 IconSearch: {
136 iconNames,
137 },
138 HookValues: {
139 hooksData: HookValues,
140 },
141 Colors: {
142 colors: allColors,
143 },
144 },
145 })
146 },
147 ["clean-md"],
148 {
149 revalidate: 3600,
150 }
151 )