Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add language detector middleware and helpers #3787

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
2 changes: 2 additions & 0 deletions jsr.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"./powered-by": "./src/middleware/powered-by/index.ts",
"./pretty-json": "./src/middleware/pretty-json/index.ts",
"./request-id": "./src/middleware/request-id/request-id.ts",
"./language": "./src/middleware/language/language.ts",
"./secure-headers": "./src/middleware/secure-headers/secure-headers.ts",
"./combine": "./src/middleware/combine/index.ts",
"./ssg": "./src/helper/ssg/index.ts",
Expand Down Expand Up @@ -93,6 +94,7 @@
"./utils/headers": "./src/utils/headers.ts",
"./utils/html": "./src/utils/html.ts",
"./utils/http-status": "./src/utils/http-status.ts",
"./utils/parse-accept": "./src/utils/parse-accept.ts",
"./utils/jwt": "./src/utils/jwt/index.ts",
"./utils/jwt/jwa": "./src/utils/jwt/jwa.ts",
"./utils/jwt/jws": "./src/utils/jwt/jws.ts",
Expand Down
8 changes: 8 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,11 @@
"import": "./dist/middleware/request-id/index.js",
"require": "./dist/cjs/middleware/request-id/index.js"
},
"./language": {
"types": "./dist/types/middleware/language/index.d.ts",
"import": "./dist/middleware/language/index.js",
"require": "./dist/cjs/middleware/language/index.js"
},
"./secure-headers": {
"types": "./dist/types/middleware/secure-headers/index.d.ts",
"import": "./dist/middleware/secure-headers/index.js",
Expand Down Expand Up @@ -506,6 +511,9 @@
"request-id": [
"./dist/types/middleware/request-id"
],
"language": [
"./dist/types/middleware/language"
],
"streaming": [
"./dist/types/helper/streaming"
],
Expand Down
5 changes: 3 additions & 2 deletions src/helper/accepts/accepts.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Hono } from '../..'
import { parseAccept } from '../../utils/parse-accept'
import type { Accept, acceptsConfig, acceptsOptions } from './accepts'
import { accepts, defaultMatch, parseAccept } from './accepts'
import { accepts, defaultMatch } from './accepts'

