feat: serve-static middleware supports Module Worker mode (#250)
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 9cfba57 · Browse files · 11 files·+254 added−160 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+254 added−160 removed
- tests:+117 added−100 removed
- other:+137 added−60 removed
Provenance
- Commit
923a30e- Tree
9f2f11f- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
9cfba57
11 files changed+254 added−160 removed
deleted:src/middleware/serve-static/index.test.ts-100 removed
1-import type { Context } from '../../context'2-import type { Next } from '../../hono'3-import { Hono } from '../../hono'4-import { serveStatic } from '.'5-6-// Mock7-const store: { [key: string]: string } = {8- 'assets/static/plain.abcdef.txt': 'This is plain.txt',9- 'assets/static/hono.abcdef.html': '<h1>Hono!</h1>',10- 'assets/static/top/index.abcdef.html': '<h1>Top</h1>',11- 'static-no-root/plain.abcdef.txt': 'That is plain.txt',12-}13-const manifest = JSON.stringify({14- 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',15- 'assets/static/hono.html': 'assets/static/hono.abcdef.html',16- 'assets/static/top/index.html': 'assets/static/top/index.abcdef.html',17- 'static-no-root/plain.txt': 'static-no-root/plain.abcdef.txt',18-})19-20-Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })21-Object.assign(global, {22- __STATIC_CONTENT: {23- get: (path: string) => {24- return store[path]25- },26- },27-})28-29-describe('ServeStatic Middleware', () => {30- const app = new Hono()31- app.use('/static/*', serveStatic({ root: './assets' }))32- app.use('/static-no-root/*', serveStatic())33-34- it('Should return plain.txt', async () => {35- const res = await app.request('http://localhost/static/plain.txt')36- expect(res.status).toBe(200)37- expect(await res.text()).toBe('This is plain.txt')38- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')39- })40-41- it('Should return hono.html', async () => {42- const res = await app.request('http://localhost/static/hono.html')43- expect(res.status).toBe(200)44- expect(await res.text()).toBe('<h1>Hono!</h1>')45- expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')46- })47-48- it('Should return 404 response', async () => {49- const res = await app.request('http://localhost/static/not-found.html')50- expect(res.status).toBe(404)51- })52-53- it('Should return plan.txt', async () => {54- const res = await app.request('http://localhost/static-no-root/plain.txt')55- expect(res.status).toBe(200)56- expect(await res.text()).toBe('That is plain.txt')57- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')58- })59-60- it('Should return index.html', async () => {61- const res = await app.request('http://localhost/static/top')62- expect(res.status).toBe(200)63- expect(await res.text()).toBe('<h1>Top</h1>')64- expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')65- })66-})67-68-describe('With middleware', () => {69- const app = new Hono()70- const md1 = async (c: Context, next: Next) => {71- await next()72- c.res.headers.append('x-foo', 'bar')73- }74- const md2 = async (c: Context, next: Next) => {75- await next()76- c.res.headers.append('x-foo2', 'bar2')77- }78-79- app.use('/static/*', md1)80- app.use('/static/*', serveStatic({ root: './assets' }))81- app.use('/static/*', md2)82- app.get('/static/foo', (c) => {83- return c.text('bar')84- })85-86- it('Should return plain.txt with correct headers', async () => {87- const res = await app.request('http://localhost/static/plain.txt')88- expect(res.status).toBe(200)89- expect(await res.text()).toBe('This is plain.txt')90- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')91- expect(res.headers.get('x-foo')).toBe('bar')92- expect(res.headers.get('x-foo2')).toBe('bar2')93- })94-95- it('Should return 200 Response', async () => {96- const res = await app.request('http://localhost/static/foo')97- expect(res.status).toBe(200)98- expect(await res.text()).toBe('bar')99- })100-})modified:src/middleware/serve-static/index.ts+1 added-41 removed
12345678910111213141516171819202122232425262728293031323334353637383940411import type { Context } from '../../context'import type { Next } from '../../hono'import { getContentFromKVAsset, getKVFilePath } from '../../utils/cloudflare'import { getMimeType } from '../../utils/mime'
type Options = { root: string}
const DEFAULT_DOCUMENT = 'index.html'
// This middleware is available only on Cloudflare Workers.export const serveStatic = (opt: Options = { root: '' }) => { return async (c: Context, next: Next) => { // Do nothing if Response is already set if (c.res) { await next() }
const url = new URL(c.req.url)
const path = getKVFilePath({ filename: url.pathname, root: opt.root, defaultDocument: DEFAULT_DOCUMENT, })
const content = await getContentFromKVAsset(path) if (content) { const mimeType = getMimeType(path) if (mimeType) { c.header('Content-Type', mimeType) } // Return Response object return c.body(content) } else { console.warn(`Static file: ${path} is not found`) await next() } }}export { serveStatic } from './serve-static'added:src/middleware/serve-static/module.mts+15 added
123456789101112131415// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignore// For ES module modeimport manifest from '__STATIC_CONTENT_MANIFEST'import type { ServeStaticOptions } from './serve-static'import { serveStatic } from './serve-static'
const module = (options: ServeStaticOptions = { root: '' }) => { return serveStatic({ root: options.root, manifest: options.manifest ? options.manifest : manifest, })}
export { module as serveStatic }modified:src/middleware/serve-static/README.md+15 added-3 removed
123345677899101112133 unmodified lines171819202122232425262728293031323334353618 unmodified lines# Serve Static Middleware
Mustache Middleware is available only on Cloudflare Workers.Serve Static Middleware is available only on Cloudflare Workers.
## Usage
index.js:index.ts:
```js```tsimport { Hono } from 'hono'import { serveStatic } from 'hono/serve-static'
const app = new Hono()3 unmodified lines
app.fire()```
In Module Worker mode:
```tsimport { Hono } from 'hono'import { serveStatic } from 'hono/serve-static.module' // <---
const app = new Hono()//...
export default app```
wrangler.toml:
```toml[site]18 unmodified linesadded:src/middleware/serve-static/serve-static.test.ts+117 added
1+import type { Context } from '../../context'2+import type { Next } from '../../hono'3+import { Hono } from '../../hono'4+import { serveStatic } from '.'5+6+// Mock7+const store: Record<string, string> = {8+ 'assets/static/plain.abcdef.txt': 'This is plain.txt',9+ 'assets/static/hono.abcdef.html': '<h1>Hono!</h1>',10+ 'assets/static/top/index.abcdef.html': '<h1>Top</h1>',11+ 'static-no-root/plain.abcdef.txt': 'That is plain.txt',12+ 'assets/static/options/foo.abcdef.txt': 'With options',13+}14+const manifest = JSON.stringify({15+ 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',16+ 'assets/static/hono.html': 'assets/static/hono.abcdef.html',17+ 'assets/static/top/index.html': 'assets/static/top/index.abcdef.html',18+ 'static-no-root/plain.txt': 'static-no-root/plain.abcdef.txt',19+})20+21+Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })22+Object.assign(global, {23+ __STATIC_CONTENT: {24+ get: (path: string) => {25+ return store[path]26+ },27+ },28+})29+30+describe('ServeStatic Middleware', () => {31+ const app = new Hono()32+ app.use('/static/*', serveStatic({ root: './assets' }))33+ app.use('/static-no-root/*', serveStatic())34+35+ it('Should return plain.txt', async () => {36+ const res = await app.request('http://localhost/static/plain.txt')37+ expect(res.status).toBe(200)38+ expect(await res.text()).toBe('This is plain.txt')39+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')40+ })41+42+ it('Should return hono.html', async () => {43+ const res = await app.request('http://localhost/static/hono.html')44+ expect(res.status).toBe(200)45+ expect(await res.text()).toBe('<h1>Hono!</h1>')46+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')47+ })48+49+ it('Should return 404 response', async () => {50+ const res = await app.request('http://localhost/static/not-found.html')51+ expect(res.status).toBe(404)52+ })53+54+ it('Should return plan.txt', async () => {55+ const res = await app.request('http://localhost/static-no-root/plain.txt')56+ expect(res.status).toBe(200)57+ expect(await res.text()).toBe('That is plain.txt')58+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')59+ })60+61+ it('Should return index.html', async () => {62+ const res = await app.request('http://localhost/static/top')63+ expect(res.status).toBe(200)64+ expect(await res.text()).toBe('<h1>Top</h1>')65+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')66+ })67+})68+69+describe('With options', () => {70+ const manifest = {71+ 'assets/static/options/foo.txt': 'assets/static/options/foo.abcdef.txt',72+ }73+74+ const app = new Hono()75+ app.use('/static/*', serveStatic({ root: './assets', manifest: manifest }))76+77+ it('Should return foo.txt', async () => {78+ const res = await app.request('http://localhost/static/options/foo.txt')79+ expect(res.status).toBe(200)80+ expect(await res.text()).toBe('With options')81+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')82+ })83+})84+85+describe('With middleware', () => {86+ const app = new Hono()87+ const md1 = async (c: Context, next: Next) => {88+ await next()89+ c.res.headers.append('x-foo', 'bar')90+ }91+ const md2 = async (c: Context, next: Next) => {92+ await next()93+ c.res.headers.append('x-foo2', 'bar2')94+ }95+96+ app.use('/static/*', md1)97+ app.use('/static/*', serveStatic({ root: './assets' }))98+ app.use('/static/*', md2)99+ app.get('/static/foo', (c) => {100+ return c.text('bar')101+ })102+103+ it('Should return plain.txt with correct headers', async () => {104+ const res = await app.request('http://localhost/static/plain.txt')105+ expect(res.status).toBe(200)106+ expect(await res.text()).toBe('This is plain.txt')107+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')108+ expect(res.headers.get('x-foo')).toBe('bar')109+ expect(res.headers.get('x-foo2')).toBe('bar2')110+ })111+112+ it('Should return 200 Response', async () => {113+ const res = await app.request('http://localhost/static/foo')114+ expect(res.status).toBe(200)115+ expect(await res.text()).toBe('bar')116+ })117+})added:src/middleware/serve-static/serve-static.ts+46 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546import type { Context } from '../../context'import type { Handler, Next } from '../../hono'import { getContentFromKVAsset, getKVFilePath } from '../../utils/cloudflare'import { getMimeType } from '../../utils/mime'
export type ServeStaticOptions = { root: string manifest?: object | string namespace?: KVNamespace}
const DEFAULT_DOCUMENT = 'index.html'
// This middleware is available only on Cloudflare Workers.export const serveStatic = (options: ServeStaticOptions = { root: '' }): Handler => { return async (c: Context, next: Next) => { // Do nothing if Response is already set if (c.res) { await next() }
const url = new URL(c.req.url)
const path = getKVFilePath({ filename: url.pathname, root: options.root, defaultDocument: DEFAULT_DOCUMENT, })
const content = await getContentFromKVAsset(path, { manifest: options.manifest, namespace: options.namespace ? options.namespace : c.env ? c.env.__STATIC_CONTENT : undefined, }) if (content) { const mimeType = getMimeType(path) if (mimeType) { c.header('Content-Type', mimeType) } // Return Response object return c.body(content) } else { console.warn(`Static file: ${path} is not found`) await next() } }}modified:src/utils/cloudflare.ts+35 added-12 removed
1123345645678910111213141516171819202122232482526272829303132113334353637386 unmodified lines454647482649505152535432333435555657585960616217 unmodified linesdeclare const __STATIC_CONTENT: KVNamespace, __STATIC_CONTENT_MANIFEST: stringdeclare const __STATIC_CONTENT: KVNamespacedeclare const __STATIC_CONTENT_MANIFEST: string
export const getContentFromKVAsset = async (path: string): Promise<ArrayBuffer> => { let ASSET_MANIFEST: Record<string, string> if (typeof __STATIC_CONTENT_MANIFEST === 'string') { ASSET_MANIFEST = JSON.parse(__STATIC_CONTENT_MANIFEST)export type KVAssetOptions = { manifest?: object | string namespace?: KVNamespace}
export const getContentFromKVAsset = async ( path: string, options?: KVAssetOptions): Promise<ArrayBuffer> => { let ASSET_MANIFEST: Record<string, string> = {}
if (options && options.manifest) { if (typeof options.manifest === 'string') { ASSET_MANIFEST = JSON.parse(options.manifest) } else { ASSET_MANIFEST = options.manifest as Record<string, string> } } else { if (typeof __STATIC_CONTENT_MANIFEST === 'string') { ASSET_MANIFEST = JSON.parse(__STATIC_CONTENT_MANIFEST) } else { ASSET_MANIFEST = __STATIC_CONTENT_MANIFEST ASSET_MANIFEST = __STATIC_CONTENT_MANIFEST } }
let ASSET_NAMESPACE: KVNamespace if (options && options.namespace) { ASSET_NAMESPACE = options.namespace } else { const ASSET_NAMESPACE = __STATIC_CONTENT ASSET_NAMESPACE = __STATIC_CONTENT }
const key = ASSET_MANIFEST[path] || path if (!key) { return6 unmodified lines } return content}
type Options = {type FilePathOptions = { filename: string root?: string defaultDocument?: string}
export const getKVFilePath = (opt: Options): string => { let filename = opt.filename let root = opt.root || '' const defaultDocument = opt.defaultDocument || 'index.html'export const getKVFilePath = (options: FilePathOptions): string => { let filename = options.filename let root = options.root || '' const defaultDocument = options.defaultDocument || 'index.html'
if (filename.endsWith('/')) { // /top/ => /top/index.html filename = filename.concat(defaultDocument)17 unmodified linesmodified:package.json+6 added-2 removed
9 unmodified lines10 "scripts": {11 "test": "jest",12 "lint": "eslint --ext js,ts src .eslintrc.js",13 "lint:fix": "eslint --ext js,ts src .eslintrc.js --fix",14- "build": "rimraf dist && tsc --project tsconfig.build.json",14+ "build": "rimraf dist && tsc --project tsconfig.build.json && tsc --project tsconfig.build.esm.json",15 "watch": "tsc --project tsconfig.build.json -w",16 "prepublishOnly": "yarn build"17 },18 "exports": {9 unmodified lines28 "./mustache": "./dist/middleware/mustache/index.js",29 "./powered-by": "./dist/middleware/powered-by/index.js",30 "./pretty-json": "./dist/middleware/pretty-json/index.js",31 "./serve-static": "./dist/middleware/serve-static/index.js",32+ "./serve-static.module": "./dist/middleware/serve-static/module.mjs",33 "./router/trie-router": "./dist/router/trie-router/index.js",34 "./router/reg-exp-router": "./dist/router/reg-exp-router/index.js",35 "./utils/jwt": "./dist/utils/jwt/index.js",36 "./utils/*": "./dist/utils/*.js"33 unmodified lines70 "pretty-json": [71 "./dist/middleware/pretty-json"72 ],73 "serve-static": [73- "./dist/middleware/serve-static"74+ "./dist/middleware/serve-static/index.d.ts"75 ],76+ "serve-static.module": [77+ "./dist/middleware/serve-static/module.d.ts"78+ ],79 "router/trie-router": [80 "./dist/router/trie-router/router.d.ts"81 ],82 "router/reg-exp-router": [61 unmodified linesadded:tsconfig.build.esm.json+16 added
12345678910111213141516{ "extends": "./tsconfig.json", "compilerOptions": { "target": "es2020", "module": "es2020", "rootDir": "./src/", "outDir": "./dist/", }, "include": [ "src/**/*.mts" ], "exclude": [ "src/**/*.ts", "src/**/*.test.ts" ]}No newline at end of filemodified:tsconfig.build.json+1 added-1 removed
1234456789{ "extends": "./tsconfig.json", "include": [ "src/**/*" "src/**/*.ts" ], "exclude": [ "src/**/*.test.ts" ]}modified:tsconfig.json+2 added-1 removed
1 unmodified line2 "compilerOptions": {3 "target": "es2017",4 "module": "commonjs",5 "declaration": true,6+ "moduleResolution": "Node",7 "outDir": "./dist",8 "esModuleInterop": true,9 "forceConsistentCasingInFileNames": true,10 "strict": true,6 unmodified lines17 "@cloudflare/workers-types"18 ],19 },20 "include": [20- "src/**/*",21+ "src/**/*.ts",22 "src/**/*.test.ts"23 ],24 }