|
| 1 | +import { getMimeType } from "./mime"; |
| 2 | +import type { ReadStream, Stats } from "node:fs"; |
| 3 | +import { createReadStream, lstatSync, existsSync } from "node:fs"; |
| 4 | +import { join } from "node:path"; |
| 5 | + |
| 6 | +export type ServeStaticOptions<E extends Env = Env> = { |
| 7 | + /** |
| 8 | + * Root path, relative to current working directory from which the app was started. Absolute paths are not supported. |
| 9 | + */ |
| 10 | + root?: string; |
| 11 | + path?: string; |
| 12 | + index?: string; // default is 'index.html' |
| 13 | + precompressed?: boolean; |
| 14 | + rewriteRequestPath?: (path: string, c: Context<E>) => string; |
| 15 | + onNotFound?: (req: Request, env: unknown) => Promise<Response> | Response; |
| 16 | +}; |
| 17 | + |
| 18 | +const COMPRESSIBLE_CONTENT_TYPE_REGEX = |
| 19 | + /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i; |
| 20 | +const ENCODINGS = { |
| 21 | + br: ".br", |
| 22 | + zstd: ".zst", |
| 23 | + gzip: ".gz", |
| 24 | +} as const; |
| 25 | +const ENCODINGS_ORDERED_KEYS = Object.keys( |
| 26 | + ENCODINGS, |
| 27 | +) as (keyof typeof ENCODINGS)[]; |
| 28 | + |
| 29 | +const createStreamBody = (stream: ReadStream) => { |
| 30 | + const body = new ReadableStream({ |
| 31 | + start(controller) { |
| 32 | + stream.on("data", (chunk) => { |
| 33 | + controller.enqueue(chunk); |
| 34 | + }); |
| 35 | + stream.on("error", (err) => { |
| 36 | + controller.error(err); |
| 37 | + }); |
| 38 | + stream.on("end", () => { |
| 39 | + controller.close(); |
| 40 | + }); |
| 41 | + }, |
| 42 | + |
| 43 | + cancel() { |
| 44 | + stream.destroy(); |
| 45 | + }, |
| 46 | + }); |
| 47 | + return body; |
| 48 | +}; |
| 49 | + |
| 50 | +const getStats = (path: string) => { |
| 51 | + let stats: Stats | undefined; |
| 52 | + try { |
| 53 | + stats = lstatSync(path); |
| 54 | + } catch {} |
| 55 | + return stats; |
| 56 | +}; |
| 57 | + |
| 58 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 59 | +export const serveStatic = <E extends Env = any>( |
| 60 | + options: ServeStaticOptions<E> = { root: "" }, |
| 61 | +): MiddlewareHandler<E> => { |
| 62 | + const root = options.root || ""; |
| 63 | + const optionPath = options.path; |
| 64 | + |
| 65 | + const onNotFound = |
| 66 | + options.onNotFound || |
| 67 | + (() => { |
| 68 | + return new Response("Not Found", { status: 404 }); |
| 69 | + }); |
| 70 | + |
| 71 | + if (root !== "" && !existsSync(root)) { |
| 72 | + console.error( |
| 73 | + `serveStatic: root path '${root}' is not found, are you sure it's correct?`, |
| 74 | + ); |
| 75 | + } |
| 76 | + |
| 77 | + return async (req: Request, env: unknown): Promise<Response> => { |
| 78 | + console.log(env); |
| 79 | + const url = new URL(req.url); |
| 80 | + let filename: string; |
| 81 | + |
| 82 | + if (optionPath) { |
| 83 | + filename = optionPath; |
| 84 | + } else { |
| 85 | + try { |
| 86 | + filename = decodeURIComponent(url.pathname); |
| 87 | + if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) { |
| 88 | + throw new Error(); |
| 89 | + } |
| 90 | + } catch { |
| 91 | + return await onNotFound(req, env); |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + let path = join( |
| 96 | + root, |
| 97 | + !optionPath && options.rewriteRequestPath |
| 98 | + ? options.rewriteRequestPath(filename, c) |
| 99 | + : filename, |
| 100 | + ); |
| 101 | + |
| 102 | + let stats = getStats(path); |
| 103 | + |
| 104 | + if (stats && stats.isDirectory()) { |
| 105 | + const indexFile = options.index ?? "index.html"; |
| 106 | + path = join(path, indexFile); |
| 107 | + stats = getStats(path); |
| 108 | + } |
| 109 | + |
| 110 | + if (!stats) { |
| 111 | + return await onNotFound(req, env); |
| 112 | + } |
| 113 | + |
| 114 | + const mimeType = getMimeType(path); |
| 115 | + const headers = new Headers(); |
| 116 | + |
| 117 | + headers.set("Content-Type", mimeType || "application/octet-stream"); |
| 118 | + |
| 119 | + if ( |
| 120 | + options.precompressed && |
| 121 | + (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType)) |
| 122 | + ) { |
| 123 | + const acceptEncodingSet = new Set( |
| 124 | + req.headers |
| 125 | + .get("Accept-Encoding") |
| 126 | + ?.split(",") |
| 127 | + .map((encoding) => encoding.trim()), |
| 128 | + ); |
| 129 | + |
| 130 | + for (const encoding of ENCODINGS_ORDERED_KEYS) { |
| 131 | + if (!acceptEncodingSet.has(encoding)) { |
| 132 | + continue; |
| 133 | + } |
| 134 | + const precompressedStats = getStats(path + ENCODINGS[encoding]); |
| 135 | + if (precompressedStats) { |
| 136 | + headers.set("Content-Encoding", encoding); |
| 137 | + headers.append("Vary", "Accept-Encoding"); |
| 138 | + stats = precompressedStats; |
| 139 | + path = path + ENCODINGS[encoding]; |
| 140 | + break; |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + const size = stats.size; |
| 146 | + |
| 147 | + if (req.method == "HEAD" || req.method == "OPTIONS") { |
| 148 | + headers.set("Content-Length", size.toString()); |
| 149 | + return new Response(null, { headers, status: 200 }); |
| 150 | + } |
| 151 | + |
| 152 | + const range = req.headers.get("range") || ""; |
| 153 | + |
| 154 | + if (!range) { |
| 155 | + headers.set("Content-Length", size.toString()); |
| 156 | + const stream = createReadStream(path); |
| 157 | + return new Response(createStreamBody(stream), { headers, status: 200 }); |
| 158 | + } |
| 159 | + |
| 160 | + headers.set("Accept-Ranges", "bytes"); |
| 161 | + headers.set("Date", stats.birthtime.toUTCString()); |
| 162 | + |
| 163 | + const parts = range.replace(/bytes=/, "").split("-", 2); |
| 164 | + const start = parseInt(parts[0], 10) || 0; |
| 165 | + let end = parseInt(parts[1], 10) || size - 1; |
| 166 | + if (size < end - start + 1) { |
| 167 | + end = size - 1; |
| 168 | + } |
| 169 | + |
| 170 | + const chunksize = end - start + 1; |
| 171 | + const stream = createReadStream(path, { start, end }); |
| 172 | + |
| 173 | + headers.set("Content-Length", chunksize.toString()); |
| 174 | + headers.set("Content-Range", `bytes ${start}-${end}/${stats.size}`); |
| 175 | + |
| 176 | + return new Response(createStreamBody(stream), { headers, status: 206 }); |
| 177 | + }; |
| 178 | +}; |
0 commit comments