Skip to content
Myr

language.ts

This file

Path

src/middleware/language/language.ts

314 lines · 8.4 KiB · TypeScript

Last changed by

fix(accepts, language): skip accept entries with quality 0 when matching (#5311)LuckTerencebefore adoptionf147de5

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–109why, one step back
1/**
2 * @module3 * Language module for Hono.4 */5import type { Context } from '../../context'6import { setCookie, getCookie } from '../../helper/cookie'7import type { MiddlewareHandler } from '../../types'8import { parseAccept } from '../../utils/accept'910export type DetectorType = 'path' | 'querystring' | 'cookie' | 'header'11export type CacheType = 'cookie'1213export interface DetectorOptions {14 /** Order of language detection strategies */15 order: DetectorType[]16 /** Query parameter name for language */17 lookupQueryString: string18 /** Cookie name for language */19 lookupCookie: string20 /** Index in URL path where language code appears */21 lookupFromPathIndex: number22 /** Header key for language detection */23 lookupFromHeaderKey: string24 /** Caching strategies */25 caches: CacheType[] | false26 /** Cookie configuration options */27 cookieOptions?: {28 domain?: string29 path?: string30 sameSite?: 'Strict' | 'Lax' | 'None'31 secure?: boolean32 maxAge?: number33 httpOnly?: boolean34 }35 /** Whether to ignore case in language codes */36 ignoreCase: boolean37 /** Default language if none detected */38 fallbackLanguage: string39 /** List of supported language codes */40 supportedLanguages: string[]41 /** Optional function to transform detected language codes */42 convertDetectedLanguage?: (lang: string) => string43 /** Enable debug logging */44 debug?: boolean45}4647export interface LanguageVariables {48 language: string49}5051export const DEFAULT_OPTIONS: DetectorOptions = {52 order: ['querystring', 'cookie', 'header'],53 lookupQueryString: 'lang',54 lookupCookie: 'language',55 lookupFromHeaderKey: 'accept-language',56 lookupFromPathIndex: 0,57 caches: ['cookie'],58 ignoreCase: true,59 fallbackLanguage: 'en',60 supportedLanguages: ['en'],61 cookieOptions: {62 sameSite: 'Strict',63 secure: true,64 maxAge: 365 * 24 * 60 * 60,65 httpOnly: true,66 },67 debug: false,68}69/**70 * Parse Accept-Language header values with quality scores71 * @param header Accept-Language header string72 * @returns Array of parsed languages with quality scores73 */74export function parseAcceptLanguage(header: string): Array<{ lang: string; q: number }> {75 return parseAccept(header).map(({ type, q }) => ({ lang: type, q }))76}7778/**79 * Validate and normalize language codes80 * @param lang Language code to normalize81 * @param options Detector options82 * @returns Normalized language code or undefined83 */84export const normalizeLanguage = (85 lang: string | null | undefined,86 options: DetectorOptions87): string | undefined => {88 if (!lang) {89 return undefined90 }9192 try {93 let normalizedLang = lang.trim()94 if (options.convertDetectedLanguage) {95 normalizedLang = options.convertDetectedLanguage(normalizedLang)96 }9798 const compLang = options.ignoreCase ? normalizedLang.toLowerCase() : normalizedLang99 const compSupported = options.supportedLanguages.map((l) =>100 options.ignoreCase ? l.toLowerCase() : l101 )102103 // Exact match104 const exactIndex = compSupported.indexOf(compLang)105 if (exactIndex !== -1) {106 return options.supportedLanguages[exactIndex]107 }108109 // Progressive truncation (RFC 4647 Lookup)

Merge commit from forkTaku Amanobefore adoptionf70e2c3

lines 110–121why, one step back
110 let longestMatchIndex = -1
111 let longestMatchLength = -1112 for (let i = 0; i < compSupported.length; i++) {113 const candidate = compSupported[i]114 if (115 candidate.length < compLang.length &&116 candidate.length > longestMatchLength &&117 compLang.startsWith(candidate) &&118 compLang[candidate.length] === '-'119 ) {120 longestMatchIndex = i121 longestMatchLength = candidate.length

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 122why, one step back
122 }

Merge commit from forkTaku Amanobefore adoptionf70e2c3

lines 123–125why, one step back
123 }
124 if (longestMatchIndex !== -1) {125 return options.supportedLanguages[longestMatchIndex]

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 126–160why, one step back
126 }
127128 return undefined129 } catch {130 return undefined131 }132}133134/**135 * Detects language from query parameter136 */137export const detectFromQuery = (c: Context, options: DetectorOptions): string | undefined => {138 const query = c.req.query(options.lookupQueryString)139 return normalizeLanguage(query, options)140}141142/**143 * Detects language from cookie144 */145export const detectFromCookie = (c: Context, options: DetectorOptions): string | undefined => {146 const cookie = getCookie(c, options.lookupCookie)147 return normalizeLanguage(cookie, options)148}149150/**151 * Detects language from Accept-Language header152 */153export function detectFromHeader(c: Context, options: DetectorOptions): string | undefined {154 try {155 const acceptLanguage = c.req.header(options.lookupFromHeaderKey)156 if (!acceptLanguage) {157 return undefined158 }159160 const languages = parseAcceptLanguage(acceptLanguage)

fix(accepts, language): skip accept entries with quality 0 when matching (#5311)LuckTerencebefore adoptionf147de5

lines 161–166why, one step back
161 for (const { lang, q } of languages) {
162 // A quality value of 0 means the language is explicitly rejected163 // (RFC 9110 §12.5.4), so it must not be detected.164 if (q === 0) {165 continue166 }

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 167–277why, one step back
167 const normalizedLang = normalizeLanguage(lang, options)
168 if (normalizedLang) {169 return normalizedLang170 }171 }172 return undefined173 } catch {174 return undefined175 }176}177178/**179 * Detects language from URL path180 */181export function detectFromPath(c: Context, options: DetectorOptions): string | undefined {182 const url = new URL(c.req.url)183 const pathSegments = url.pathname.split('/').filter(Boolean)184 const langSegment = pathSegments[options.lookupFromPathIndex]185 return normalizeLanguage(langSegment, options)186}187188/**189 * Collection of all language detection strategies190 */191export const detectors = {192 querystring: detectFromQuery,193 cookie: detectFromCookie,194 header: detectFromHeader,195 path: detectFromPath,196} as const197198/** Type for detector functions */199export type DetectorFunction = (c: Context, options: DetectorOptions) => string | undefined200201/** Type-safe detector map */202export type Detectors = Record<keyof typeof detectors, DetectorFunction>203204/**205 * Validate detector options206 * @param options Detector options to validate207 * @throws Error if options are invalid208 */209export function validateOptions(options: DetectorOptions): void {210 if (!options.supportedLanguages.includes(options.fallbackLanguage)) {211 throw new Error('Fallback language must be included in supported languages')212 }213214 if (options.lookupFromPathIndex < 0) {215 throw new Error('Path index must be non-negative')216 }217218 if (!options.order.every((detector) => Object.keys(detectors).includes(detector))) {219 throw new Error('Invalid detector type in order array')220 }221}222223/**224 * Cache detected language225 */226function cacheLanguage(c: Context, language: string, options: DetectorOptions): void {227 if (!Array.isArray(options.caches) || !options.caches.includes('cookie')) {228 return229 }230231 try {232 setCookie(c, options.lookupCookie, language, options.cookieOptions)233 } catch (error) {234 if (options.debug) {235 console.error('Failed to cache language:', error)236 }237 }238}239240/**241 * Detect language from request242 */243const detectLanguage = (c: Context, options: DetectorOptions): string => {244 let detectedLang: string | undefined245246 for (const detectorName of options.order) {247 const detector = detectors[detectorName]248249 try {250 detectedLang = detector(c, options)251 if (detectedLang) {252 if (options.debug) {253 console.log(`Language detected from ${detectorName}: ${detectedLang}`)254 }255 break256 }257 } catch (error) {258 if (options.debug) {259 console.error(`Error in ${detectorName} detector:`, error)260 }261 continue262 }263 }264265 const finalLang = detectedLang || options.fallbackLanguage266267 if (detectedLang && options.caches) {268 cacheLanguage(c, finalLang, options)269 }270271 return finalLang272}273274/**275 * Language detector middleware factory276 * @param userOptions Configuration options for the language detector277 * @returns Hono middleware function

docs(language): add JSDoc @example to languageDetector (#5081)Muhammad Bilalbefore adoption46557ef

lines 278–295why, one step back
278 *
279 * @example280 * ```ts281 * type Variables = LanguageVariables282 * const app = new Hono<{ Variables: Variables }>()283 *284 * app.use(285 * languageDetector({286 * supportedLanguages: ['en', 'ja'], // Must include fallback287 * fallbackLanguage: 'en', // Required288 * })289 * )290 *291 * app.get('/', (c) => {292 * const lang = c.get('language')293 * return c.text(`Current language: ${lang}`)294 * })295 * ```

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 296–314why, one step back
296 */
297export const languageDetector = (userOptions: Partial<DetectorOptions>): MiddlewareHandler => {298 const options: DetectorOptions = {299 ...DEFAULT_OPTIONS,300 ...userOptions,301 cookieOptions: {302 ...DEFAULT_OPTIONS.cookieOptions,303 ...userOptions.cookieOptions,304 },305 }306307 validateOptions(options)308309 return async function languageDetector(ctx, next) {310 const lang = detectLanguage(ctx, options)311 ctx.set('language', lang)312 await next()313 }314}