Skip to content
Myr

refactor(TypeScript): enable strict null check (#280)

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 c066151 · Browse files · 32 files+250 added−221 removed
This commit

State

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

Diff stats

32 files+250 added−221 removed

  • tests:+175 added−168 removed
  • other:+75 added−53 removed

32 files+250 added−221 removed

modified:src/middleware/basic-auth/index.ts+2 added-2 removed
modified:src/middleware/cookie/index.ts+1 added-1 removed
modified:src/middleware/cors/index.test.ts+6 added-6 removed
35 unmodified lines
36 req.headers.append('Access-Control-Request-Headers', 'X-PINGOTHER, Content-Type')37 const res = await app.request(req)3839 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([40 expect(res.headers.get('Access-Control-Allow-Methods')?.split(',')[0]).toBe('GET')41 expect(res.headers.get('Access-Control-Allow-Headers')?.split(',')).toEqual([42 'X-PINGOTHER',43 'Content-Type',44 ])45 })
2 unmodified lines
48 const req = new Request('https://localhost/api2/abc', { method: 'OPTIONS' })49 const res = await app.request(req)5051 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([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([54 'X-Custom-Header',55 'Upgrade-Insecure-Requests',56 ])57 expect(res.headers.get('Access-Control-Allow-Methods').split(/\s*,\s*/)).toEqual([57 expect(res.headers.get('Access-Control-Allow-Methods')?.split(/\s*,\s*/)).toEqual([58 'POST',59 'GET',60 'OPTIONS',61 ])62 expect(res.headers.get('Access-Control-Expose-Headers').split(/\s*,\s*/)).toEqual([62 expect(res.headers.get('Access-Control-Expose-Headers')?.split(/\s*,\s*/)).toEqual([63 'Content-Length',64 'X-Kuma-Revision',65 ])66 expect(res.headers.get('Access-Control-Max-Age')).toBe('600')
3 unmodified lines
modified:src/middleware/cors/index.ts+4 added-4 removed
39 unmodified lines
40 if (opts.credentials) {41 set('Access-Control-Allow-Credentials', 'true')42 }4344 if (opts.exposeHeaders.length) {44 if (opts.exposeHeaders?.length) {45 set('Access-Control-Expose-Headers', opts.exposeHeaders.join(','))46 }4748 if (c.req.method === 'OPTIONS') {
2 unmodified lines
51 if (opts.maxAge != null) {52 set('Access-Control-Max-Age', opts.maxAge.toString())53 }5455 if (opts.allowMethods.length) {55 if (opts.allowMethods?.length) {56 set('Access-Control-Allow-Methods', opts.allowMethods.join(','))57 }5859 let headers = opts.allowHeaders60 if (!headers.length) {60 if (!headers?.length) {61 const requestHeaders = c.req.headers.get('Access-Control-Request-Headers')62 if (requestHeaders) {63 headers = requestHeaders.split(/\s*,\s*/)64 }65 }66 if (headers.length) {66 if (headers?.length) {67 set('Access-Control-Allow-Headers', headers.join(','))68 set('Vary', 'Access-Control-Request-Headers')69 }70
11 unmodified lines
modified:src/middleware/etag/index.test.ts+1 added-1 removed
35 unmodified lines
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')40 const etag = res.headers.get('Etag') || ''4142 const req = new Request('http://localhost/etag/abc', {43 headers: {44 'If-None-Match': etag,
7 unmodified lines
modified:src/middleware/etag/index.ts+3 added-2 removed
11 unmodified lines
12 const ifNoneMatch = c.req.header('If-None-Match') || c.req.header('if-none-match')1314 await next()1516 const res = c.res as Response16 const clone = c.res.clone()17 const body = await parseBody(c.res)17 const clone = res.clone()18 const body = await parseBody(res)19 const hash = await sha1(body)2021 const etag = options.weak ? `W/"${hash}"` : `"${hash}"`22
13 unmodified lines
modified:src/middleware/graphql-server/index.ts+7 added-2 removed
53 unmodified lines
54 if (e instanceof Error) {55 console.error(`${e.stack || e.message}`)56 return c.json(errorMessages([e.message], [e]), 400)57 }58 throw e59 }6061 const { query, variables, operationName } = params62
21 unmodified lines
84 originalError: syntaxError,85 })86 return c.json(errorMessages(['GraphQL syntax error.'], [e]), 400)87 }88 throw syntaxError89 }9091 // Validate AST, reporting any errors.92 const validationErrors = validate(schema, documentAST, [...specifiedRules, ...validationRules])
44 unmodified lines
137 })138 // Return 400: Bad Request if any execution context errors exist.139 return c.json(errorMessages(['GraphQL execution context error.'], [e]), 400)140 }141 throw contextError142 }143144 if (!result.data) {141 if (result.data == null) {142 return c.json(errorMessages([result.errors.toString()], result.errors), 500)145 if (result.errors) {146 return c.json(errorMessages([result.errors.toString()], result.errors), 500)147 }148 }149150 /*151 Now, does not support GraphiQL
87 unmodified lines
modified:src/middleware/serve-static/serve-static.ts+5 added-4 removed
1import type { Context } from '../../context'1import type { Context, Env } from '../../context'2import type { Handler, Next } from '../../hono'3import { getContentFromKVAsset, getKVFilePath } from '../../utils/cloudflare'4import { getMimeType } from '../../utils/mime'5
5 unmodified lines
1112const DEFAULT_DOCUMENT = 'index.html'1314// This middleware is available only on Cloudflare Workers.15export const serveStatic = (options: ServeStaticOptions = { root: '' }): Handler => {16 return async (c: Context, next: Next) => {15export const serveStatic = (options: ServeStaticOptions = { root: '' }): Handler<string, Env> => {16 return async (c: Context, next: Next): Promise<Response | undefined> => {17 // Do nothing if Response is already set18 if (c.res && c.res.finalized) {18 if (c.res && c.res._finalized) {19 await next()20 }2122 const url = new URL(c.req.url)
18 unmodified lines
41 } else {42 console.warn(`Static file: ${path} is not found`)43 await next()44 }45 return46 }47}
modified:src/router/reg-exp-router/node.ts+2 added-2 removed
44 unmodified lines
45 children: Record<string, Node> = {}46 reverse: boolean4748 constructor({ reverse }: Partial<Node> = { reverse: false }) {49 this.reverse = reverse49 this.reverse = reverse as boolean50 }5152 newChildNode(): Node {53 return new Node({ reverse: this.reverse })
27 unmodified lines
81 node.varIndex = context.varIndex++82 }83 }84 if (name !== '') {85 paramMap.push([name, node.varIndex])85 paramMap.push([name, node.varIndex as number])86 }87 } else {88 node = this.children[token] ||= this.newChildNode()89 }
29 unmodified lines
modified:src/router/reg-exp-router/router.test.ts+35 added-35 removed
8 unmodified lines
910 it('get, post hello', async () => {11 let res = router.match('GET', '/hello')12 expect(res).not.toBeNull()13 expect(res.handlers).toEqual(['get hello'])13 expect(res?.handlers).toEqual(['get hello'])1415 res = router.match('POST', '/hello')16 expect(res).not.toBeNull()17 expect(res.handlers).toEqual(['post hello'])17 expect(res?.handlers).toEqual(['post hello'])1819 res = router.match('PUT', '/hello')20 expect(res).toBeNull()21
11 unmodified lines
33 it('Named Param', async () => {34 router.add('GET', '/entry/:id', 'get entry')35 const res = router.match('GET', '/entry/123')36 expect(res).not.toBeNull()37 expect(res.handlers).toEqual(['get entry'])38 expect(res.params['id']).toBe('123')37 expect(res?.handlers).toEqual(['get entry'])38 expect(res?.params['id']).toBe('123')39 })4041 it('Wildcard', async () => {42 router.add('GET', '/wild/*/card', 'get wildcard')43 const res = router.match('GET', '/wild/xxx/card')44 expect(res).not.toBeNull()45 expect(res.handlers).toEqual(['get wildcard'])45 expect(res?.handlers).toEqual(['get wildcard'])46 })4748 it('Default', async () => {49 router.add('GET', '/api/abc', 'get api')50 router.add('GET', '/api/*', 'fallback')51 let res = router.match('GET', '/api/abc')52 expect(res).not.toBeNull()53 expect(res.handlers).toEqual(['get api', 'fallback'])53 expect(res?.handlers).toEqual(['get api', 'fallback'])54 res = router.match('GET', '/api/def')55 expect(res).not.toBeNull()56 expect(res.handlers).toEqual(['fallback'])56 expect(res?.handlers).toEqual(['fallback'])57 })5859 it('Regexp', async () => {60 router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post')61 let res = router.match('GET', '/post/20210101/hello')62 expect(res).not.toBeNull()63 expect(res.handlers).toEqual(['get post'])64 expect(res.params['date']).toBe('20210101')65 expect(res.params['title']).toBe('hello')63 expect(res?.handlers).toEqual(['get post'])64 expect(res?.params['date']).toBe('20210101')65 expect(res?.params['title']).toBe('hello')66 res = router.match('GET', '/post/onetwothree')67 expect(res).toBeNull()68 res = router.match('GET', '/post/123/123')69 expect(res).toBeNull()
6 unmodified lines
76 router.add('GET', '/api/*', 'fallback')7778 let res = router.match('GET', '/api')79 expect(res).not.toBeNull()80 expect(res.handlers).toEqual(['auth middleware', 'top', 'fallback'])80 expect(res?.handlers).toEqual(['auth middleware', 'top', 'fallback'])8182 res = router.match('GET', '/api/posts')83 expect(res).not.toBeNull()84 expect(res.handlers).toEqual(['auth middleware', 'posts', 'fallback'])84 expect(res?.handlers).toEqual(['auth middleware', 'posts', 'fallback'])85 })86})8788describe('Registration order', () => {
6 unmodified lines
95 router.add('GET', '/:type/:action', 'foo')96 router.add('GET', '/posts/:id', 'bar')97 const res = router.match('GET', '/posts/123')98 expect(res).not.toBeNull()99 expect(res.handlers).toEqual(['foo', 'bar'])99 expect(res?.handlers).toEqual(['foo', 'bar'])100 })101102 it('concrete -> abstract', async () => {103 router.add('GET', '/posts/:id', 'bar')104 router.add('GET', '/:type/:action', 'foo')105 const res = router.match('GET', '/posts/123')106 expect(res).not.toBeNull()107 expect(res.handlers).toEqual(['bar', 'foo'])107 expect(res?.handlers).toEqual(['bar', 'foo'])108 })109})110111describe('Optimization for METHOD_NAME_OF_ALL', () => {
5 unmodified lines
117 it('Apply to all requests', async () => {118 router.add(METHOD_NAME_ALL, '*', 'OK')119 const res = router.match('GET', '/entry/123')120 expect(res).not.toBeNull()121 expect(res.handlers).toEqual(['OK'])122 expect(res.params).toMatchObject({})121 expect(res?.handlers).toEqual(['OK'])122 expect(res?.params).toMatchObject({})123 })124125 it('Apply to all requests under a specific path', async () => {126 router.add(METHOD_NAME_ALL, '/path/to/*', 'OK')
1 unmodified line
128 expect(res).toBeNull()129130 res = router.match('GET', '/path/to/entry/123')131 expect(res).not.toBeNull()132 expect(res.handlers).toEqual(['OK'])133 expect(res.params).toMatchObject({})132 expect(res?.handlers).toEqual(['OK'])133 expect(res?.params).toMatchObject({})134 })135})136137describe('Multi match', () => {
9 unmodified lines
147 router.add('GET', '/entry/:id/comment/:comment_id', 'get comment')148 it('GET /', async () => {149 const res = router.match('GET', '/')150 expect(res).not.toBeNull()151 expect(res.handlers).toEqual(['middleware a', 'middleware b'])151 expect(res?.handlers).toEqual(['middleware a', 'middleware b'])152 })153 it('GET /entry/123', async () => {154 const res = router.match('GET', '/entry/123')155 expect(res).not.toBeNull()156 expect(res.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])157 expect(res.params['id']).toBe('123')156 expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])157 expect(res?.params['id']).toBe('123')158 })159 it('GET /entry/123/comment/456', async () => {160 const res = router.match('GET', '/entry/123/comment/456')161 expect(res).not.toBeNull()162 expect(res.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])163 expect(res.params['id']).toBe('123')164 expect(res.params['comment_id']).toBe('456')162 expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])163 expect(res?.params['id']).toBe('123')164 expect(res?.params['comment_id']).toBe('456')165 })166 it('POST /entry', async () => {167 const res = router.match('POST', '/entry')168 expect(res).not.toBeNull()169 expect(res.handlers).toEqual(['middleware a', 'middleware c', 'post entry'])169 expect(res?.handlers).toEqual(['middleware a', 'middleware c', 'post entry'])170 })171 it('DELETE /entry', async () => {172 const res = router.match('DELETE', '/entry')173 expect(res).not.toBeNull()174 expect(res.handlers).toEqual(['middleware a'])174 expect(res?.handlers).toEqual(['middleware a'])175 })176 })177178 describe('Ambiguous', () => {
3 unmodified lines
182 router.add('GET', '/entry/:name', 'get entry')183 it('GET /entry/entry', async () => {184 const res = router.match('GET', '/entry/entries')185 expect(res).not.toBeNull()186 expect(res.handlers).toEqual(['get user entries', 'get entry'])187 expect(res.params['user']).toBe('entry')188 expect(res.params['name']).toBe('entries')186 expect(res?.handlers).toEqual(['get user entries', 'get entry'])187 expect(res?.params['user']).toBe('entry')188 expect(res?.params['name']).toBe('entries')189 })190 })191192 describe('Multiple handlers', () => {
6 unmodified lines
199200 it('GET /entry/123', async () => {201 const res = router.match('GET', '/entry/123')202 expect(res).not.toBeNull()203 expect(res.handlers).toEqual([':type', ':class', ':model', 'entry'])204 expect(res.params['type']).toBe('entry')205 expect(res.params['class']).toBe('entry')206 expect(res.params['model']).toBe('entry')203 expect(res?.handlers).toEqual([':type', ':class', ':model', 'entry'])204 expect(res?.params['type']).toBe('entry')205 expect(res?.params['class']).toBe('entry')206 expect(res?.params['model']).toBe('entry')207 })208 })209})210
56 unmodified lines
267268 it('top', async () => {269 const res = router.match('GET', '/')270 expect(res).not.toBeNull()271 expect(res.handlers).toEqual(['/', '/*', '*'])271 expect(res?.handlers).toEqual(['/', '/*', '*'])272 })273274 it('Under a certain path', async () => {275 const res = router.match('GET', '/x')276 expect(res).not.toBeNull()277 expect(res.handlers).toEqual(['/*', '*', '/x', '/x/*'])277 expect(res?.handlers).toEqual(['/*', '*', '/x', '/x/*'])278 })279})
modified:src/router/reg-exp-router/router.ts+4 added
1/* eslint-disable @typescript-eslint/ban-ts-comment */2import type { Router, Result } from '../../router'3import { METHOD_NAME_ALL } from '../../router'4import type { ParamMap } from './trie'5import { Trie } from './trie'
324 unmodified lines
330 Record<string, AnyMatcher<T>>,331 Record<string, AnyMatcher<T>[]>,332 boolean333 ] {334 // @ts-ignore335 this.routeData.routes.sort(({ hint: a }, { hint: b }) => {336 if (a.componentsLength !== b.componentsLength) {337 return a.componentsLength - b.componentsLength338 }
20 unmodified lines
359360 const primaryMatchers: Record<string, AnyMatcher<T>> = {}361 const secondaryMatchers: Record<string, AnyMatcher<T>[]> = {}362 let hasAmbiguous = false363 // @ts-ignore364 this.routeData.methods.forEach((method) => {365 let _hasAmbiguous366 ;[primaryMatchers[method], secondaryMatchers[method], _hasAmbiguous] =367 this.buildMatcher(method)
9 unmodified lines
377378 private buildMatcher(method: string): [AnyMatcher<T>, AnyMatcher<T>[], boolean] {379 let hasAmbiguous = false380 const targetMethods = new Set([method, METHOD_NAME_ALL])381 // @ts-ignore382 const routes = this.routeData.routes.filter(({ method }) => targetMethods.has(method))383384 // Reset temporary data per method385 for (let i = 0, len = routes.length; i < len; i++) {
81 unmodified lines
modified:src/router/reg-exp-router/trie.ts+2 added
23 unmodified lines
24 * - /* wildcard25 * - character26 */27 const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g)28 // eslint-disable-next-line @typescript-eslint/ban-ts-comment29 // @ts-ignore30 this.root.insert(tokens, index, paramMap, this.context)3132 return paramMap33 }
24 unmodified lines
modified:src/router/trie-router/node.test.ts+58 added-58 removed
4 unmodified lines
5 node.insert('get', '/', 'get root')6 it('get /', () => {7 const res = node.search('get', '/')8 expect(res).not.toBeNull()9 expect(res.handlers).toEqual(['get root'])9 expect(res?.handlers).toEqual(['get root'])10 expect(node.search('get', '/hello')).toBeNull()11 })12})13
23 unmodified lines
37 it('get, post /hello', () => {38 expect(node.search('get', '/')).toBeNull()39 expect(node.search('post', '/')).toBeNull()4041 expect(node.search('get', '/hello').handlers).toEqual(['get hello'])42 expect(node.search('post', '/hello').handlers).toEqual(['post hello'])41 expect(node.search('get', '/hello')?.handlers).toEqual(['get hello'])42 expect(node.search('post', '/hello')?.handlers).toEqual(['post hello'])43 expect(node.search('put', '/hello')).toBeNull()44 })45 it('get /nothing', () => {46 expect(node.search('get', '/nothing')).toBeNull()47 })48 it('/hello/foo, /hello/bar', () => {49 expect(node.search('get', '/hello/foo').handlers).toEqual(['get hello foo'])49 expect(node.search('get', '/hello/foo')?.handlers).toEqual(['get hello foo'])50 expect(node.search('post', '/hello/foo')).toBeNull()51 expect(node.search('get', '/hello/bar')).toBeNull()52 })53 it('/hello/foo/bar', () => {
9 unmodified lines
6364 it('get /entry/123', () => {65 const res = node.search('get', '/entry/123')66 expect(res).not.toBeNull()67 expect(res.handlers).toEqual(['get entry'])68 expect(res.params).not.toBeNull()69 expect(res.params['id']).toBe('123')70 expect(res.params['id']).not.toBe('1234')67 expect(res?.handlers).toEqual(['get entry'])68 expect(res?.params).not.toBeNull()69 expect(res?.params['id']).toBe('123')70 expect(res?.params['id']).not.toBe('1234')71 })7273 it('get /entry/456/comment', () => {74 const res = node.search('get', '/entry/456/comment')
2 unmodified lines
7778 it('get /entry/789/comment/123', () => {79 const res = node.search('get', '/entry/789/comment/123')80 expect(res).not.toBeNull()81 expect(res.handlers).toEqual(['get comment'])82 expect(res.params['id']).toBe('789')83 expect(res.params['comment_id']).toBe('123')81 expect(res?.handlers).toEqual(['get comment'])82 expect(res?.params['id']).toBe('789')83 expect(res?.params['comment_id']).toBe('123')84 })8586 it('get /map/:location/events', () => {87 const res = node.search('get', '/map/yokohama/events')88 expect(res).not.toBeNull()89 expect(res.handlers).toEqual(['get events'])90 expect(res.params['location']).toBe('yokohama')89 expect(res?.handlers).toEqual(['get events'])90 expect(res?.params['location']).toBe('yokohama')91 })92})9394describe('Name path - Multiple route', () => {
4 unmodified lines
99100 it('get /posts/123', () => {101 const res = node.search('get', '/posts/123')102 expect(res).not.toBeNull()103 expect(res.handlers).toEqual(['common', 'specialized'])104 expect(res.params['id']).toBe('123')103 expect(res?.handlers).toEqual(['common', 'specialized'])104 expect(res?.params['id']).toBe('123')105 })106})107108describe('Wildcard', () => {
1 unmodified line
110 node.insert('get', '/wildcard-abc/*/wildcard-efg', 'wildcard')111 it('/wildcard-abc/xxxxxx/wildcard-efg', () => {112 const res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg')113 expect(res).not.toBeNull()114 expect(res.handlers).toEqual(['wildcard'])114 expect(res?.handlers).toEqual(['wildcard'])115 })116 node.insert('get', '/wildcard-abc/*/wildcard-efg/hijk', 'wildcard')117 it('/wildcard-abc/xxxxxx/wildcard-efg/hijk', () => {118 const res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg/hijk')119 expect(res).not.toBeNull()120 expect(res.handlers).toEqual(['wildcard'])120 expect(res?.handlers).toEqual(['wildcard'])121 })122})123124describe('Regexp', () => {
1 unmodified line
126 node.insert('get', '/regex-abc/:id{[0-9]+}/comment/:comment_id{[a-z]+}', 'regexp')127 it('/regexp-abc/123/comment/abc', () => {128 const res = node.search('get', '/regex-abc/123/comment/abc')129 expect(res).not.toBeNull()130 expect(res.handlers).toEqual(['regexp'])131 expect(res.params['id']).toBe('123')132 expect(res.params['comment_id']).toBe('abc')130 expect(res?.handlers).toEqual(['regexp'])131 expect(res?.params['id']).toBe('123')132 expect(res?.params['comment_id']).toBe('abc')133 })134 it('/regexp-abc/abc', () => {135 const res = node.search('get', '/regex-abc/abc')136 expect(res).toBeNull()
9 unmodified lines
146 node.insert('ALL', '/all-methods', 'all methods') // ALL147 it('/all-methods', () => {148 let res = node.search('get', '/all-methods')149 expect(res).not.toBeNull()150 expect(res.handlers).toEqual(['all methods'])150 expect(res?.handlers).toEqual(['all methods'])151 res = node.search('put', '/all-methods')152 expect(res).not.toBeNull()153 expect(res.handlers).toEqual(['all methods'])153 expect(res?.handlers).toEqual(['all methods'])154 })155})156157describe('Special Wildcard', () => {
2 unmodified lines
160161 it('/foo', () => {162 const res = node.search('get', '/foo')163 expect(res).not.toBeNull()164 expect(res.handlers).toEqual(['match all'])164 expect(res?.handlers).toEqual(['match all'])165 })166 it('/hello', () => {167 const res = node.search('get', '/hello')168 expect(res).not.toBeNull()169 expect(res.handlers).toEqual(['match all'])169 expect(res?.handlers).toEqual(['match all'])170 })171 it('/hello/foo', () => {172 const res = node.search('get', '/hello/foo')173 expect(res).not.toBeNull()174 expect(res.handlers).toEqual(['match all'])174 expect(res?.handlers).toEqual(['match all'])175 })176})177178describe('Special Wildcard deeply', () => {
1 unmodified line
180 node.insert('ALL', '/hello/*', 'match hello')181 it('/hello', () => {182 const res = node.search('get', '/hello')183 expect(res).not.toBeNull()184 expect(res.handlers).toEqual(['match hello'])184 expect(res?.handlers).toEqual(['match hello'])185 })186 it('/hello/foo', () => {187 const res = node.search('get', '/hello/foo')188 expect(res).not.toBeNull()189 expect(res.handlers).toEqual(['match hello'])189 expect(res?.handlers).toEqual(['match hello'])190 })191})192193describe('Default with wildcard', () => {
2 unmodified lines
196 node.insert('ALL', '/api/abc', 'match api')197 it('/api/abc', () => {198 const res = node.search('get', '/api/abc')199 expect(res).not.toBeNull()200 expect(res.handlers).toEqual(['fallback', 'match api'])200 expect(res?.handlers).toEqual(['fallback', 'match api'])201 })202 it('/api/def', () => {203 const res = node.search('get', '/api/def')204 expect(res).not.toBeNull()205 expect(res.handlers).toEqual(['fallback'])205 expect(res?.handlers).toEqual(['fallback'])206 })207})208209describe('Multi match', () => {
6 unmodified lines
216 node.insert('get', '/abc/*/ghi/jkl', 'GET /abc/*/ghi/jkl')217 it('get /abc/edf', () => {218 const res = node.search('get', '/abc/edf')219 expect(res).not.toBeNull()220 expect(res.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf'])220 expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf'])221 })222 it('get /abc/xxx/edf', () => {223 const res = node.search('get', '/abc/xxx/edf')224 expect(res).not.toBeNull()225 expect(res.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/*/edf'])225 expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/*/edf'])226 })227 it('get /', () => {228 const res = node.search('get', '/')229 expect(res).not.toBeNull()230 expect(res.handlers).toEqual(['GET *'])230 expect(res?.handlers).toEqual(['GET *'])231 })232 it('post /', () => {233 const res = node.search('post', '/')234 expect(res).toBeNull()235 })236 it('get /abc/edf/ghi', () => {237 const res = node.search('get', '/abc/edf/ghi')238 expect(res).not.toBeNull()239 expect(res.handlers).toEqual(['GET *', 'GET /abc/*'])239 expect(res?.handlers).toEqual(['GET *', 'GET /abc/*'])240 })241 })242243 describe('Blog', () => {
7 unmodified lines
251 node.insert('get', '/entry/:id/comment/:comment_id', 'get comment') // 4.7252 it('get /entry/123', async () => {253 const res = node.search('get', '/entry/123')254 expect(res).not.toBeNull()255 expect(res.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])256 expect(res.params['id']).toBe('123')255 expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])256 expect(res?.params['id']).toBe('123')257 })258 it('get /entry/123/comment/456', async () => {259 const res = node.search('get', '/entry/123/comment/456')260 expect(res).not.toBeNull()261 expect(res.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])262 expect(res.params['id']).toBe('123')263 expect(res.params['comment_id']).toBe('456')261 expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])262 expect(res?.params['id']).toBe('123')263 expect(res?.params['comment_id']).toBe('456')264 })265 it('post /entry', async () => {266 const res = node.search('post', '/entry')267 expect(res).not.toBeNull()268 expect(res.handlers).toEqual(['middleware b', 'middleware c', 'post entry'])268 expect(res?.handlers).toEqual(['middleware b', 'middleware c', 'post entry'])269 })270 it('delete /entry', async () => {271 const res = node.search('delete', '/entry')272 expect(res).not.toBeNull()273 expect(res.handlers).toEqual(['middleware b'])273 expect(res?.handlers).toEqual(['middleware b'])274 })275 })276277 describe('ALL', () => {
3 unmodified lines
281 node.insert('ALL', '/abc/*/def', 'ALL /abc/*/def')282 it('get /', () => {283 const res = node.search('get', '/')284 expect(res).not.toBeNull()285 expect(res.handlers).toEqual(['ALL *'])285 expect(res?.handlers).toEqual(['ALL *'])286 })287 it('post /abc', () => {288 const res = node.search('post', '/abc')289 expect(res).not.toBeNull()290 expect(res.handlers).toEqual(['ALL *', 'ALL /abc/*'])290 expect(res?.handlers).toEqual(['ALL *', 'ALL /abc/*'])291 })292 it('delete /abc/xxx/def', () => {293 const res = node.search('post', '/abc/xxx/def')294 expect(res).not.toBeNull()295 expect(res.handlers).toEqual(['ALL *', 'ALL /abc/*', 'ALL /abc/*/def'])295 expect(res?.handlers).toEqual(['ALL *', 'ALL /abc/*', 'ALL /abc/*/def'])296 })297 })298299 describe('Regexp', () => {
2 unmodified lines
302 node.insert('get', '/regex-abc/:id{[0-9]+}/def', 'regexp')303 it('/regexp-abc/123/def', () => {304 const res = node.search('get', '/regex-abc/123/def')305 expect(res).not.toBeNull()306 expect(res.handlers).toEqual(['middleware a', 'regexp'])307 expect(res.params['id']).toBe('123')306 expect(res?.handlers).toEqual(['middleware a', 'regexp'])307 expect(res?.params['id']).toBe('123')308 })309 it('/regexp-abc/123', () => {310 const res = node.search('get', '/regex-abc/123/ghi')311 expect(res).not.toBeNull()312 expect(res.handlers).toEqual(['middleware a'])312 expect(res?.handlers).toEqual(['middleware a'])313 })314 })315316 describe('Trailing slash', () => {
16 unmodified lines
333 node.insert('get', '/hey', 'Middleware B')334 it('get /hey', () => {335 const res = node.search('get', '/hey')336 expect(res).not.toBeNull()337 expect(res.handlers).toEqual(['Middleware A', 'Middleware B'])337 expect(res?.handlers).toEqual(['Middleware A', 'Middleware B'])338 })339 })340})341
47 unmodified lines
389390 it('get /page', () => {391 const res = node.search('get', '/page')392 expect(res).not.toBeNull()393 expect(res.handlers).toEqual(['a', '/page', '/:slug'])393 expect(res?.handlers).toEqual(['a', '/page', '/:slug'])394 })395 })396397 describe('With Named path', () => {
4 unmodified lines
402403 it('get /posts/123', () => {404 const res = node.search('get', '/posts/123')405 expect(res).not.toBeNull()406 expect(res.handlers).toEqual(['a', '/posts/:id', '/:type/:id'])406 expect(res?.handlers).toEqual(['a', '/posts/:id', '/:type/:id'])407 })408 })409410 describe('With Wildcards', () => {
5 unmodified lines
416417 it('get /api/posts/123', () => {418 const res = node.search('get', '/api/posts/123')419 expect(res).not.toBeNull()420 expect(res.handlers).toEqual(['1st', '2nd', '4th', '3rd'])420 expect(res?.handlers).toEqual(['1st', '2nd', '4th', '3rd'])421 })422 })423424 describe('With special Wildcard', () => {
5 unmodified lines
430 it('get /posts', () => {431 const res = node.search('get', '/posts')432433 expect(res).not.toBeNull()434 expect(res.handlers).toEqual(['/posts', '/posts/*'])434 expect(res?.handlers).toEqual(['/posts', '/posts/*'])435 })436 })437438 describe('Complex', () => {
12 unmodified lines
451 it('get /api/posts/123', () => {452 const res = node.search('get', '/api/posts/123')453 // ---> will match => c, d, e, e, f, g, a, b454 // ---> sort by score => a, b, c, d, e, f, g455 expect(res.handlers).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'g'])455 expect(res?.handlers).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'g'])456 })457 })458459 describe('Multi match', () => {
4 unmodified lines
464 node.insert('get', '/abc/*/ghi/jkl', 'GET /abc/*/ghi/jkl') // 4.4465 it('get /abc/edf', () => {466 const res = node.search('get', '/abc/edf')467 expect(res).not.toBeNull()468 expect(res.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf'])468 expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf'])469 })470 })471472 describe('Multi match', () => {
5 unmodified lines
478479 it('get /api/entry', async () => {480 const res = node.search('get', '/api/entry')481 expect(res).not.toBeNull()482 expect(res.handlers).toEqual(['a', 'entry', 'b'])482 expect(res?.handlers).toEqual(['a', 'entry', 'b'])483 })484 })485486 describe('fallback', () => {
4 unmodified lines
491 node.insert('get', '/entry/:id', 'get entry') // 2.3492 it('post /entry', async () => {493 const res = node.search('post', '/entry')494 expect(res).not.toBeNull()495 expect(res.handlers).toEqual(['post entry', 'fallback'])495 expect(res?.handlers).toEqual(['post entry', 'fallback'])496 })497 })498 })499 describe('page', () => {
2 unmodified lines
502 node.insert('ALL', '/*', 'fallback') // 1.2503 it('get /page', async () => {504 const res = node.search('get', '/page')505 expect(res).not.toBeNull()506 expect(res.handlers).toEqual(['page', 'fallback'])506 expect(res?.handlers).toEqual(['page', 'fallback'])507 })508 })509})510
8 unmodified lines
519520 it('top', async () => {521 const res = node.search('get', '/')522 expect(res).not.toBeNull()523 expect(res.handlers).toEqual(['/', '/*', '*']) // => failed ['*', '/*', '/']523 expect(res?.handlers).toEqual(['/', '/*', '*']) // => failed ['*', '/*', '/']524 })525526 it('Under a certain path', async () => {527 const res = node.search('get', '/x')528 expect(res).not.toBeNull()529 expect(res.handlers).toEqual(['/*', '*', '/x', '/x/*'])529 expect(res?.handlers).toEqual(['/*', '*', '/x', '/x/*'])530 })531})
modified:src/router/trie-router/node.ts+1 added-1 removed
189 unmodified lines
190 }191 return next192 }193194 search(method: string, path: string): Result<T> {194 search(method: string, path: string): Result<T> | null {195 const handlerSets: HandlerSet<T>[] = []196 let params: Record<string, string> = {}197198 // eslint-disable-next-line @typescript-eslint/no-this-alias
35 unmodified lines
modified:src/router/trie-router/router.test.ts+20 added-20 removed
7 unmodified lines
89 it('get, post hello', async () => {10 let res = router.match('GET', '/hello')11 expect(res).not.toBeNull()12 expect(res.handlers).toEqual(['get hello'])12 expect(res?.handlers).toEqual(['get hello'])1314 res = router.match('POST', '/hello')15 expect(res).not.toBeNull()16 expect(res.handlers).toEqual(['post hello'])16 expect(res?.handlers).toEqual(['post hello'])1718 res = router.match('PUT', '/hello')19 expect(res).toBeNull()20
8 unmodified lines
29 it('Named Param', async () => {30 router.add('GET', '/entry/:id', 'get entry')31 const res = router.match('GET', '/entry/123')32 expect(res).not.toBeNull()33 expect(res.handlers).toEqual(['get entry'])34 expect(res.params['id']).toBe('123')33 expect(res?.handlers).toEqual(['get entry'])34 expect(res?.params['id']).toBe('123')35 })3637 it('Wildcard', async () => {38 router.add('GET', '/wild/*/card', 'get wildcard')39 const res = router.match('GET', '/wild/xxx/card')40 expect(res).not.toBeNull()41 expect(res.handlers).toEqual(['get wildcard'])41 expect(res?.handlers).toEqual(['get wildcard'])42 })4344 it('Default', async () => {45 router.add('GET', '/api/*', 'fallback')46 router.add('GET', '/api/abc', 'get api')47 let res = router.match('GET', '/api/abc')48 expect(res).not.toBeNull()49 expect(res.handlers).toEqual(['fallback', 'get api'])49 expect(res?.handlers).toEqual(['fallback', 'get api'])50 res = router.match('GET', '/api/def')51 expect(res).not.toBeNull()52 expect(res.handlers).toEqual(['fallback'])52 expect(res?.handlers).toEqual(['fallback'])53 })5455 it('Regexp', async () => {56 router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post')57 let res = router.match('GET', '/post/20210101/hello')58 expect(res).not.toBeNull()59 expect(res.handlers).toEqual(['get post'])60 expect(res.params['date']).toBe('20210101')61 expect(res.params['title']).toBe('hello')59 expect(res?.handlers).toEqual(['get post'])60 expect(res?.params['date']).toBe('20210101')61 expect(res?.params['title']).toBe('hello')62 res = router.match('GET', '/post/onetwothree')63 expect(res).toBeNull()64 res = router.match('GET', '/post/123/123')65 expect(res).toBeNull()
13 unmodified lines
79 router.add('GET', '/entry/:id/comment/:comment_id', 'get comment')80 it('GET /', async () => {81 const res = router.match('GET', '/')82 expect(res).not.toBeNull()83 expect(res.handlers).toEqual(['middleware a', 'middleware b'])83 expect(res?.handlers).toEqual(['middleware a', 'middleware b'])84 })85 it('GET /entry/123', async () => {86 const res = router.match('GET', '/entry/123')87 expect(res).not.toBeNull()88 expect(res.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])89 expect(res.params['id']).toBe('123')88 expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])89 expect(res?.params['id']).toBe('123')90 })91 it('GET /entry/123/comment/456', async () => {92 const res = router.match('GET', '/entry/123/comment/456')93 expect(res).not.toBeNull()94 expect(res.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])95 expect(res.params['id']).toBe('123')96 expect(res.params['comment_id']).toBe('456')94 expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])95 expect(res?.params['id']).toBe('123')96 expect(res?.params['comment_id']).toBe('456')97 })98 it('POST /entry', async () => {99 const res = router.match('POST', '/entry')100 expect(res).not.toBeNull()101 expect(res.handlers).toEqual(['middleware a', 'middleware c', 'post entry'])101 expect(res?.handlers).toEqual(['middleware a', 'middleware c', 'post entry'])102 })103 it('DELETE /entry', async () => {104 const res = router.match('DELETE', '/entry')105 expect(res).not.toBeNull()106 expect(res.handlers).toEqual(['middleware a'])106 expect(res?.handlers).toEqual(['middleware a'])107 })108 })109})110
4 unmodified lines
115 router.add('GET', '/entry/:id', 'get entry')116 it('POST /entry', async () => {117 const res = router.match('POST', '/entry')118 expect(res).not.toBeNull()119 expect(res.handlers).toEqual(['post entry', 'fallback'])119 expect(res?.handlers).toEqual(['post entry', 'fallback'])120 })121})122123describe('page', () => {
1 unmodified line
125 router.add('GET', '/page', 'page')126 router.add('ALL', '*', 'fallback') // or '*'127 it('GET /page', async () => {128 const res = router.match('GET', '/page')129 expect(res.handlers).toEqual(['page', 'fallback'])129 expect(res?.handlers).toEqual(['page', 'fallback'])130 })131})
modified:src/router/trie-router/router.ts+1 added-1 removed
10 unmodified lines
11 add(method: string, path: string, handler: T) {12 this.node.insert(method, path, handler)13 }1415 match(method: string, path: string): Result<T> {15 match(method: string, path: string): Result<T> | null {16 return this.node.search(method, path)17 }18}
modified:src/utils/jwt/jwt.test.ts+4 added
1/* eslint-disable @typescript-eslint/ban-ts-comment */2import * as JWT from './jwt'3import {4 AlgorithmTypes,5 JwtTokenSignatureMismatched,
15 unmodified lines
21 } catch (e) {22 err = e as JwtAlorithmNotImplemented23 }24 expect(tok).toBe('')25 // @ts-ignore26 expect(err).toEqual(new JwtAlorithmNotImplemented(alg))27 })2829 it('JwtTokenInvalid', async () => {
5 unmodified lines
35 authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)36 } catch (e) {37 err = e as JwtTokenInvalid38 }39 // @ts-ignore40 expect(err).toEqual(new JwtTokenInvalid(tok))41 expect(authorized).toBe(false)42 })43
7 unmodified lines
51 authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)52 } catch (e) {53 err = e as JwtTokenNotBefore54 }55 // @ts-ignore56 expect(err).toEqual(new JwtTokenNotBefore(tok))57 expect(authorized).toBe(false)58 })59
114 unmodified lines
modified:src/utils/jwt/types.test.ts+2 added
3 unmodified lines
4 it('AlgorithmTypes', () => {5 expect('HS256' as AlgorithmTypes).toBe(AlgorithmTypes.HS256)6 expect('HS384' as AlgorithmTypes).toBe(AlgorithmTypes.HS384)7 expect('HS512' as AlgorithmTypes).toBe(AlgorithmTypes.HS512)8 // eslint-disable-next-line @typescript-eslint/ban-ts-comment9 // @ts-ignore10 expect(undefined as AlgorithmTypes).toBe(undefined)11 expect('' as AlgorithmTypes).toBe('')12 })13})
modified:src/utils/body.ts+2 added
15 unmodified lines
16 return acc17 }, form)18 return data19 }2021 return r.arrayBuffer()22}
modified:src/utils/buffer.test.ts+4 added
9 unmodified lines
10 )11 ).toBe(true)12 expect(await timingSafeEqual('a', 'a')).toBe(true)13 expect(await timingSafeEqual('', '')).toBe(true)14 // eslint-disable-next-line @typescript-eslint/ban-ts-comment15 // @ts-ignore16 expect(await timingSafeEqual(undefined, undefined)).toBe(true)17 expect(await timingSafeEqual(true, true)).toBe(true)18 expect(await timingSafeEqual(false, false)).toBe(true)19 expect(await timingSafeEqual(true, true, (d: string) => sha256CryptoJS(d).toString()))
8 unmodified lines
28 await timingSafeEqual('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'a')29 ).toBe(false)30 expect(await timingSafeEqual('alpha', 'beta')).toBe(false)31 expect(await timingSafeEqual(false, true)).toBe(false)32 // eslint-disable-next-line @typescript-eslint/ban-ts-comment33 // @ts-ignore34 expect(await timingSafeEqual(false, undefined)).toBe(false)35 expect(36 await timingSafeEqual(37 () => {},
18 unmodified lines
modified:src/utils/cloudflare.ts+2 added-2 removed
7 unmodified lines
89export const getContentFromKVAsset = async (10 path: string,11 options?: KVAssetOptions12): Promise<ArrayBuffer> => {12): Promise<ArrayBuffer | null> => {13 let ASSET_MANIFEST: Record<string, string> = {}1415 if (options && options.manifest) {16 if (typeof options.manifest === 'string') {
17 unmodified lines
34 }3536 const key = ASSET_MANIFEST[path] || path37 if (!key) {38 return38 return null39 }4041 let content = await ASSET_NAMESPACE.get(key, { type: 'arrayBuffer' })42
37 unmodified lines
modified:src/utils/crypto.ts+2 added-1 removed
15 unmodified lines
16 const hash = await createHash(data, algorithm)17 return hash18}1920export const createHash = async (data: Data, algorithm: Algorithm): Promise<string> => {20export const createHash = async (data: Data, algorithm: Algorithm): Promise<string | null> => {21 if (crypto && crypto.subtle) {22 const buffer = await crypto.subtle.digest(23 {24 name: algorithm.name,
4 unmodified lines
29 .call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2))30 .join('')31 return hash32 }33 return null34}
modified:src/utils/encode.test.ts+5 added
1/* eslint-disable @typescript-eslint/ban-ts-comment */2import {3 utf8ToUint8Array,4 decodeBase64,5 encodeBase64,
8 unmodified lines
14 expect(encodeBase64('炎')).toBe('54KO')15 expect(encodeBase64('abcdef')).not.toBe('abcdedf')16 expect(encodeBase64('')).toBe('')17 expect(() => {18 // @ts-ignore19 encodeBase64(null)20 }).toThrow(TypeError)21 })22
2 unmodified lines
25 expect(decodeBase64('54KO')).toBe('炎')26 expect(decodeBase64('abcdedf')).not.toBe('abcdef')27 expect(decodeBase64('')).toBe('')28 expect(() => {29 // @ts-ignore30 decodeBase64(null)31 }).toThrowError(TypeError)32 })33 })
6 unmodified lines
40 expect(encodeBase64URL('炎')).toBe('54KO')41 expect(encodeBase64URL('abcdef')).not.toBe('abcdedf')42 expect(encodeBase64URL('')).toBe('')43 expect(() => {44 // @ts-ignore45 encodeBase64URL(null)46 }).toThrow(TypeError)47 })48
5 unmodified lines
54 expect(decodeBase64URL('54KO')).toBe('炎')55 expect(decodeBase64URL('abcdedf')).not.toBe('abcdef')56 expect(decodeBase64URL('')).toBe('')57 expect(() => {58 // @ts-ignore59 decodeBase64URL(null)60 }).toThrowError(TypeError)61 })62 })
9 unmodified lines
modified:src/utils/encode.ts+2 added
65 unmodified lines
6667 try {68 return Buffer.from(String.fromCharCode(...new Uint8Array(buf))).toString('base64')69 } catch (e) {}7071 return ''72}7374export const arrayBufferToBase64URL = async (buf: ArrayBuffer) => {75 return (await arrayBufferToBase64(buf)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
1 unmodified line
modified:src/utils/mime.ts+1 added-1 removed
1export const getMimeType = (filename: string): string => {1export const getMimeType = (filename: string): string | undefined => {2 const regexp = /\.([a-zA-Z0-9]+?)$/3 const match = filename.match(regexp)4 if (!match) return5 let mimeType = mimes[match[1]]
83 unmodified lines
modified:src/utils/url.test.ts+6 added-6 removed
19 unmodified lines
2021 it('getPattern', () => {22 let res = getPattern(':id')23 expect(res).not.toBeNull()24 expect(res[0]).toBe(':id')25 expect(res[1]).toBe('id')26 expect(res[2]).toBe(true)24 expect(res?.[0]).toBe(':id')25 expect(res?.[1]).toBe('id')26 expect(res?.[2]).toBe(true)27 res = getPattern(':id{[0-9]+}')28 expect(res[0]).toBe(':id{[0-9]+}')29 expect(res[1]).toBe('id')30 expect(res[2]).toEqual(/^[0-9]+$/)28 expect(res?.[0]).toBe(':id{[0-9]+}')29 expect(res?.[1]).toBe('id')30 expect(res?.[2]).toEqual(/^[0-9]+$/)31 res = getPattern('*')32 expect(res).toBe('*')33 })34
72 unmodified lines
modified:src/compose.test.ts+34 added-41 removed
59 unmodified lines
6061 const req = new Request('http://localhost/')62 const c: Context = new Context(req)6364 const onError = (error: Error, c: Context) => {65 return c.text('onError', 500)66 }6764 const mHandlerFoo = async (c: Context, next: Function) => {65 c.req.headers.append('x-header-foo', 'foo')66 await next()67 }
12 unmodified lines
80 middleware.push(mHandlerBar)81 middleware.push(handler)8283 it('Should return 200 Response', async () => {88 const composed = compose<Context>(middleware, onError)84 const composed = compose<Context>(middleware)85 const context = await composed(c)86 const res = context.res87 expect(res).not.toBeNull()88 expect(res.status).toBe(200)
6 unmodified lines
95 const middleware: Function[] = []9697 const req = new Request('http://localhost/')98 const c: Context = new Context(req)103 const onError = (error: Error, c: Context) => {104 return c.text('onError', 500)105 }99 const handler = (c: Context) => {100 return c.text('Hello')101 }109 const mHandler = async (c: Context, next: Function) => {102 const mHandler = async (_c: Context, next: Function) => {103 await next()104 }105106 middleware.push(handler)107 middleware.push(mHandler)108109 it('Should return 200 Response', async () => {117 const composed = compose<Context>(middleware, onError)110 const composed = compose<Context>(middleware)111 const context = await composed(c)112 expect(context.res).not.toBeNull()113 expect(context.res.status).toBe(200)121 expect(await context.res.text()).toBe('Hello')114 expect(await context.res!.text()).toBe('Hello')115 })116})117118describe('compose with Context - 404 not found', () => {119 const middleware: Function[] = []120121 const req = new Request('http://localhost/')122 const c: Context = new Context(req)130 const onError = (error: Error, c: Context) => {123 const onError = (_error: Error, c: Context) => {124 return c.text('onError', 500)125 }126 const onNotFound = (c: Context) => {127 return c.text('onNotFound', 404)128 }136 const mHandler = async (c: Context, next: Function) => {129 const mHandler = async (_c: Context, next: Function) => {130 await next()131 }132133 middleware.push(mHandler)
11 unmodified lines
145 const middleware: Function[] = []146147 const req = new Request('http://localhost/')148 const c: Context = new Context(req)156 const onError = (error: Error, c: Context) => {149 const onError = (_error: Error, c: Context) => {150 return c.text('onError', 500)151 }159 const handler = (c: Context, next: Function) => {152 const handler = (c: Context, _next: Function) => {153 return c.text('Hello')154 }155 const mHandler = async (c: Context, next: Function) => {156 await next()
16 unmodified lines
173 const middleware: Function[] = []174175 const req = new Request('http://localhost/')176 const c: Context = new Context(req)184 const onError = (error: Error, c: Context) => {177 const onError = (_error: Error, c: Context) => {178 return c.text('onError', 500)179 }180 const handler = (c: Context) => {181 const message = c.req.header('x-custom') || 'blank'
20 unmodified lines
202 const middleware: Function[] = []203204 const req = new Request('http://localhost/')205 const c: Context = new Context(req)213 const onError = (error: Error, c: Context) => {206 const onError = (_error: Error, c: Context) => {207 return c.text('onError', 500)208 }209210 it('Error on handler', async () => {211 const handler = () => {212 throw new Error()213 }214222 const mHandler = async (c: Context, next: Function) => {215 const mHandler = async (_c: Context, next: Function) => {216 await next()217 }218219 middleware.push(mHandler)
28 unmodified lines
248 it('Run all the middlewares', async () => {249 const ctx: C = { req: {}, res: {} }250 const stack: number[] = []251 const middlewares = [259 async (ctx: C, next: Function) => {252 async (_ctx: C, next: Function) => {253 stack.push(0)254 await next()255 },263 async (ctx: C, next: Function) => {256 async (_ctx: C, next: Function) => {257 stack.push(1)258 await next()259 },267 async (ctx: C, next: Function) => {260 async (_ctx: C, next: Function) => {261 stack.push(2)262 await next()263 },264 ]272 const composed = await compose(middlewares)265 const composed = compose(middlewares)266 await composed(ctx)267 expect(stack).toEqual([0, 1, 2])268 })269})
7 unmodified lines
277 const arr: number[] = []278 const stack = []279 const called: boolean[] = []280288 stack.push(async (context: C, next: Function) => {281 stack.push(async (_context: C, next: Function) => {282 called.push(true)283284 arr.push(1)285 await next()286 arr.push(6)287 })288296 stack.push(async (context: C, next: Function) => {289 stack.push(async (_context: C, next: Function) => {290 called.push(true)291292 arr.push(2)293 await next()294 arr.push(5)295 })296304 stack.push(async (context: C, next: Function) => {297 stack.push(async (_context: C, next: Function) => {298 called.push(true)299300 arr.push(3)301 await next()
9 unmodified lines
311 const arr: number[] = []312 const stack = []313 const called: boolean[] = []314322 stack.push(async (context: C, next: Function) => {315 stack.push(async (_context: C, next: Function) => {316 called.push(true)317318 arr.push(1)319 await next()320 arr.push(6)321 })322330 stack.push(async (context: C, next: Function) => {323 stack.push(async () => {324 called.push(true)325 arr.push(2)326 })327335 stack.push(async (context: C, next: Function) => {328 stack.push(async (_context: C, next: Function) => {329 called.push(true)330331 arr.push(3)332 await next()
47 unmodified lines
380 it('should create next functions that return a Promise', function () {381 const stack: any[] = []382 const arr: any[] = []383 for (let i = 0; i < 5; i++) {391 stack.push((context: C, next: Function) => {384 stack.push((_context: C, next: Function) => {385 arr.push(next())386 })387 }388
11 unmodified lines
400 it('should work when yielding at the end of the stack', async () => {401 const stack = []402 let called = false403411 stack.push(async (ctx: C, next: Function) => {404 stack.push(async (_ctx: C, next: Function) => {405 await next()406 called = true407 })408
44 unmodified lines
453 it('should catch downstream errors', async () => {454 const arr: any[] = []455 const stack = []456464 stack.push(async (ctx: C, next: Function) => {457 stack.push(async (_ctx: C, next: Function) => {458 arr.push(1)459 try {460 arr.push(6)461 await next()
3 unmodified lines
465 }466 arr.push(3)467 })468476 stack.push(async (ctx: C, next: Function) => {469 stack.push(async () => {470 arr.push(4)471 throw new Error()472 })473
33 unmodified lines
507 const called: number[] = []508509 return compose([510 compose([518 (ctx: C, next: Function) => {511 (_ctx: C, next: Function) => {512 called.push(1)513 return next()514 },522 (ctx: C, next: Function) => {515 (_ctx: C, next: Function) => {516 called.push(2)517 return next()518 },519 ]),527 (ctx: C, next: Function) => {520 (_ctx: C, next: Function) => {521 called.push(3)522 return next()523 },524 ])({}).then(() => expect(called).toEqual([1, 2, 3]))525 })526527 it('should throw if next() is called multiple times', () => {528 return compose([536 async (ctx: C, next: Function) => {529 async (_ctx: C, next: Function) => {530 await next()531 await next()532 },533 ])({}).then(
9 unmodified lines
543 it('should return a valid middleware', () => {544 let val = 0545 return compose([546 compose([554 (ctx: C, next: Function) => {547 (_ctx: C, next: Function) => {548 val++549 return next()550 },558 (ctx: C, next: Function) => {551 (_ctx: C, next: Function) => {552 val++553 return next()554 },555 ]),563 (ctx: C, next: Function) => {556 (_ctx: C, next: Function) => {557 val++558 return next()559 },560 ])({}).then(function () {
24 unmodified lines
585 })586587 it('should not affect the original middleware array', () => {588 const middleware = []596 const fn1 = (ctx: C, next: Function) => {589 const fn1 = (_ctx: C, next: Function) => {590 return next()591 }592 middleware.push(fn1)593
7 unmodified lines
601 expect(fn).toEqual(fn1)602 }603 })604612 it('should not get stuck on the passed in next', () => {605 it('should not get stuck on the passed in next', async () => {606 type C = {607 middleware: number608 next: number609 }
20 unmodified lines
modified:src/compose.ts+7 added-7 removed
14 unmodified lines
15 return Promise.reject(new Error('next() called multiple times'))16 }17 let handler = middleware[i]18 index = i19 if (i === middleware.length) handler = next19 if (i === middleware.length && next) handler = next2021 if (handler === undefined) {22 if (context instanceof Context && context.res.finalized === false) {21 if (!handler) {22 if (context instanceof Context && context.res._finalized === false && onNotFound) {23 context.res = onNotFound(context)24 context.res.finalized = true24 context.res._finalized = true25 }26 return Promise.resolve(context)27 }28
1 unmodified line
30 .then(async (res: Response) => {31 // If handler return Response like `return c.text('foo')`32 if (res && context instanceof Context) {33 context.res = res34 context.res.finalized = true34 context.res._finalized = true35 }36 return context37 })38 .catch((err) => {39 if (onError && context instanceof Context) {39 if (context instanceof Context && onError) {40 if (err instanceof Error) {41 context.res = onError(err, context)42 context.res.finalized = true42 context.res._finalized = true43 }44 return context45 } else {46 throw err
5 unmodified lines
modified:src/context.test.ts-1 removed
124 unmodified lines
125 const ctx = new Context(req, {126 env: {127 API_KEY: key,128 },129 event: null,129 })130 expect(ctx.env.API_KEY).toBe(key)131 })132
18 unmodified lines
modified:src/context.ts+13 added-10 removed
1import type { StatusCode } from './utils/http-status'2import { isAbsoluteURL } from './utils/url'34type Headers = Record<string, string>5type Data = string | ArrayBuffer | ReadableStream5export type Data = string | ArrayBuffer | ReadableStream67export type Env = Record<string, any>89export class Context<RequestParamKeyType extends string = string, E = Env> {10 req: Request<RequestParamKeyType>11 res: Response12 env: E13 event: FetchEvent13 event: FetchEvent | undefined1415 private _status: StatusCode = 20016 private _pretty: boolean = false17 private _prettySpace: number = 2
5 unmodified lines
23 notFound: () => Response | Promise<Response>2425 constructor(26 req: Request<RequestParamKeyType>,27 opts?: { env: E; event: FetchEvent; res?: Response }27 opts: { env?: Env; event?: FetchEvent; res?: Response } = {28 env: {},29 event: undefined,30 res: undefined,31 }32 ) {33 this.req = this.initRequest<RequestParamKeyType>(req)34 this._map = {}3536 Object.assign(this, opts)3738 if (!this.res) {39 const res = new Response(null, { status: 404 })36 res.finalized = false40 res._finalized = false41 this.res = res42 }43 }4445 private initRequest<T extends string>(req: Request<T>): Request<T> {42 req.header = ((name?: string): string | Record<string, string> => {46 req.header = ((name?: string): string | Record<string, string> | null => {47 if (name) {48 return req.headers.get(name)49 } else {50 const result: Record<string, string> = {}
3 unmodified lines
54 return result55 }56 }) as typeof req.header5754 req.query = ((key?: string): string | Record<string, string> => {58 req.query = ((key?: string): string | Record<string, string> | null => {59 const url = new URL(req.url)60 if (key) {61 return url.searchParams.get(key)62 } else {63 const result: Record<string, string> = {}64 for (const key of url.searchParams.keys()) {61 result[key] = url.searchParams.get(key)65 result[key] = url.searchParams.get(key) || ''66 }67 return result68 }69 }) as typeof req.query
34 unmodified lines
104 this._pretty = prettyJSON105 this._prettySpace = space106 }107104 newResponse(data: Data, init: ResponseInit = {}): Response {108 newResponse(data: Data | null, init: ResponseInit = {}): Response {109 init.status = init.status || this._status || 200106 let headers: Record<string, string> = {}110 const headers: Record<string, string> = {}111 this.res.headers.forEach((v, k) => {112 headers[k] = v113 })114 init.headers = Object.assign(headers, init.headers)111 headers = {}115116 return new Response(data, init)117 }118
51 unmodified lines
modified:src/hono.ts+11 added-12 removed
25 unmodified lines
26 (): Record<string, string>27 }28 }29 interface Response {30 finalized: boolean30 _finalized: boolean31 }32}3334export type Handler<RequestParamKeyType extends string = string, E = Env> = (35 c: Context<RequestParamKeyType, E>,36 next: Next37) => Response | Promise<Response> | void | Promise<void>37) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined>38export type NotFoundHandler<E = Env> = (c: Context<string, E>) => Response39export type ErrorHandler<E = Env> = (err: Error, c: Context<string, E>) => Response40export type Next = () => Promise<void>41
46 unmodified lines
88 readonly strict: boolean = true // strict routing - default is true89 private _tempPath: string90 private path: string = '/'9192 private _cachedResponse: Response9392 routes: Route<E>[] = []9394 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {95 super()
19 unmodified lines
115 })116117 Object.assign(this, init)118121 this._tempPath = null122123 this._cachedResponse = new Response(null, { status: 404 })124 this._cachedResponse.finalized = false119 this._tempPath = ''120 }121122 private notFoundHandler: NotFoundHandler = (c: Context) => {123 const message = '404 Not Found'
11 unmodified lines
135 if (app) {136 app.routes.map((r) => {137 this.addRoute(r.method, r.path, r.handler)138 })144 this._tempPath = null139 this._tempPath = ''140 }141142 return this143 }
31 unmodified lines
175 const r: Route<E> = { path: path, method: method, handler: handler }176 this.routes.push(r)177 }178184 private async matchRoute(method: string, path: string): Promise<Result<Handler<string, E>>> {179 private async matchRoute(180 method: string,181 path: string182 ): Promise<Result<Handler<string, E>> | null> {183 return this.router.match(method, path)184 }185186 private async dispatch(request: Request, event?: FetchEvent, env?: E): Promise<Response> {
1 unmodified line
188 const method = request.method189190 const result = await this.matchRoute(method, path)191194 request.param = ((key?: string): string | Record<string, string> => {192 request.param = ((key?: string): string | Record<string, string> | null => {193 if (result) {194 if (key) {195 return result.params[key]196 } else {197 return result.params198 }199 }200 return null201 }) as typeof request.param202 const handlers = result ? result.handlers : [this.notFoundHandler]203204 const c = new Context<string, E>(request, {205 env: env,206 event: event,208 res: this._cachedResponse,207 })208 c.notFound = () => this.notFoundHandler(c)209210 const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)
3 unmodified lines
214 } catch (err) {215 if (err instanceof Error) {216 return this.errorHandler(err, c)217 }218 throw err219 }220221 if (!context.res) return context.notFound()222
22 unmodified lines
modified:tsconfig.json+3 added-1 removed
8 unmodified lines
9 "forceConsistentCasingInFileNames": true,10 "strict": true,11 "skipLibCheck": true,12 "strictPropertyInitialization": false,13 "strictNullChecks": false,13 "strictNullChecks": true,14 "noUnusedLocals": true,15 "noUnusedParameters": true,16 "types": [17 "jest",18 "node",19 "@cloudflare/workers-types"
7 unmodified lines