feat: update visibility (#164)
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 1a30e37 · Browse files · 12 files·+75 added−101 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+75 added−101 removed
- tests:+53 added−75 removed
- other:+22 added−26 removed
Provenance
- Commit
3d064d0- Tree
9efba82- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
1a30e37
12 files changed+75 added−101 removed
modified:src/middleware/basic-auth/index.test.ts+11 added-11 removed
65 unmodified lines6667686970707172727374757677787879808182838384858687888989909192939494959697989910010010110210310410510510610710810911011111211311311411511611711811911912012112212312412412512612712812965 unmodified lines app.get('/auth-unicode/*', () => new Response('auth')) app.get('/auth-multi/*', () => new Response('auth')) app.get('/auth-override-func/*', () => new Response('auth'))
it('Unauthorized', async () => { it('Should not authorize', async () => { const req = new Request('http://localhost/auth/a') const res = await app.dispatch(req) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(401) expect(await res.text()).toBe('Unauthorized') })
it('Authorizated', async () => { it('Should authorize', async () => { const credential = Buffer.from(username + ':' + password).toString('base64')
const req = new Request('http://localhost/auth/a') req.headers.set('Authorization', `Basic ${credential}`) const res = await app.dispatch(req) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })
it('Authorizated Unicode', async () => { it('Should authorize Unicode', async () => { const credential = Buffer.from(username + ':' + unicodePassword).toString('base64')
const req = new Request('http://localhost/auth-unicode/a') req.headers.set('Authorization', `Basic ${credential}`) const res = await app.dispatch(req) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })
it('Authorizated multiple users', async () => { it('Should authorize multiple users', async () => { let credential = Buffer.from(usernameB + ':' + passwordB).toString('base64')
let req = new Request('http://localhost/auth-multi/b') req.headers.set('Authorization', `Basic ${credential}`) let res = await app.dispatch(req) let res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth')
credential = Buffer.from(usernameC + ':' + passwordC).toString('base64') req = new Request('http://localhost/auth-multi/c') req.headers.set('Authorization', `Basic ${credential}`) res = await app.dispatch(req) res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })
it('should authorize with sha256 function override', async () => { it('Should authorize with sha256 function override', async () => { const credential = Buffer.from(username + ':' + password).toString('base64')
const req = new Request('http://localhost/auth-override-func/a') req.headers.set('Authorization', `Basic ${credential}`) const res = await app.dispatch(req) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })})modified:src/middleware/body-parse/index.test.ts+3 added-3 removed
20 unmodified lines212223242525262728295 unmodified lines353637383939404142438 unmodified lines525354555656575859602 unmodified lines20 unmodified lines method: 'POST', body: JSON.stringify(payload), headers: new Headers({ 'Content-Type': 'application/json' }), }) const res = await app.dispatch(req) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual(payload) expect(await res.json()).toEqual(payload)5 unmodified lines method: 'POST', body: 'hello', headers: new Headers({ 'Content-Type': 'application/text' }), }) const res = await app.dispatch(req) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual(payload) expect(await res.text()).toEqual(payload)8 unmodified lines headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) const res = await app.dispatch(req) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual({ message: 'hello' }) expect(await res.json()).toEqual({ message: 'hello' })2 unmodified linesmodified:src/middleware/cookie/index.test.ts+3 added-5 removed
16 unmodified lines17 it('Parse cookie on c.req.cookie', async () => {18 const req = new Request('http://localhost/cookie')19 const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry '20 req.headers.set('Cookie', cookieString)21- const res = await app.dispatch(req)21+ const res = await app.request(req)22 23 expect(res.headers.get('Yummy-Cookie')).toBe('choco')24 expect(res.headers.get('Tasty-Cookie')).toBe('strawberry')25 })5 unmodified lines31 return c.text('Give cookie')32 })33 34 it('Set cookie on c.cookie', async () => {35- const req = new Request('http://localhost/set-cookie')36- const res = await app.dispatch(req)35+ const res = await app.request('http://localhost/set-cookie')36 expect(res.status).toBe(200)37 const header = res.headers.get('Set-Cookie')38 expect(header).toBe('delicious_cookie=macha')39 })13 unmodified lines53 return c.text('Give cookie')54 })55 56 it('Complex pattern', async () => {58- const req = new Request('http://localhost/set-cookie-complex')59- const res = await app.dispatch(req)57+ const res = await app.request('http://localhost/set-cookie-complex')58 expect(res.status).toBe(200)59 const header = res.headers.get('Set-Cookie')60 expect(header).toBe(61 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'3 unmodified linesmodified:src/middleware/cors/index.test.ts+3 added-4 removed
23 unmodified lines24 return c.json({ success: true })25 })26 27 it('GET default', async () => {28- const req = new Request('http://localhost/api/abc')29- const res = await app.dispatch(req)28+ const res = await app.request('http://localhost/api/abc')29 30 expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')31 expect(res.headers.get('Vary')).toBeNull()32 })33 34 it('Preflight default', async () => {35 const req = new Request('https://localhost/api/abc', { method: 'OPTIONS' })36 req.headers.append('Access-Control-Request-Headers', 'X-PINGOTHER, Content-Type')38- const res = await app.dispatch(req)37+ const res = await app.request(req)38 39 expect(res.status).toBe(204)40 expect(res.headers.get('Access-Control-Allow-Methods').split(',')[0]).toBe('GET')41 expect(res.headers.get('Access-Control-Allow-Headers').split(',')).toEqual([3 unmodified lines45 })46 47 it('Preflight with options', async () => {48 const req = new Request('https://localhost/api2/abc', { method: 'OPTIONS' })50- const res = await app.dispatch(req)49+ const res = await app.request(req)50 51 expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')52 expect(res.headers.get('Vary').split(/\s*,\s*/)).toEqual(expect.arrayContaining(['Origin']))53 expect(res.headers.get('Access-Control-Allow-Headers').split(/\s*,\s*/)).toEqual([16 unmodified linesmodified:src/middleware/etag/index.test.ts+9 added-18 removed
15 unmodified lines16 app.get('/etag-weak/abc', (c) => {17 return c.text('Hono is cool')18 })19 20- it('should return etag header', async () => {21- let req = new Request('http://localhost/etag/abc')22- let res = await app.dispatch(req)23-20+ it('Should return etag header', async () => {21+ let res = await app.request('http://localhost/etag/abc')22 expect(res.headers.get('ETag')).not.toBeFalsy()23 expect(res.headers.get('ETag')).toBe('"4e32298b1cb4edc595237405e5b696e105c2399a"')24 27- req = new Request('http://localhost/etag/def')28- res = await app.dispatch(req)29-25+ res = await app.request('http://localhost/etag/def')26 expect(res.headers.get('ETag')).not.toBeFalsy()27 expect(res.headers.get('ETag')).toBe('"c1d44ff03aff1372856c281854f454e2e1d15b7c"')28 })29 34- it('should return etag header - weak', async () => {35- const req = new Request('http://localhost/etag-weak/abc')36- const res = await app.dispatch(req)37-30+ it('Should return etag header - weak', async () => {31+ const res = await app.request('http://localhost/etag-weak/abc')32 expect(res.headers.get('ETag')).not.toBeFalsy()33 expect(res.headers.get('ETag')).toBe('W/"4e32298b1cb4edc595237405e5b696e105c2399a"')34 })35 42- it('should return 304 response', async () => {43- let req = new Request('http://localhost/etag/abc')44- let res = await app.dispatch(req)45-36+ it('Should return 304 response', async () => {37+ let res = await app.request('http://localhost/etag/abc')38 expect(res.status).toBe(200)39 expect(res.headers.get('ETag')).not.toBeFalsy()40 const etag = res.headers.get('Etag')41 50- req = new Request('http://localhost/etag/abc', {42+ const req = new Request('http://localhost/etag/abc', {43 headers: {44 'If-None-Match': etag,45 },46 })55- res = await app.dispatch(req)56-47+ res = await app.request(req)48 expect(res.status).toBe(304)49 expect(await res.text()).toBe('')50 })51 })modified:src/middleware/logger/index.test.ts+4 added-9 removed
16 unmodified lines17 app.get('/long', (c) => c.text(longRandomString))18 app.get('/empty', (c) => c.text(''))19 20 it('Log status 200 with empty body', async () => {21- const req = new Request('http://localhost/empty')22- const res = await app.dispatch(req)21+ const res = await app.request('http://localhost/empty')22 expect(res).not.toBeNull()23 expect(res.status).toBe(200)24 expect(log.startsWith(' --> GET /empty \x1b[32m200\x1b[0m')).toBe(true)25 expect(log.endsWith(' 0b')).toBe(true)26 })27 28 it('Log status 200 with small body', async () => {30- const req = new Request('http://localhost/short')31- const res = await app.dispatch(req)29+ const res = await app.request('http://localhost/short')30 expect(res).not.toBeNull()31 expect(res.status).toBe(200)32 expect(log.startsWith(' --> GET /short \x1b[32m200\x1b[0m')).toBe(true)33 expect(log.endsWith(` ${shortRandomString.length}b`)).toBe(true)34 })35 36 it('Log status 200 with big body', async () => {39- const req = new Request('http://localhost/long')40- const res = await app.dispatch(req)37+ const res = await app.request('http://localhost/long')38 expect(res).not.toBeNull()39 expect(res.status).toBe(200)40 expect(log.startsWith(' --> GET /long \x1b[32m200\x1b[0m')).toBe(true)41 expect(log.endsWith(` ${longRandomString.length / 1024}kB`)).toBe(true)3 unmodified lines45 const msg = 'Default 404 Not Found'46 app.all('*', (c) => {47 return c.text(msg, 404)48 })52-53- const req = new Request('http://localhost/notfound')49+ const res = await app.request('http://localhost/notfound')54- const res = await app.dispatch(req)50 expect(res).not.toBeNull()51 expect(res.status).toBe(404)52 expect(log.startsWith(' --> GET /notfound \x1b[33m404\x1b[0m')).toBe(true)53 expect(log.endsWith(` ${msg.length}b`)).toBe(true)2 unmodified linesmodified:src/middleware/mustache/index.test.ts+2 added-4 removed
43 unmodified lines44 return c.render('index')45 })46 47 it('Mustache template rendering', async () => {48- const req = new Request('http://localhost/foo')49- const res = await app.dispatch(req)48+ const res = await app.request('http://localhost/foo')49 expect(res.status).toBe(200)50 expect(await res.text()).toBe('<html><body>Title: Hono!</body></html>')51 })52 53 it('Mustache template rendering with root', async () => {55- const req = new Request('http://localhost/bar')56- const res = await app.dispatch(req)54+ const res = await app.request('http://localhost/bar')55 expect(res.status).toBe(200)56 expect(await res.text()).toBe('<h1>With Root</h1>')57 })58 })modified:src/middleware/powered-by/index.test.ts+3 added-4 removed
3 unmodified lines4 describe('Powered by Middleware', () => {5 const app = new Hono()6 7 app.use('*', poweredBy())8- app.get('/', () => new Response('root'))8+ app.get('/', (c) => c.text('root'))9 10- it('Response headers include X-Powered-By', async () => {11- const req = new Request('http://localhost/')12- const res = await app.dispatch(req)10+ it('Should return with X-Powered-By header', async () => {11+ const res = await app.request('http://localhost/')12 expect(res).not.toBeNull()13 expect(res.status).toBe(200)14 expect(res.headers.get('X-Powered-By')).toBe('Hono')15 })1 unmodified linemodified:src/middleware/pretty-json/index.test.ts+2 added-4 removed
8 unmodified lines9 })10 11 it('Should return pretty JSON output', async () => {12 app.use('*', prettyJSON())13- const req = new Request('http://localhost/?pretty')14- const res = await app.dispatch(req)13+ const res = await app.request('http://localhost/?pretty')14 expect(res).not.toBeNull()15 expect(res.status).toBe(200)16 expect(await res.text()).toBe(`{17 "message": "Hono!"1 unmodified line19 })20 21 it('Should return pretty JSON output with 4 spaces', async () => {22 app.use('*', prettyJSON({ space: 4 }))24- const req = new Request('http://localhost/?pretty')25- const res = await app.dispatch(req)23+ const res = await app.request('http://localhost/?pretty')24 expect(res).not.toBeNull()25 expect(res.status).toBe(200)26 expect(await res.text()).toBe(`{27 "message": "Hono!"3 unmodified linesmodified:src/middleware/serve-static/index.test.ts+13 added-13 removed
24 unmodified lines25 })26 27 describe('ServeStatic Middleware', () => {28 const app = new Hono()29-29 app.use('/static/*', serveStatic({ root: './assets' }))30 app.use('/static-no-root/*', serveStatic())31 33- it('Serve static files', async () => {34- let req = new Request('http://localhost/static/plain.txt')35- let res = await app.dispatch(req)32+ it('Should return plain.txt', async () => {33+ const res = await app.request('http://localhost/static/plain.txt')34 expect(res.status).toBe(200)35 expect(await res.text()).toBe('This is plain.txt')36 expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')37 expect(res.headers.get('Content-Length')).toBe('17')38+ })39 41- req = new Request('http://localhost/static/hono.html')42- res = await app.dispatch(req)40+ it('Should return hono.html', async () => {41+ const res = await app.request('http://localhost/static/hono.html')42 expect(res.status).toBe(200)43 expect(await res.text()).toBe('<h1>Hono!</h1>')44 expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')45 expect(res.headers.get('Content-Length')).toBe('14')46+ })47 48- req = new Request('http://localhost/static/not-found.html')49- res = await app.dispatch(req)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 52- req = new Request('http://localhost/static-no-root/plain.txt')53- res = await app.dispatch(req)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 expect(res.headers.get('Content-Length')).toBe('17')59 })60 60- it('Serve index.html', async () => {61- const req = new Request('http://localhost/static/top')62- const res = await app.dispatch(req)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 expect(res.headers.get('Content-Length')).toBe('12')2 unmodified linesmodified:src/context.ts+13 added-9 removed
23 unmodified lines24 constructor(25 req: Request<RequestParamKeyType>,26 opts?: { res: Response; env: Env; event: FetchEvent }27 ) {28- this.req = req28+ this.req = this.initRequest(req)29 if (opts) {30 this.res = opts.res31 this.env = opts.env32 this.event = opts.event33 }34 this._headers = {}35 }36 37+ private initRequest<T>(req: Request<T>): Request<T> {38+ req.header = (name: string): string => {39+ return req.headers.get(name)40+ }41+ req.query = (key: string): string => {42+ const url = new URL(req.url)43+ return url.searchParams.get(key)44+ }45+ return req46+ }47+48 header(name: string, value: string): void {38- /*39- XXX:40- app.use('*', (c, next) => {41- next()42- c.header('foo', 'bar') // => c.res.headers.set(...)43- })44- */49 if (this.res) {50 this.res.headers.set(name, value)51 }52 this._headers[name] = value51 unmodified lines104 }105 106 json(object: object, status: StatusCode = this._status, headers: Headers = {}): Response {107 if (typeof object !== 'object') {104- throw new TypeError('json method arg must be a object!')108+ throw new TypeError('json method arg must be an object!')109 }110 const body = this._pretty111 ? JSON.stringify(object, null, this._prettySpace)112 : JSON.stringify(object)29 unmodified linesmodified:src/hono.ts+9 added-17 removed
9 unmodified lines10 interface Request<ParamKeyType = string> {11 param: (key: ParamKeyType) => string12 query: (key: string) => string13 header: (name: string) => string14- // TODO: do not use `any`14 parsedBody: any15 }16 }17 44 unmodified lines62 'options',63 'patch',64 'all'65 ) {67- routerClass: { new (): Router<any> } = TrieRouter68- strict: boolean = true // strict routing - default is true69- router: Router<Handler>70- middlewareRouters: Router<MiddlewareHandler>[]71- tempPath: string66+ readonly routerClass: { new (): Router<any> } = TrieRouter67+ readonly strict: boolean = true // strict routing - default is true68+ private router: Router<Handler>69+ private middlewareRouters: Router<MiddlewareHandler>[]70+ private tempPath: string71 72 constructor(init: Partial<Pick<Hono, 'routerClass' | 'strict'>> = {}) {73 super()74 60 unmodified lines135 private async matchRoute(method: string, path: string): Promise<Result<Handler>> {136 return this.router.match(method, path)137 }138 140- async dispatch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {139+ private async dispatch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {140 const path = getPathFromURL(request.url, { strict: this.strict })141 const method = request.method142 143 const result = await this.matchRoute(method, path)1 unmodified line145 // Methods for Request object146 request.param = (key: string): string => {147 if (result) return result.params[key]148 }150- request.header = (name: string): string => {151- return request.headers.get(name)152- }153- request.query = (key: string): string => {154- const url = new URL(c.req.url)155- return url.searchParams.get(key)156- }149 150 const handler = result ? result.handler : this.notFoundHandler151 152 const middleware = []30 unmodified lines183 async fetch(request: Request, env?: Env, event?: FetchEvent): Promise<Response> {184 return this.dispatch(request, env, event)185 }186 195- request(input: RequestInfo, requestInit?: RequestInit) {196- const req = new Request(input, requestInit)187+ request(input: RequestInfo, requestInit?: RequestInit): Promise<Response> {188+ const req = input instanceof Request ? input : new Request(input, requestInit)189 return this.dispatch(req)190 }191 200- fire() {192+ fire(): void {193 addEventListener('fetch', (event: FetchEvent): void => {194 event.respondWith(this.handleEvent(event))195 })196 }1 unmodified line