Skip to content
Myr

fix(serve-static): support extensionless files and refactor (#2260)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Yusuke Wada · committed by GitHub · parent 5816cb2 · Browse files · 14 files+353 added−248 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

14 files+353 added−248 removed

  • tests:+65 added−25 removed
  • other:+288 added−223 removed

14 files+353 added−248 removed

modified:deno_dist/adapter/deno/serve-static.ts+20 added-53 removed
added:deno_dist/middleware/serve-static/index.ts+87 added
1import type { Context } from '../../context.ts'2import type { Env, MiddlewareHandler } from '../../types.ts'3import { getFilePath, getFilePathWithoutDefaultDocument } from '../../utils/filepath.ts'4import { getMimeType } from '../../utils/mime.ts'56export type ServeStaticOptions<E extends Env = Env> = {7 root?: string8 path?: string9 mimes?: Record<string, string>10 rewriteRequestPath?: (path: string) => string11 onNotFound?: (path: string, c: Context<E>) => void | Promise<void>12}1314const DEFAULT_DOCUMENT = 'index.html'15const defaultPathResolve = (path: string) => path1617/**18 * This middleware is not directly used by the user. Create a wrapper specifying `getContent()` by the environment such as Deno or Bun.19 */20export const serveStatic = <E extends Env = Env>(21 options: ServeStaticOptions<E> & {22 // eslint-disable-next-line @typescript-eslint/no-explicit-any23 getContent: (path: string) => any24 pathResolve?: (path: string) => string25 }26): MiddlewareHandler => {27 return async (c, next) => {28 // Do nothing if Response is already set29 if (c.finalized) {30 await next()31 return32 }33 const url = new URL(c.req.url)3435 let filename = options.path ?? decodeURI(url.pathname)36 filename = options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename37 const root = options.root3839 let path = getFilePath({40 filename,41 root,42 defaultDocument: DEFAULT_DOCUMENT,43 })4445 if (!path) {46 return await next()47 }4849 const getContent = options.getContent50 const pathResolve = options.pathResolve ?? defaultPathResolve5152 path = pathResolve(path)53 let content = await getContent(path)5455 if (!content) {56 let pathWithOutDefaultDocument = getFilePathWithoutDefaultDocument({57 filename,58 root,59 })60 if (!pathWithOutDefaultDocument) {61 return await next()62 }63 pathWithOutDefaultDocument = pathResolve(pathWithOutDefaultDocument)64 content = await getContent(pathWithOutDefaultDocument)65 if (content) {66 path = pathWithOutDefaultDocument67 }68 }6970 if (content) {71 let mimeType: string | undefined = undefined72 if (options.mimes) {73 mimeType = getMimeType(path, options.mimes) ?? getMimeType(path)74 } else {75 mimeType = getMimeType(path)76 }77 if (mimeType) {78 c.header('Content-Type', mimeType)79 }80 return c.body(content)81 }8283 await options.onNotFound?.(path, c)84 await next()85 return86 }87}
modified:deno_dist/utils/filepath.ts+18 added-5 removed
added:runtime_tests/bun/static/download+1 added
1download
modified:runtime_tests/bun/index.test.tsx+7 added
127 unmodified lines
128 expect(await res.text()).toBe('Bun!')129 expect(onNotFound).not.toHaveBeenCalled()130 })131132 it('Should return 200 response - /static/download', async () => {133 const res = await app.request(new Request('http://localhost/static/download'))134 expect(res.status).toBe(200)135 expect(await res.text()).toBe('download')136 expect(onNotFound).not.toHaveBeenCalled()137 })138139 it('Should return 200 response - /dot-static/plain.txt', async () => {140 const res = await app.request(new Request('http://localhost/dot-static/plain.txt'))141 expect(res.status).toBe(200)142 expect(await res.text()).toBe('Bun!!')
137 unmodified lines
added:runtime_tests/deno/static/download+1 added
1download
modified:runtime_tests/deno/middleware.test.tsx+4 added
107 unmodified lines
108 res = await app.request('http://localhost/static/plain.txt')109 assertEquals(res.status, 200)110 assertEquals(await res.text(), 'Deno!')111112 res = await app.request('http://localhost/static/download')113 assertEquals(res.status, 200)114 assertEquals(await res.text(), 'download')115116 res = await app.request('http://localhost/dot-static/plain.txt')117 assertEquals(res.status, 200)118 assertEquals(await res.text(), 'Deno!!')119 assertSpyCalls(onNotFound, 1)
29 unmodified lines
modified:src/adapter/bun/serve-static.ts+16 added-53 removed
modified:src/adapter/cloudflare-workers/serve-static.test.ts+7 added
12 unmodified lines
13 'assets/.static/plain.abcdef.txt': 'In the dot',14 'assets/static/video/morning-routine.abcdef.m3u8': 'Good morning',15 'assets/static/video/morning-routine1.abcdef.ts': 'Good',16 'assets/static/video/introduction.abcdef.mp4': 'Let me introduce myself',17 'assets/static/download': 'download',18}19const manifest = JSON.stringify({20 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',21 'assets/static/hono.html': 'assets/static/hono.abcdef.html',22 'assets/static/top/index.html': 'assets/static/top/index.abcdef.html',23 'static-no-root/plain.txt': 'static-no-root/plain.abcdef.txt',24 'assets/.static/plain.txt': 'assets/.static/plain.abcdef.txt',25 'assets/static/download': 'assets/static/download',26})2728Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })29Object.assign(global, {
160 unmodified lines
190 const res = await app.request('http://localhost/static/foo')191 expect(res.status).toBe(200)192 expect(await res.text()).toBe('bar')193 })194195 it('Should handle a file without an extension', async () => {196 const res = await app.request('http://localhost/static/download')197 expect(res.status).toBe(200)198 })199})200201describe('Types of middleware', () => {202 it('Should pass env type from generics of serveStatic', async () => {
18 unmodified lines
modified:src/adapter/cloudflare-workers/serve-static.ts+20 added-54 removed
1// @denoify-ignore2import type { KVNamespace } from '@cloudflare/workers-types'3import type { Context } from '../../context'3import { serveStatic as baseServeStatic } from '../../middleware/serve-static'4import type { ServeStaticOptions as BaseServeStaticOptions } from '../../middleware/serve-static'5import type { Env, MiddlewareHandler } from '../../types'5import { getFilePath } from '../../utils/filepath'6import { getMimeType } from '../../utils/mime'6import { getContentFromKVAsset } from './utils'79export type ServeStaticOptions<E extends Env = Env> = {10 root?: string11 path?: string12 mimes?: Record<string, string>13 manifest: object | string8export type ServeStaticOptions<E extends Env = Env> = BaseServeStaticOptions<E> & {9 namespace?: KVNamespace15 rewriteRequestPath?: (path: string) => string16 onNotFound?: (path: string, c: Context<E>) => void | Promise<void>10 manifest: object | string11}1219const DEFAULT_DOCUMENT = 'index.html'2013// This middleware is available only on Cloudflare Workers.14export const serveStatic = <E extends Env = Env>(15 options: ServeStaticOptions<E>16): MiddlewareHandler => {25 return async (c, next) => {26 // Do nothing if Response is already set27 if (c.finalized) {28 await next()29 return17 return async function serveStatic(c, next) {18 const getContent = async (path: string) => {19 return getContentFromKVAsset(path, {20 manifest: options.manifest,21 // eslint-disable-next-line @typescript-eslint/ban-ts-comment22 // @ts-ignore23 namespace: options.namespace24 ? options.namespace25 : c.env26 ? c.env.__STATIC_CONTENT27 : undefined,28 })29 }3132 const url = new URL(c.req.url)33 const filename = options.path ?? decodeURI(url.pathname)34 const path = getFilePath({35 filename: options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename,36 root: options.root,37 defaultDocument: DEFAULT_DOCUMENT,38 })3940 if (!path) {41 return await next()42 }4344 const content = await getContentFromKVAsset(path, {45 manifest: options.manifest,46 // eslint-disable-next-line @typescript-eslint/ban-ts-comment47 // @ts-ignore48 namespace: options.namespace ? options.namespace : c.env ? c.env.__STATIC_CONTENT : undefined,49 })5051 if (content) {52 let mimeType: string | undefined = undefined53 if (options.mimes) {54 mimeType = getMimeType(path, options.mimes) ?? getMimeType(path)55 } else {56 mimeType = getMimeType(path)57 }58 if (mimeType) {59 c.header('Content-Type', mimeType)60 }61 // Return Response object62 return c.body(content)63 }6465 await options.onNotFound?.(path, c)66 await next()67 return30 return baseServeStatic({31 ...options,32 getContent,33 })(c, next)34 }35}
modified:src/adapter/deno/serve-static.ts+20 added-53 removed
1import type { Context } from '../../context'1import type { ServeStaticOptions } from '../../middleware/serve-static'2import { serveStatic as baseServeStatic } from '../../middleware/serve-static'3import type { Env, MiddlewareHandler } from '../../types'3import { getFilePath } from '../../utils/filepath'4import { getMimeType } from '../../utils/mime'45// eslint-disable-next-line @typescript-eslint/ban-ts-comment6// @ts-ignore7const { open } = Deno810export type ServeStaticOptions<E extends Env = Env> = {11 root?: string12 path?: string13 mimes?: Record<string, string>14 rewriteRequestPath?: (path: string) => string15 onNotFound?: (path: string, c: Context<E>) => void | Promise<void>16}1718const DEFAULT_DOCUMENT = 'index.html'199export const serveStatic = <E extends Env = Env>(21 options: ServeStaticOptions<E> = { root: '' }10 options: ServeStaticOptions<E>11): MiddlewareHandler => {23 return async (c, next) => {24 // Do nothing if Response is already set25 if (c.finalized) {26 await next()27 return28 }2930 const url = new URL(c.req.url)31 const filename = options.path ?? decodeURI(url.pathname)32 let path = getFilePath({33 filename: options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename,34 root: options.root,35 defaultDocument: DEFAULT_DOCUMENT,36 })3738 if (!path) {39 return await next()40 }4142 path = `./${path}`4344 let file4546 try {47 file = await open(path)48 } catch (e) {49 console.warn(`${e}`)50 }5152 if (file) {53 const mimeType = getMimeType(path)54 if (mimeType) {55 c.header('Content-Type', mimeType)12 return async function serveStatic(c, next) {13 const getContent = async (path: string) => {14 // eslint-disable-next-line @typescript-eslint/no-explicit-any15 let file: any16 try {17 file = await open(path)18 } catch (e) {19 console.warn(`${e}`)20 }57 // Return Response object with stream58 return c.body(file.readable)21 return file ? file.readable : undefined22 }6061 await options.onNotFound?.(path, c)62 await next()63 return23 const pathResolve = (path: string) => {24 return `./${path}`25 }26 return baseServeStatic({27 ...options,28 getContent,29 pathResolve,30 })(c, next)31 }32}
added:src/middleware/serve-static/index.ts+87 added
1import type { Context } from '../../context'2import type { Env, MiddlewareHandler } from '../../types'3import { getFilePath, getFilePathWithoutDefaultDocument } from '../../utils/filepath'4import { getMimeType } from '../../utils/mime'56export type ServeStaticOptions<E extends Env = Env> = {7 root?: string8 path?: string9 mimes?: Record<string, string>10 rewriteRequestPath?: (path: string) => string11 onNotFound?: (path: string, c: Context<E>) => void | Promise<void>12}1314const DEFAULT_DOCUMENT = 'index.html'15const defaultPathResolve = (path: string) => path1617/**18 * This middleware is not directly used by the user. Create a wrapper specifying `getContent()` by the environment such as Deno or Bun.19 */20export const serveStatic = <E extends Env = Env>(21 options: ServeStaticOptions<E> & {22 // eslint-disable-next-line @typescript-eslint/no-explicit-any23 getContent: (path: string) => any24 pathResolve?: (path: string) => string25 }26): MiddlewareHandler => {27 return async (c, next) => {28 // Do nothing if Response is already set29 if (c.finalized) {30 await next()31 return32 }33 const url = new URL(c.req.url)3435 let filename = options.path ?? decodeURI(url.pathname)36 filename = options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename37 const root = options.root3839 let path = getFilePath({40 filename,41 root,42 defaultDocument: DEFAULT_DOCUMENT,43 })4445 if (!path) {46 return await next()47 }4849 const getContent = options.getContent50 const pathResolve = options.pathResolve ?? defaultPathResolve5152 path = pathResolve(path)53 let content = await getContent(path)5455 if (!content) {56 let pathWithOutDefaultDocument = getFilePathWithoutDefaultDocument({57 filename,58 root,59 })60 if (!pathWithOutDefaultDocument) {61 return await next()62 }63 pathWithOutDefaultDocument = pathResolve(pathWithOutDefaultDocument)64 content = await getContent(pathWithOutDefaultDocument)65 if (content) {66 path = pathWithOutDefaultDocument67 }68 }6970 if (content) {71 let mimeType: string | undefined = undefined72 if (options.mimes) {73 mimeType = getMimeType(path, options.mimes) ?? getMimeType(path)74 } else {75 mimeType = getMimeType(path)76 }77 if (mimeType) {78 c.header('Content-Type', mimeType)79 }80 return c.body(content)81 }8283 await options.onNotFound?.(path, c)84 await next()85 return86 }87}
modified:src/utils/filepath.test.ts+47 added-25 removed
1import { getFilePath } from './filepath'1import { getFilePath, getFilePathWithoutDefaultDocument } from './filepath'23describe('getFilePathWithoutDefaultDocument', () => {4 it('Should return file path correctly', async () => {5 expect(getFilePathWithoutDefaultDocument({ filename: 'foo.txt' })).toBe('foo.txt')6 expect(getFilePathWithoutDefaultDocument({ filename: 'foo.txt', root: 'bar' })).toBe(7 'bar/foo.txt'8 )910 expect(getFilePathWithoutDefaultDocument({ filename: '../foo' })).toBeUndefined()11 expect(getFilePathWithoutDefaultDocument({ filename: '/../foo' })).toBeUndefined()12 expect(getFilePathWithoutDefaultDocument({ filename: './../foo' })).toBeUndefined()13 expect(getFilePathWithoutDefaultDocument({ filename: 'foo..bar.txt' })).toBe('foo..bar.txt')14 expect(getFilePathWithoutDefaultDocument({ filename: '/foo..bar.txt' })).toBe('foo..bar.txt')15 expect(getFilePathWithoutDefaultDocument({ filename: './foo..bar.txt' })).toBe('foo..bar.txt')16 expect(getFilePathWithoutDefaultDocument({ filename: './..foo/bar.txt' })).toBe('..foo/bar.txt')17 expect(getFilePathWithoutDefaultDocument({ filename: './foo../bar.txt' })).toBe('foo../bar.txt')18 expect(getFilePathWithoutDefaultDocument({ filename: './..foo../bar.txt' })).toBe(19 '..foo../bar.txt'20 )2122 expect(23 getFilePathWithoutDefaultDocument({ filename: slashToBackslash('/../foo') })24 ).toBeUndefined()25 expect(26 getFilePathWithoutDefaultDocument({ filename: slashToBackslash('./../foo') })27 ).toBeUndefined()28 expect(getFilePathWithoutDefaultDocument({ filename: slashToBackslash('foo..bar.txt') })).toBe(29 'foo..bar.txt'30 )31 expect(getFilePathWithoutDefaultDocument({ filename: slashToBackslash('/foo..bar.txt') })).toBe(32 'foo..bar.txt'33 )34 expect(35 getFilePathWithoutDefaultDocument({ filename: slashToBackslash('./foo..bar.txt') })36 ).toBe('foo..bar.txt')37 expect(38 getFilePathWithoutDefaultDocument({ filename: slashToBackslash('./..foo/bar.txt') })39 ).toBe('..foo/bar.txt')40 expect(41 getFilePathWithoutDefaultDocument({ filename: slashToBackslash('./foo../bar.txt') })42 ).toBe('foo../bar.txt')43 expect(44 getFilePathWithoutDefaultDocument({ filename: slashToBackslash('./..foo../bar.txt') })45 ).toBe('..foo../bar.txt')46 })47})4849describe('getFilePath', () => {50 it('Should return file path correctly', async () => {51 expect(getFilePath({ filename: 'foo' })).toBe('foo/index.html')6 expect(getFilePath({ filename: 'foo.txt' })).toBe('foo.txt')5253 expect(getFilePath({ filename: 'foo', root: 'bar' })).toBe('bar/foo/index.html')9 expect(getFilePath({ filename: 'foo.txt', root: 'bar' })).toBe('bar/foo.txt')5455 expect(getFilePath({ filename: 'foo', defaultDocument: 'index.txt' })).toBe('foo/index.txt')56 expect(getFilePath({ filename: 'foo', root: 'bar', defaultDocument: 'index.txt' })).toBe(57 'bar/foo/index.txt'58 )1516 expect(getFilePath({ filename: './foo' })).toBe('foo/index.html')17 expect(getFilePath({ filename: 'foo', root: './bar' })).toBe('bar/foo/index.html')1819 expect(getFilePath({ filename: '../foo' })).toBeUndefined()20 expect(getFilePath({ filename: '/../foo' })).toBeUndefined()21 expect(getFilePath({ filename: './../foo' })).toBeUndefined()22 expect(getFilePath({ filename: 'foo..bar.txt' })).toBe('foo..bar.txt')23 expect(getFilePath({ filename: '/foo..bar.txt' })).toBe('foo..bar.txt')24 expect(getFilePath({ filename: './foo..bar.txt' })).toBe('foo..bar.txt')25 expect(getFilePath({ filename: './..foo/bar.txt' })).toBe('..foo/bar.txt')26 expect(getFilePath({ filename: './foo../bar.txt' })).toBe('foo../bar.txt')27 expect(getFilePath({ filename: './..foo../bar.txt' })).toBe('..foo../bar.txt')2829 expect(getFilePath({ filename: slashToBackslash('/../foo') })).toBeUndefined()30 expect(getFilePath({ filename: slashToBackslash('./../foo') })).toBeUndefined()31 expect(getFilePath({ filename: slashToBackslash('foo..bar.txt') })).toBe('foo..bar.txt')32 expect(getFilePath({ filename: slashToBackslash('/foo..bar.txt') })).toBe('foo..bar.txt')33 expect(getFilePath({ filename: slashToBackslash('./foo..bar.txt') })).toBe('foo..bar.txt')34 expect(getFilePath({ filename: slashToBackslash('./..foo/bar.txt') })).toBe('..foo/bar.txt')35 expect(getFilePath({ filename: slashToBackslash('./foo../bar.txt') })).toBe('foo../bar.txt')36 expect(getFilePath({ filename: slashToBackslash('./..foo../bar.txt') })).toBe('..foo../bar.txt')59 })60})6162function slashToBackslash(filename: string) {
2 unmodified lines
modified:src/utils/filepath.ts+18 added-5 removed
4 unmodified lines
5}67export const getFilePath = (options: FilePathOptions): string | undefined => {8 let filename = options.filename9 if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) {10 return11 }1213 let root = options.root || ''9 const defaultDocument = options.defaultDocument || 'index.html'1011 if (filename.endsWith('/')) {12 // /top/ => /top/index.html
2 unmodified lines
15 // /top => /top/index.html16 filename = filename.concat('/' + defaultDocument)17 }1819 const path = getFilePathWithoutDefaultDocument({20 root: options.root,21 filename,22 })2324 return path25}2627export const getFilePathWithoutDefaultDocument = (28 options: Omit<FilePathOptions, 'defaultDocument'>29) => {30 let root = options.root || ''31 let filename = options.filename3233 if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) {34 return35 }3637 // /foo.html => foo.html38 filename = filename.replace(/^\.?[\/\\]/, '')3940 // foo\bar.txt => foo/bar.txt
11 unmodified lines