accepts.test.ts
This file
Path
src/helper/accepts/accepts.test.ts
344 lines · 10.9 KiB · TypeScript
Last changed by
fix(accepts): match media types and language tags case-insensitively (#5376)Harshit Prakashbefore adoptionf5a5346
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–2why, one step back1import { Hono } from '../..'2import { parseAccept } from '../../utils/accept'fix(accepts): match media types and language tags case-insensitively (#5376)Harshit Prakashbefore adoptionf5a5346
line 3why, one step back3import type { AcceptHeader } from '../../utils/headers'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 4–73why, one step back4import type { Accept, acceptsConfig, acceptsOptions } from './accepts'5import { accepts, defaultMatch } from './accepts'67describe('parseAccept', () => {8 test('should parse accept header', () => {9 const acceptHeader =10 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8;level=1;foo=bar'11 const accepts = parseAccept(acceptHeader)12 expect(accepts).toEqual([13 { type: 'text/html', params: {}, q: 1 },14 { type: 'application/xhtml+xml', params: {}, q: 1 },15 { type: 'image/webp', params: {}, q: 1 },16 { type: 'application/xml', params: { q: '0.9' }, q: 0.9 },17 { type: '*/*', params: { q: '0.8', level: '1', foo: 'bar' }, q: 0.8 },18 ])19 })20})2122describe('defaultMatch', () => {23 test('should return default support', () => {24 const accepts: Accept[] = [25 { type: 'text/html', params: {}, q: 1 },26 { type: 'application/xhtml+xml', params: {}, q: 1 },27 { type: 'application/xml', params: { q: '0.9' }, q: 0.9 },28 { type: 'image/webp', params: {}, q: 1 },29 { type: '*/*', params: { q: '0.8' }, q: 0.8 },30 ]31 const config: acceptsConfig = {32 header: 'Accept',33 supports: ['text/html'],34 default: 'text/html',35 }36 const result = defaultMatch(accepts, config)37 expect(result).toBe('text/html')38 })39})4041describe('accepts', () => {42 test('should return matched support', () => {43 const c = {44 req: {45 header: () => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',46 },47 // eslint-disable-next-line @typescript-eslint/no-explicit-any48 } as any49 const options: acceptsConfig = {50 header: 'Accept',51 supports: ['application/xml', 'text/html'],52 default: 'application/json',53 }54 const result = accepts(c, options)55 expect(result).toBe('text/html')56 })5758 test('should return default support if no matched support', () => {59 const c = {60 req: {61 header: () => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',62 },63 // eslint-disable-next-line @typescript-eslint/no-explicit-any64 } as any65 const options: acceptsConfig = {66 header: 'Accept',67 supports: ['application/json'],68 default: 'text/html',69 }70 const result = accepts(c, options)71 expect(result).toBe('text/html')72 })73fix(accepts): support wildcard media types and specificity ordering in defaultMatch (#5255)ADITYA KUMAR JHAbefore adoption28a9c12
lines 74–153why, one step back74 test('should match wildcard subtype application/*', () => {75 const c = {76 req: {77 header: () => 'application/*',78 },79 // eslint-disable-next-line @typescript-eslint/no-explicit-any80 } as any81 const options: acceptsConfig = {82 header: 'Accept',83 supports: ['application/json', 'text/html'],84 default: 'text/html',85 }86 const result = accepts(c, options)87 expect(result).toBe('application/json')88 })8990 test('should return default support for global wildcard */*', () => {91 const c = {92 req: {93 header: () => 'text/plain, */*;q=0.5',94 },95 // eslint-disable-next-line @typescript-eslint/no-explicit-any96 } as any97 const options: acceptsConfig = {98 header: 'Accept',99 supports: ['application/json'],100 default: 'text/html',101 }102 const result = accepts(c, options)103 expect(result).toBe('text/html')104 })105106 test('should return default support for single asterisk wildcard *', () => {107 const c = {108 req: {109 header: () => '*',110 },111 // eslint-disable-next-line @typescript-eslint/no-explicit-any112 } as any113 const options: acceptsConfig = {114 header: 'Accept-Encoding',115 supports: ['gzip', 'deflate'],116 default: 'identity',117 }118 const result = accepts(c, options)119 expect(result).toBe('identity')120 })121122 test('should prefer exact match over wildcard match at same quality factor', () => {123 const c = {124 req: {125 header: () => '*/*, application/json',126 },127 // eslint-disable-next-line @typescript-eslint/no-explicit-any128 } as any129 const options: acceptsConfig = {130 header: 'Accept',131 supports: ['text/html', 'application/json'],132 default: 'text/html',133 }134 const result = accepts(c, options)135 expect(result).toBe('application/json')136 })137138 test('should match subtype wildcard while global wildcard falls through to default', () => {139 const c = {140 req: {141 header: () => '*/*, text/*',142 },143 // eslint-disable-next-line @typescript-eslint/no-explicit-any144 } as any145 const options: acceptsConfig = {146 header: 'Accept',147 supports: ['application/json', 'text/plain'],148 default: 'application/json',149 }150 const result = accepts(c, options)151 expect(result).toBe('text/plain')152 })153Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 154–193why, one step back154 test('should return default support if no accept header', () => {155 const c = {156 req: {157 header: () => undefined,158 },159 // eslint-disable-next-line @typescript-eslint/no-explicit-any160 } as any161 const options: acceptsConfig = {162 header: 'Accept',163 supports: ['application/json'],164 default: 'text/html',165 }166 const result = accepts(c, options)167 expect(result).toBe('text/html')168 })169170 test('should return matched support with custom match function', () => {171 const c = {172 req: {173 header: () => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',174 },175 // eslint-disable-next-line @typescript-eslint/no-explicit-any176 } as any177 // this match function will return the least q value178 const match = (accepts: Accept[], config: acceptsConfig) => {179 const { supports, default: defaultSupport } = config180 const accept = accepts181 .sort((a, b) => a.q - b.q)182 .find((accept) => supports.includes(accept.type))183 return accept ? accept.type : defaultSupport184 }185 const options: acceptsOptions = {186 header: 'Accept',187 supports: ['application/xml', 'text/html'],188 default: 'application/json',189 match,190 }191 const result = accepts(c, options)192 expect(result).toBe('application/xml')193 })fix(accepts, language): skip accept entries with quality 0 when matching (#5311)LuckTerencebefore adoptionf147de5
lines 194–240why, one step back194195 test('should not match entries explicitly rejected with q=0', () => {196 const c = {197 req: {198 header: () => 'application/json;q=0',199 },200 // eslint-disable-next-line @typescript-eslint/no-explicit-any201 } as any202 const options: acceptsConfig = {203 header: 'Accept',204 supports: ['application/json'],205 default: 'text/html',206 }207 const result = accepts(c, options)208 expect(result).toBe('text/html')209 })210211 test('should skip q=0 entries and match the remaining ones', () => {212 const c = {213 req: {214 header: () => 'text/html;q=0.5, application/json;q=0',215 },216 // eslint-disable-next-line @typescript-eslint/no-explicit-any217 } as any218 const options: acceptsConfig = {219 header: 'Accept',220 supports: ['application/json'],221 default: 'application/octet-stream',222 }223 const result = accepts(c, options)224 expect(result).toBe('application/octet-stream')225 })226227 test('should not match a subtype wildcard the client rejected with q=0', () => {228 const c = {229 req: {230 header: () => 'application/*;q=0',231 },232 // eslint-disable-next-line @typescript-eslint/no-explicit-any233 } as any234 const options: acceptsConfig = {235 header: 'Accept',236 supports: ['application/json'],237 default: 'text/html',238 }239 const result = accepts(c, options)240 expect(result).toBe('text/html')fix(accepts): match media types and language tags case-insensitively (#5376)Harshit Prakashbefore adoptionf5a5346
lines 241–274why, one step back241 })242243 describe('case insensitivity', () => {244 const pick = (header: AcceptHeader, value: string, supports: string[]) => {245 const c = {246 req: { header: () => value },247 // eslint-disable-next-line @typescript-eslint/no-explicit-any248 } as any249 return accepts(c, { header, supports, default: 'DEFAULT' })250 }251252 // Media types are case-insensitive (RFC 9110 §8.3.1)253 test.each(['text/html', 'TEXT/HTML', 'Text/Html', 'text/HTML'])(254 'Accept: %s matches text/html',255 (value) => {256 expect(pick('Accept', value, ['text/html'])).toBe('text/html')257 }258 )259260 test('a case-different subtype wildcard still matches', () => {261 expect(pick('Accept', 'TEXT/*', ['text/html'])).toBe('text/html')262 })263264 // Language tags are case-insensitive (RFC 4647 §2.1)265 test.each(['en-US', 'EN-US', 'en-us', 'En-Us'])(266 'Accept-Language: %s matches en-US',267 (value) => {268 expect(pick('Accept-Language', value, ['en-US'])).toBe('en-US')269 }270 )271272 test('a case-different entry with q=0 is still not acceptable', () => {273 expect(pick('Accept-Language', 'EN;q=0', ['en'])).toBe('DEFAULT')274 })fix(accepts, language): skip accept entries with quality 0 when matching (#5311)LuckTerencebefore adoptionf147de5
line 275why, one step back275 })Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 276–344why, one step back276})277278describe('Usage', () => {279 test('decide compression by Accept-Encoding header', async () => {280 const app = new Hono()281 app.get('/compressed', async (c) => {282 const encoding = accepts(c, {283 header: 'Accept-Encoding',284 supports: ['gzip', 'deflate'],285 default: 'identity',286 })287 const COMPRESS_DATA = 'COMPRESS_DATA'288 const readable = new ReadableStream({289 start(controller) {290 controller.enqueue(new TextEncoder().encode(COMPRESS_DATA))291 controller.close()292 },293 })294295 if (encoding === 'gzip') {296 c.header('Content-Encoding', 'gzip')297 return c.body(readable.pipeThrough(new CompressionStream('gzip')))298 }299 if (encoding === 'deflate') {300 c.header('Content-Encoding', 'deflate')301 return c.body(readable.pipeThrough(new CompressionStream('deflate')))302 }303304 c.body(COMPRESS_DATA)305 })306307 const req1 = await app.request('/compressed', { headers: { 'Accept-Encoding': 'deflate' } })308 const req2 = await app.request('/compressed', { headers: { 'Accept-Encoding': 'gzip' } })309 const req3 = await app.request('/compressed', {310 headers: { 'Accept-Encoding': 'gzip;q=0.5,deflate' },311 })312 const req4 = await app.request('/compressed', { headers: { 'Accept-Encoding': 'br' } })313314 expect(req1.headers.get('Content-Encoding')).toBe('deflate')315 expect(req2.headers.get('Content-Encoding')).toBe('gzip')316 expect(req3.headers.get('Content-Encoding')).toBe('deflate')317 expect(req4.headers.get('Content-Encoding')).toBeNull()318 })319320 test('decide language by Accept-Language header', async () => {321 const app = new Hono()322 const SUPPORTED_LANGS = ['en', 'ja', 'zh']323 app.get('/*', async (c) => {324 const lang = accepts(c, {325 header: 'Accept-Language',326 supports: SUPPORTED_LANGS,327 default: 'en',328 })329 const isLangedPath = SUPPORTED_LANGS.some((l) => c.req.path.startsWith(`/${l}`))330 if (isLangedPath) {331 return c.body(`lang: ${lang}`)332 }333334 return c.redirect(`/${lang}${c.req.path}`)335 })336337 const req1 = await app.request('/foo', { headers: { 'Accept-Language': 'en=0.8,ja' } })338 const req2 = await app.request('/en/foo', { headers: { 'Accept-Language': 'en' } })339340 expect(req1.status).toBe(302)341 expect(req1.headers.get('Location')).toBe('/ja/foo')342 expect(await req2.text()).toBe('lang: en')343 })344})