-
-
Notifications
You must be signed in to change notification settings - Fork 652
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
lord007tn
wants to merge
8
commits into
honojs:main
Choose a base branch
from
lord007tn:feature/language-detector
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
fcaa8c2
feat(language-detector): add language detector middleware and helper …
lord007tn 629eb03
chore(language-detector): add export in package.json
lord007tn bdf1a30
chore(language-detector): add export to jsr
lord007tn 05007db
feat: new parse-accept helper, add edge case tests
lord007tn 44fe77d
chore: add jsr for parse-accept
lord007tn 6b4e053
fix: export default options, remove empty type
lord007tn e84b840
refac: rename languageDetectorMiddleware to languageDetector
lord007tn 2127d80
chore format code
lord007tn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,276 @@ | ||
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() | ||
}) | ||
}) | ||
|
||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
} from './language' | ||
declare module '../..' { | ||
interface ContextVariableMap extends LanguageVariables {} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.