describe('parseAccept', () => {
test('should parse accept header', () => {
Expand All @@ -10,8 +11,8 @@ describe('parseAccept', () => {
expect(accepts).toEqual([
{ type: 'text/html', params: {}, q: 1 },
{ type: 'application/xhtml+xml', params: {}, q: 1 },
{ type: 'application/xml', params: { q: '0.9' }, q: 0.9 },
{ type: 'image/webp', params: {}, q: 1 },
{ type: 'application/xml', params: { q: '0.9' }, q: 0.9 },
{ type: '*/*', params: { q: '0.8', level: '1', foo: 'bar' }, q: 0.8 },
])
})
Expand Down
26 changes: 1 addition & 25 deletions src/helper/accepts/accepts.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Context } from '../../context'
import type { AcceptHeader } from '../../utils/headers'
import { parseAccept } from '../../utils/parse-accept'

export interface Accept {
type: string
Expand All @@ -17,31 +18,6 @@ export interface acceptsOptions extends acceptsConfig {
match?: (accepts: Accept[], config: acceptsConfig) => string
}

export const parseAccept = (acceptHeader: string): Accept[] => {
// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
const accepts = acceptHeader.split(',') // ['text/html', 'application/xhtml+xml', 'application/xml;q=0.9', 'image/webp', '*/*;q=0.8']
return accepts.map((accept) => {
const parts = accept.trim().split(';') // ['text/html', 'q=0.9', 'image/webp']
const type = parts[0] // text/html
const params = parts.slice(1) // ['q=0.9', 'image/webp']
const q = params.find((param) => param.startsWith('q='))

const paramsObject = params.reduce((acc, param) => {
const keyValue = param.split('=')
const key = keyValue[0].trim()
const value = keyValue[1].trim()
acc[key] = value
return acc
}, {} as { [key: string]: string })

return {
type: type,
params: paramsObject,
q: q ? parseFloat(q.split('=')[1]) : 1,
}
})
}

export const defaultMatch = (accepts: Accept[], config: acceptsConfig): string => {
const { supports, default: defaultSupport } = config
const accept = accepts.sort((a, b) => b.q - a.q).find((accept) => supports.includes(accept.type))
Expand Down
275 changes: 275 additions & 0 deletions src/middleware/language/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,275 @@
import { Hono } from '../../hono'
import { detectors } from './language'
import { languageDetector } from '.'

describe('languageDetector', () => {
const createTestApp = (options = {}) => {
const app = new Hono()

app.use('/*', languageDetector(options))

app.get('/*', (c) => c.text(c.get('language')))

return app
}

describe('Query Parameter Detection', () => {
it('should detect language from query parameter', async () => {
const app = createTestApp({
supportedLanguages: ['en', 'fr', 'es'],
fallbackLanguage: 'en',
})

const res = await app.request('/?lang=fr')
expect(await res.text()).toBe('fr')
})

it('should ignore unsupported languages in query', async () => {
const app = createTestApp({
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
})

const res = await app.request('/?lang=de')
expect(await res.text()).toBe('en')
})
})

describe('Cookie Detection', () => {
it('should detect language from cookie', async () => {
const app = createTestApp({
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
})

const res = await app.request('/', {
headers: {
cookie: 'language=fr',
},
})
expect(await res.text()).toBe('fr')
})

it('should cache detected language in cookie when enabled', async () => {
const app = createTestApp({
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
caches: ['cookie'],
})

const res = await app.request('/?lang=fr')
expect(res.headers.get('set-cookie')).toContain('language=fr')
})
})

describe('Header Detection', () => {
it('should detect language from Accept-Language header', async () => {
const app = createTestApp({
supportedLanguages: ['en', 'fr', 'es'],
fallbackLanguage: 'en',
})

const res = await app.request('/', {
headers: {
'accept-language': 'fr-FR,fr;q=0.9,en;q=0.8',
},
})
expect(await res.text()).toBe('fr')
})

it('should handle malformed Accept-Language headers', async () => {
const app = createTestApp({
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
})

const res = await app.request('/', {
headers: {
'accept-language': 'invalid;header;;format',
},
})
expect(await res.text()).toBe('en')
})
})

describe('Path Detection', () => {
it('should detect language from path', async () => {
const app = createTestApp({
order: ['path'],
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
lookupFromPathIndex: 0,
})

const res = await app.request('/fr/page')
expect(await res.text()).toBe('fr')
})

it('should handle invalid path index gracefully', async () => {
const app = createTestApp({
order: ['path'],
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
lookupFromPathIndex: 99,
})

const res = await app.request('/fr/page')
expect(await res.text()).toBe('en')
})
})

describe('Detection Order', () => {
it('should respect detection order', async () => {
const app = createTestApp({
order: ['cookie', 'querystring'],
supportedLanguages: ['en', 'fr', 'es'],
fallbackLanguage: 'en',
})

const res = await app.request('/?lang=fr', {
headers: {
cookie: 'language=es',
},
})

// Since cookie is first in order, it should use 'es'
expect(await res.text()).toBe('es')
})

it('should fall back to next detector if first fails', async () => {
const app = createTestApp({
order: ['cookie', 'querystring'],
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
})

const res = await app.request('/?lang=fr') // No cookie
expect(await res.text()).toBe('fr') // Should use querystring
})
})

describe('Language Conversion', () => {
it('should apply language conversion function', async () => {
const app = createTestApp({
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
convertDetectedLanguage: (lang: string) => lang.split('-')[0],
})

const res = await app.request('/?lang=fr-FR')
expect(await res.text()).toBe('fr')
})

it('should handle case sensitivity according to options', async () => {
const app = createTestApp({
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
ignoreCase: false,
})

const res = await app.request('/?lang=FR')
expect(await res.text()).toBe('en') // Falls back because case doesn't match
})
})

describe('Error Handling', () => {
it('should fall back to default language on error', async () => {
const app = createTestApp({
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
})

const detector = vi.spyOn(detectors, 'querystring').mockImplementation(() => {
throw new Error('Simulated error')
})

const res = await app.request('/?lang=fr')
expect(await res.text()).toBe('en')

detector.mockRestore()
})

it('should handle missing cookie values gracefully', async () => {
const app = createTestApp({
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
order: ['cookie'],
})

const res = await app.request('/')
expect(await res.text()).toBe('en')
})
})

describe('Configuration Validation', () => {
it('should throw if fallback language is not in supported languages', () => {
expect(() => {
createTestApp({
supportedLanguages: ['fr', 'es'],
fallbackLanguage: 'en',
})
}).toThrow()
})

it('should throw if path index is negative', () => {
expect(() => {
createTestApp({
lookupFromPathIndex: -1,
})
}).toThrow()
})

it('should handle empty supported languages list', () => {
expect(() => {
createTestApp({
supportedLanguages: [],
})
}).toThrow()
})
})

describe('Debug Mode', () => {
it('should log errors in debug mode', async () => {
const consoleErrorSpy = vi.spyOn(console, 'error')

const app = createTestApp({
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
debug: true,
})

const detector = vi.spyOn(detectors, 'querystring').mockImplementation(() => {
throw new Error('Simulated error')
})

await app.request('/?lang=fr')

expect(consoleErrorSpy).toHaveBeenCalledWith(
'Error in querystring detector:',
expect.any(Error)
)

detector.mockRestore()
consoleErrorSpy.mockRestore()
})

// The log test remains unchanged
it('should log debug information when enabled', async () => {
const consoleSpy = vi.spyOn(console, 'log')

const app = createTestApp({
supportedLanguages: ['en', 'fr'],
fallbackLanguage: 'en',
debug: true,
})

await app.request('/?lang=fr')

expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining('Language detected from querystring')
)

consoleSpy.mockRestore()
})
})
})
14 changes: 14 additions & 0 deletions src/middleware/language/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { LanguageVariables, DetectorType, CacheType } from './language'
export type { LanguageVariables, DetectorType, CacheType }
export {
languageDetector,
DetectorOptions,
detectFromCookie,
detectFromHeader,
detectFromPath,
detectFromQuery,
DEFAULT_OPTIONS,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DEFAULT_OPTIONS is a type. It should not be here.

diff --git a/src/middleware/language/index.ts b/src/middleware/language/index.ts
index d225a54a..061c7538 100644
--- a/src/middleware/language/index.ts
+++ b/src/middleware/language/index.ts
@@ -1,8 +1,7 @@
-import type { LanguageVariables, DetectorType, CacheType } from './language'
-export type { LanguageVariables, DetectorType, CacheType }
+import type { LanguageVariables, DetectorOptions, DetectorType, CacheType } from './language'
+export type { LanguageVariables, DetectorOptions, DetectorType, CacheType }
 export {
   languageDetector,
-  DetectorOptions,
   detectFromCookie,
   detectFromHeader,
   detectFromPath,

} from './language'
declare module '../..' {
interface ContextVariableMap extends LanguageVariables {}
}
Loading
Loading