|
| 1 | +import { join } from "@std/path"; |
| 2 | +import { log } from "lume/core/utils/log.ts"; |
| 3 | +import type { RequestHandler } from "lume/core/server.ts"; |
| 4 | + |
| 5 | +interface MarkdownSourceMiddlewareOptions { |
| 6 | + /** Directory where the built static assets live. */ |
| 7 | + root?: string; |
| 8 | +} |
| 9 | + |
| 10 | +/** Reads a markdown file and returns a Response, or null if not found. Throws on other errors. */ |
| 11 | +async function serveMarkdownFile( |
| 12 | + filePath: string, |
| 13 | + absoluteRoot: string, |
| 14 | +): Promise<Response | null> { |
| 15 | + if (!filePath.startsWith(absoluteRoot + "/")) { |
| 16 | + return new Response("Forbidden", { status: 403 }); |
| 17 | + } |
| 18 | + try { |
| 19 | + const file = await Deno.readFile(filePath); |
| 20 | + return new Response(file, { |
| 21 | + headers: new Headers({ |
| 22 | + "content-type": "text/markdown; charset=utf-8", |
| 23 | + "cache-control": "public, max-age=300", |
| 24 | + }), |
| 25 | + }); |
| 26 | + } catch (error) { |
| 27 | + if (error instanceof Deno.errors.NotFound) { |
| 28 | + return null; |
| 29 | + } |
| 30 | + throw error; |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +export default function createMarkdownSourceMiddleware( |
| 35 | + { root = "_site" }: MarkdownSourceMiddlewareOptions = {}, |
| 36 | +): RequestHandler { |
| 37 | + const absoluteRoot = root.startsWith("/") ? root : join(Deno.cwd(), root); |
| 38 | + |
| 39 | + return async function markdownSourceMiddleware(req, next) { |
| 40 | + const pathname = new URL(req.url).pathname; |
| 41 | + |
| 42 | + // Case A: Direct .md URL request (e.g. /runtime/getting_started/installation.md) |
| 43 | + if (pathname.endsWith(".md")) { |
| 44 | + const filePath = join(absoluteRoot, pathname.slice(1)); |
| 45 | + try { |
| 46 | + const response = await serveMarkdownFile(filePath, absoluteRoot); |
| 47 | + if (response) return response; |
| 48 | + // Fallback: /foo/bar.md → /foo/bar/index.md (for index.md source files) |
| 49 | + const indexPath = filePath.replace(/\.md$/, "/index.md"); |
| 50 | + const indexResponse = await serveMarkdownFile(indexPath, absoluteRoot); |
| 51 | + return indexResponse ?? next(req); |
| 52 | + } catch (error) { |
| 53 | + log.error(`Failed serving ${pathname} from ${filePath}: ${error}`); |
| 54 | + return new Response("Internal Server Error", { status: 500 }); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + // Case B: Accept: text/markdown header — content negotiation |
| 59 | + // Tools like Claude Code send this header when they prefer markdown over HTML |
| 60 | + const acceptHeader = req.headers.get("accept") ?? ""; |
| 61 | + if ( |
| 62 | + acceptHeader.includes("text/markdown") && |
| 63 | + !acceptHeader.includes("text/html") |
| 64 | + ) { |
| 65 | + // Convert the HTML path to its .md equivalent |
| 66 | + // e.g. /runtime/getting_started/installation/ -> /runtime/getting_started/installation.md |
| 67 | + // Also try the index.md variant for directory-style URLs (e.g. /runtime/contributing/) |
| 68 | + const mdPath = pathname.replace(/\/$/, "") + ".md"; |
| 69 | + const mdIndexPath = pathname.replace(/\/$/, "") + "/index.md"; |
| 70 | + const filePath = join(absoluteRoot, mdPath.slice(1)); |
| 71 | + const indexFilePath = join(absoluteRoot, mdIndexPath.slice(1)); |
| 72 | + try { |
| 73 | + const response = (await serveMarkdownFile(filePath, absoluteRoot)) ?? |
| 74 | + (await serveMarkdownFile(indexFilePath, absoluteRoot)); |
| 75 | + if (response) { |
| 76 | + // Add Vary: Accept so caches don't serve this markdown to requests that want HTML |
| 77 | + response.headers.set("vary", "Accept"); |
| 78 | + return response; |
| 79 | + } |
| 80 | + // No .md source for this page (e.g. generated API reference) — serve HTML normally. |
| 81 | + // Add Vary: Accept so HTTP caches don't serve this HTML to markdown-only requests. |
| 82 | + const htmlResponse = await next(req); |
| 83 | + const headers = new Headers(htmlResponse.headers); |
| 84 | + headers.set("vary", "Accept"); |
| 85 | + return new Response(htmlResponse.body, { |
| 86 | + status: htmlResponse.status, |
| 87 | + statusText: htmlResponse.statusText, |
| 88 | + headers, |
| 89 | + }); |
| 90 | + } catch (error) { |
| 91 | + log.error(`Failed serving markdown for ${pathname}: ${error}`); |
| 92 | + return new Response("Internal Server Error", { status: 500 }); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + return next(req); |
| 97 | + }; |
| 98 | +} |
0 commit comments