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
Provenance
- Commit
f8371ab- Tree
0ca8f39- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
5816cb2
14 files changed+353 added−248 removed
modified:deno_dist/adapter/deno/serve-static.ts+20 added-53 removed
11233445678101112131415161718199211011232425262728293031323334353637383940414243444546474849505152535455121314151617181920575821226061626323242526272829303132import type { Context } from '../../context.ts'import type { ServeStaticOptions } from '../../middleware/serve-static/index.ts'import { serveStatic as baseServeStatic } from '../../middleware/serve-static/index.ts'import type { Env, MiddlewareHandler } from '../../types.ts'import { getFilePath } from '../../utils/filepath.ts'import { getMimeType } from '../../utils/mime.ts'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignoreconst { open } = Deno
export type ServeStaticOptions<E extends Env = Env> = { root?: string path?: string mimes?: Record<string, string> rewriteRequestPath?: (path: string) => string onNotFound?: (path: string, c: Context<E>) => void | Promise<void>}
const DEFAULT_DOCUMENT = 'index.html'
export const serveStatic = <E extends Env = Env>( options: ServeStaticOptions<E> = { root: '' } options: ServeStaticOptions<E>): MiddlewareHandler => { return async (c, next) => { // Do nothing if Response is already set if (c.finalized) { await next() return }
const url = new URL(c.req.url) const filename = options.path ?? decodeURI(url.pathname) let path = getFilePath({ filename: options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename, root: options.root, defaultDocument: DEFAULT_DOCUMENT, })
if (!path) { return await next() }
path = `./${path}`
let file
try { file = await open(path) } catch (e) { console.warn(`${e}`) }
if (file) { const mimeType = getMimeType(path) if (mimeType) { c.header('Content-Type', mimeType) return async function serveStatic(c, next) { const getContent = async (path: string) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any let file: any try { file = await open(path) } catch (e) { console.warn(`${e}`) } // Return Response object with stream return c.body(file.readable) return file ? file.readable : undefined }
await options.onNotFound?.(path, c) await next() return const pathResolve = (path: string) => { return `./${path}` } return baseServeStatic({ ...options, getContent, pathResolve, })(c, next) }}added:deno_dist/middleware/serve-static/index.ts+87 added
1+import type { Context } from '../../context.ts'2+import type { Env, MiddlewareHandler } from '../../types.ts'3+import { getFilePath, getFilePathWithoutDefaultDocument } from '../../utils/filepath.ts'4+import { getMimeType } from '../../utils/mime.ts'5+6+export 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+}13+14+const DEFAULT_DOCUMENT = 'index.html'15+const defaultPathResolve = (path: string) => path16+17+/**18+ * This middleware is not directly used by the user. Create a wrapper specifying `getContent()` by the environment such as Deno or Bun.19+ */20+export 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)34+35+ let filename = options.path ?? decodeURI(url.pathname)36+ filename = options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename37+ const root = options.root38+39+ let path = getFilePath({40+ filename,41+ root,42+ defaultDocument: DEFAULT_DOCUMENT,43+ })44+45+ if (!path) {46+ return await next()47+ }48+49+ const getContent = options.getContent50+ const pathResolve = options.pathResolve ?? defaultPathResolve51+52+ path = pathResolve(path)53+ let content = await getContent(path)54+55+ 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+ }69+70+ 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+ }82+83+ await options.onNotFound?.(path, c)84+ await next()85+ return86+ }87+}modified:deno_dist/utils/filepath.ts+18 added-5 removed
4 unmodified lines567891011121391011122 unmodified lines151617181920212223242526272829303132333435363738394011 unmodified lines4 unmodified lines}
export const getFilePath = (options: FilePathOptions): string | undefined => { let filename = options.filename if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) { return }
let root = options.root || '' const defaultDocument = options.defaultDocument || 'index.html'
if (filename.endsWith('/')) { // /top/ => /top/index.html2 unmodified lines // /top => /top/index.html filename = filename.concat('/' + defaultDocument) }
const path = getFilePathWithoutDefaultDocument({ root: options.root, filename, })
return path}
export const getFilePathWithoutDefaultDocument = ( options: Omit<FilePathOptions, 'defaultDocument'>) => { let root = options.root || '' let filename = options.filename
if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) { return }
// /foo.html => foo.html filename = filename.replace(/^\.?[\/\\]/, '')
// foo\bar.txt => foo/bar.txt11 unmodified linesadded:runtime_tests/bun/static/download+1 added
1+downloadmodified:runtime_tests/bun/index.test.tsx+7 added
127 unmodified lines128 expect(await res.text()).toBe('Bun!')129 expect(onNotFound).not.toHaveBeenCalled()130 })131 132+ 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+ })138+139 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 linesadded:runtime_tests/deno/static/download+1 added
1+downloadmodified:runtime_tests/deno/middleware.test.tsx+4 added
107 unmodified lines108 res = await app.request('http://localhost/static/plain.txt')109 assertEquals(res.status, 200)110 assertEquals(await res.text(), 'Deno!')111 112+ res = await app.request('http://localhost/static/download')113+ assertEquals(res.status, 200)114+ assertEquals(await res.text(), 'download')115+116 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 linesmodified:src/adapter/bun/serve-static.ts+16 added-53 removed
123345566891011121314151617719892122232425101112131415162728293031323334353637171819394041424344454647484950515253545556575859606120212223242526// @denoify-ignore/* eslint-disable @typescript-eslint/ban-ts-comment */import type { Context } from '../../context'import { serveStatic as baseServeStatic } from '../../middleware/serve-static'import type { ServeStaticOptions } from '../../middleware/serve-static'import type { Env, MiddlewareHandler } from '../../types'import { getFilePath } from '../../utils/filepath'import { getMimeType } from '../../utils/mime'
export type ServeStaticOptions<E extends Env = Env> = { root?: string path?: string mimes?: Record<string, string> rewriteRequestPath?: (path: string) => string onNotFound?: (path: string, c: Context<E>) => void | Promise<void>}
const DEFAULT_DOCUMENT = 'index.html'
export const serveStatic = <E extends Env = Env>( options: ServeStaticOptions<E> = { root: '' } options: ServeStaticOptions<E>): MiddlewareHandler => { return async (c, next) => { // Do nothing if Response is already set if (c.finalized) { await next() return return async function serveStatic(c, next) { const getContent = async (path: string) => { path = `./${path}` // @ts-ignore const file = Bun.file(path) return (await file.exists()) ? file : null } const url = new URL(c.req.url)
const filename = options.path ?? decodeURI(url.pathname) let path = getFilePath({ filename: options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename, root: options.root, defaultDocument: DEFAULT_DOCUMENT, })
if (!path) { return await next() const pathResolve = (path: string) => { return `./${path}` }
path = `./${path}`
// @ts-ignore const file = Bun.file(path) const isExists = await file.exists() if (isExists) { let mimeType: string | undefined = undefined if (options.mimes) { mimeType = getMimeType(path, options.mimes) ?? getMimeType(path) } else { mimeType = getMimeType(path) } if (mimeType) { c.header('Content-Type', mimeType) } // Return Response object return c.body(file) }
await options.onNotFound?.(path, c) await next() return return baseServeStatic({ ...options, getContent, pathResolve, })(c, next) }}modified:src/adapter/cloudflare-workers/serve-static.test.ts+7 added
12 unmodified lines13 '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 }19 const 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 })27 28 Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })29 Object.assign(global, {160 unmodified lines190 const res = await app.request('http://localhost/static/foo')191 expect(res.status).toBe(200)192 expect(await res.text()).toBe('bar')193 })194+195+ 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 })200 201 describe('Types of middleware', () => {202 it('Should pass env type from generics of serveStatic', async () => {18 unmodified linesmodified:src/adapter/cloudflare-workers/serve-static.ts+20 added-54 removed
1 // @denoify-ignore2 import type { KVNamespace } from '@cloudflare/workers-types'3-import type { Context } from '../../context'3+import { serveStatic as baseServeStatic } from '../../middleware/serve-static'4+import type { ServeStaticOptions as BaseServeStaticOptions } from '../../middleware/serve-static'5 import type { Env, MiddlewareHandler } from '../../types'5-import { getFilePath } from '../../utils/filepath'6-import { getMimeType } from '../../utils/mime'6 import { getContentFromKVAsset } from './utils'7 9-export type ServeStaticOptions<E extends Env = Env> = {10- root?: string11- path?: string12- mimes?: Record<string, string>13- manifest: object | string8+export 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 }12 19-const DEFAULT_DOCUMENT = 'index.html'20-13 // This middleware is available only on Cloudflare Workers.14 export 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 }31-32- 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- })39-40- if (!path) {41- return await next()42- }43-44- 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- })50-51- 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- }64-65- 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
1-import type { Context } from '../../context'1+import type { ServeStaticOptions } from '../../middleware/serve-static'2+import { serveStatic as baseServeStatic } from '../../middleware/serve-static'3 import type { Env, MiddlewareHandler } from '../../types'3-import { getFilePath } from '../../utils/filepath'4-import { getMimeType } from '../../utils/mime'4 5 // eslint-disable-next-line @typescript-eslint/ban-ts-comment6 // @ts-ignore7 const { open } = Deno8 10-export 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-}17-18-const DEFAULT_DOCUMENT = 'index.html'19-9 export 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- }29-30- 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- })37-38- if (!path) {39- return await next()40- }41-42- path = `./${path}`43-44- let file45-46- try {47- file = await open(path)48- } catch (e) {49- console.warn(`${e}`)50- }51-52- 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 }60-61- 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
1+import type { Context } from '../../context'2+import type { Env, MiddlewareHandler } from '../../types'3+import { getFilePath, getFilePathWithoutDefaultDocument } from '../../utils/filepath'4+import { getMimeType } from '../../utils/mime'5+6+export 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+}13+14+const DEFAULT_DOCUMENT = 'index.html'15+const defaultPathResolve = (path: string) => path16+17+/**18+ * This middleware is not directly used by the user. Create a wrapper specifying `getContent()` by the environment such as Deno or Bun.19+ */20+export 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)34+35+ let filename = options.path ?? decodeURI(url.pathname)36+ filename = options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename37+ const root = options.root38+39+ let path = getFilePath({40+ filename,41+ root,42+ defaultDocument: DEFAULT_DOCUMENT,43+ })44+45+ if (!path) {46+ return await next()47+ }48+49+ const getContent = options.getContent50+ const pathResolve = options.pathResolve ?? defaultPathResolve51+52+ path = pathResolve(path)53+ let content = await getContent(path)54+55+ 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+ }69+70+ 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+ }82+83+ await options.onNotFound?.(path, c)84+ await next()85+ return86+ }87+}modified:src/utils/filepath.test.ts+47 added-25 removed
1-import { getFilePath } from './filepath'1+import { getFilePath, getFilePathWithoutDefaultDocument } from './filepath'2 3+describe('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+ )9+10+ 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+ )21+22+ 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+})48+49 describe('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')52 53 expect(getFilePath({ filename: 'foo', root: 'bar' })).toBe('bar/foo/index.html')9- expect(getFilePath({ filename: 'foo.txt', root: 'bar' })).toBe('bar/foo.txt')54 55 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 )15-16- expect(getFilePath({ filename: './foo' })).toBe('foo/index.html')17- expect(getFilePath({ filename: 'foo', root: './bar' })).toBe('bar/foo/index.html')18-19- 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')28-29- 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 })61 62 function slashToBackslash(filename: string) {2 unmodified linesmodified:src/utils/filepath.ts+18 added-5 removed
4 unmodified lines5 }6 7 export const getFilePath = (options: FilePathOptions): string | undefined => {8 let filename = options.filename9- if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) {10- return11- }12-13- let root = options.root || ''9 const defaultDocument = options.defaultDocument || 'index.html'10 11 if (filename.endsWith('/')) {12 // /top/ => /top/index.html2 unmodified lines15 // /top => /top/index.html16 filename = filename.concat('/' + defaultDocument)17 }18 19+ const path = getFilePathWithoutDefaultDocument({20+ root: options.root,21+ filename,22+ })23+24+ return path25+}26+27+export const getFilePathWithoutDefaultDocument = (28+ options: Omit<FilePathOptions, 'defaultDocument'>29+) => {30+ let root = options.root || ''31+ let filename = options.filename32+33+ if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) {34+ return35+ }36+37 // /foo.html => foo.html38 filename = filename.replace(/^\.?[\/\\]/, '')39 40 // foo\bar.txt => foo/bar.txt11 unmodified lines