Create a multilingual canonical arbitration: locale fallbacks, mixed-language pages, and…
- User
Create a multilingual canonical arbitration: locale fallbacks, mixed-language pages, and tests.
Assistant
Create a multilingual canonical arbitration: locale fallbacks, mixed-language pages, and tests.
The user wants a "multilingual canonical arbitration" system. This is about handling internationalization (i18n) with:
Let me create a comprehensive system that demonstrates:
I'll create a sophisticated system that handles:
Let me build this as a well-structured project.
A sophisticated i18n system handling locale fallbacks, mixed-language pages, and canonical URL resolution.
multilingual-arbitration/
├── src/
│ ├── core/
│ │ ├── LocaleResolver.ts
│ │ ├── CanonicalArbiter.ts
│ │ ├── ContentNegotiator.ts
│ │ └── FallbackChain.ts
│ ├── content/
│ │ ├── TranslationStore.ts
│ │ └── MixedLanguagePage.ts
│ ├── utils/
│ │ └── helpers.ts
│ └── index.ts
├── tests/
│ ├── localeResolver.test.ts
│ ├── canonicalArbiter.test.ts
│ ├── fallbackChain.test.ts
│ ├── mixedLanguage.test.ts
│ └── integration.test.ts
├── package.json
├── tsconfig.json
└── vitest.config.ts
src/core/types.ts// Core type definitions for multilingual system
export interface Locale {
code: string; // e.g., 'en-US'
language: string; // e.g., 'en'
region?: string; // e.g., 'US'
script?: string; // e.g., 'Latn'
quality: number; // 0-1 preference score
}
export interface LocaleConfig {
defaultLocale: string;
supportedLocales: string[];
fallbackChain: Record<string, string[]>;
aliases: Record<string, string>;
}
export interface CanonicalResult {
canonicalUrl: string;
canonicalLocale: string;
alternates: AlternateLink[];
matchedLocale: string;
fallbackUsed: boolean;
fallbackChain: string[];
}
export interface AlternateLink {
locale: string;
url: string;
hrefLang: string;
isDefault: boolean;
}
export interface ContentSegment {
locale: string;
content: string;
field: string;
isTranslatable: boolean;
}
export interface MixedLanguagePage {
id: string;
defaultLocale: string;
segments: ContentSegment[];
availableLocales: string[];
canonicalLocale: string;
}
export interface TranslationEntry {
key: string;
value: string;
locale: string;
context?: string;
plural?: boolean;
}
export type LocaleMatchResult = {
matched: string;
source: 'exact' | 'language' | 'fallback' | 'default';
confidence: number;
};
src/core/FallbackChain.tsimport type { LocaleConfig, LocaleMatchResult } from './types';
export class FallbackChain {
private config: LocaleConfig;
constructor(config: LocaleConfig) {
this.config = config;
}
/**
* Builds a fallback chain for a given locale
*/
buildChain(locale: string): string[] {
const chain: string[] = [];
const normalizedLocale = this.normalizeLocale(locale);
// Add the locale itself if supported
if (this.isSupported(normalizedLocale)) {
chain.push(normalizedLocale);
}
// Check explicit fallback chain
const explicitFallbacks = this.config.fallbackChain[normalizedLocale] || [];
for (const fallback of explicitFallbacks) {
if (!chain.includes(fallback) && this.isSupported(fallback)) {
chain.push(fallback);
}
}
// Add language-only fallback (e.g., 'en-US' -> 'en')
const languageOnly = this.extractLanguage(normalizedLocale);
if (languageOnly !== normalizedLocale && !chain.includes(languageOnly)) {
if (this.isSupported(languageOnly)) {
chain.push(languageOnly);
}
}
// Add sibling locales (same language, different region)
for (const supported of this.config.supportedLocales) {
const supportedLang = this.extractLanguage(supported);
if (supportedLang === languageOnly && !chain.includes(supported)) {
chain.push(supported);
}
}
// Add default locale as final fallback
if (!chain.includes(this.config.defaultLocale)) {
chain.push(this.config.defaultLocale);
}
return chain;
}
/**
* Resolves the best matching locale from a list of preferences
*/
resolve(preferences: string[]): LocaleMatchResult {
for (const pref of preferences) {
const normalized = this.normalizeLocale(pref);
// Exact match
if (this.isSupported(normalized)) {
return {
matched: normalized,
source: 'exact',
confidence: 1.0
};
}
// Language-only match
const langOnly = this.extractLanguage(normalized);
const langMatch = this.config.supportedLocales.find(
s => this.extractLanguage(s) === langOnly
);
if (langMatch) {
return {
matched: langMatch,
source: 'language',
confidence: 0.8
};
}
}
// Check fallback chains
for (const pref of preferences) {
const chain = this.buildChain(pref);
if (chain.length > 0 && chain[0] !== this.config.defaultLocale) {
return {
matched: chain[0],
source: 'fallback',
confidence: 0.5
};
}
}
// Default
return {
matched: this.config.defaultLocale,
source: 'default',
confidence: 0.1
};
}
/**
* Normalizes a locale string
*/
normalizeLocale(locale: string): string {
const lower = locale.toLowerCase().trim();
// Check aliases
if (this.config.aliases[lower]) {
return this.config.aliases[lower];
}
// Normalize format: xx-XX or xx-Xxxx
const parts = lower.split(/[-_]/);
if (parts.length === 1) {
return parts[0];
}
const lang = parts[0];
const region = parts[1].toUpperCase();
const script = parts[2] ? parts[2].charAt(0).toUpperCase() + parts[2].slice(1) : '';
return script ? `${lang}-${region}-${script}` : `${lang}-${region}`;
}
/**
* Extracts language code from locale
*/
extractLanguage(locale: string): string {
return locale.split(/[-_]/)[0].toLowerCase();
}
/**
* Checks if locale is supported
*/
isSupported(locale: string): boolean {
const normalized = this.normalizeLocale(locale);
return this.config.supportedLocales.some(
s => this.normalizeLocale(s) === normalized
);
}
/**
* Gets all locales that share a language
*/
getSiblingLocales(locale: string): string[] {
const lang = this.extractLanguage(locale);
return this.config.supportedLocales.filter(
s => this.extractLanguage(s) === lang
);
}
}
src/core/LocaleResolver.tsimport type { Locale, LocaleConfig, LocaleMatchResult } from './types';
import { FallbackChain } from './FallbackChain';
export class LocaleResolver {
private fallbackChain: FallbackChain;
private config: LocaleConfig;
constructor(config: LocaleConfig) {
this.config = config;
this.fallbackChain = new FallbackChain(config);
}
/**
* Parses Accept-Language header
*/
parseAcceptLanguage(header: string): Locale[] {
if (!header) return [];
return header
.split(',')
.map(part => {
const trimmed = part.trim();
const [locale, ...params] = trimmed.split(';');
let quality = 1.0;
for (const param of params) {
const [key, value] = param.trim().split('=');
if (key === 'q' && value) {
quality = parseFloat(value);
}
}
const normalizedLocale = this.fallbackChain.normalizeLocale(locale);
const [lang, region, script] = normalizedLocale.split('-');
return {
code: normalizedLocale,
language: lang,
region: region,
script: script,
quality
};
})
.filter(locale => locale.quality > 0)
.sort((a, b) => b.quality - a.quality);
}
/**
* Resolves the best locale from multiple sources
*/
resolveFromRequest(options: {
acceptLanguage?: string;
cookie?: string;
urlPath?: string;
queryParam?: string;
userPreference?: string;
}): LocaleMatchResult & { sourceLocale: string } {
const preferences: { locale: string; priority: number }[] = [];
// Highest priority: explicit user preference
if (options.userPreference) {
preferences.push({ locale: options.userPreference, priority: 100 });
}
// Query parameter
if (options.queryParam) {
preferences.push({ locale: options.queryParam, priority: 90 });
}
// Cookie
if (options.cookie) {
preferences.push({ locale: options.cookie, priority: 80 });
}
// URL path
if (options.urlPath) {
const urlLocale = this.extractLocaleFromPath(options.urlPath);
if (urlLocale) {
preferences.push({ locale: urlLocale, priority: 70 });
}
}
// Accept-Language header
if (options.acceptLanguage) {
const locales = this.parseAcceptLanguage(options.acceptLanguage);
for (const locale of locales) {
preferences.push({ locale: locale.code, priority: locale.quality * 60 });
}
}
// Sort by priority
preferences.sort((a, b) => b.priority - a.priority);
// Try to match
const localePrefs = preferences.map(p => p.locale);
const result = this.fallbackChain.resolve(localePrefs);
return {
...result,
sourceLocale: preferences[0]?.locale || this.config.defaultLocale
};
}
/**
* Extracts locale from URL path
*/
extractLocaleFromPath(path: string): string | null {
const match = path.match(/^\/([a-z]{2}(-[A-Z]{2})?)(\/|$)/i);
return match ? match[1] : null;
}
/**
* Gets locale-specific URL
*/
localizePath(path: string, locale: string): string {
const normalized = this.fallbackChain.normalizeLocale(locale);
const currentLocale = this.extractLocaleFromPath(path);
let cleanPath = path;
if (currentLocale) {
cleanPath = path.replace(`/${currentLocale}`, '') || '/';
}
// Don't prefix default locale if configured that way
if (normalized === this.config.defaultLocale) {
return cleanPath;
}
return `/${normalized}${cleanPath === '/' ? '' : cleanPath}`;
}
getFallbackChain(): FallbackChain {
return this.fallbackChain;
}
}
src/core/CanonicalArbiter.tsimport type { LocaleConfig, CanonicalResult, AlternateLink } from './types';
import { LocaleResolver } from './LocaleResolver';
import { FallbackChain } from './FallbackChain';
export class CanonicalArbiter {
private resolver: LocaleResolver;
private fallbackChain: FallbackChain;
private config: LocaleConfig;
private baseUrl: string;
constructor(config: LocaleConfig, baseUrl: string) {
this.config = config;
this.baseUrl = baseUrl.replace(/\/$/, '');
this.fallbackChain = new FallbackChain(config);
this.resolver = new LocaleResolver(config);
}
/**
* Determines canonical URL for multilingual content
*/
arbitrate(options: {
path: string;
requestedLocale?: string;
contentLocales?: string[];
acceptLanguage?: string;
}): CanonicalResult {
const { path, requestedLocale, contentLocales, acceptLanguage } = options;
// Determine available locales for this content
const availableLocales = contentLocales || this.config.supportedLocales;
// Resolve the best locale
let matchedLocale: string;
let fallbackUsed = false;
let fallbackChainUsed: string[] = [];
if (requestedLocale) {
const chain = this.buildContentFallbackChain(requestedLocale, availableLocales);
fallbackChainUsed = chain;
matchedLocale = chain[0];
fallbackUsed = chain.length > 1;
} else if (acceptLanguage) {
const locales = this.resolver.parseAcceptLanguage(acceptLanguage);
for (const locale of locales) {
const chain = this.buildContentFallbackChain(locale.code, availableLocales);
if (chain.length > 0) {
matchedLocale = chain[0];
fallbackChainUsed = chain;
fallbackUsed = chain.length > 1 && chain[0] !== locale.code;
break;
}
}
}
// Default fallback
if (!matchedLocale) {
const defaultChain = this.buildContentFallbackChain(
this.config.defaultLocale,
availableLocales
);
matchedLocale = defaultChain[0] || this.config.defaultLocale;
fallbackChainUsed = defaultChain;
fallbackUsed = defaultChain.length > 0 && defaultChain[0] !== this.config.defaultLocale;
}
// Determine canonical locale (most specific available translation)
const canonicalLocale = this.determineCanonicalLocale(availableLocales);
// Build URLs
const canonicalPath = this.resolver.localizePath(path, canonicalLocale);
const canonicalUrl = `${this.baseUrl}${canonicalPath}`;
// Build alternates
const alternates = this.buildAlternates(path, availableLocales, canonicalLocale);
return {
canonicalUrl,
canonicalLocale,
alternates,
matchedLocale,
fallbackUsed,
fallbackChain: fallbackChainUsed
};
}
/**
* Builds fallback chain constrained by available content
*/
private buildContentFallbackChain(
requestedLocale: string,
availableLocales: string[]
): string[] {
const fullChain = this.fallbackChain.buildChain(requestedLocale);
const result: string[] = [];
for (const locale of fullChain) {
// Exact match
if (availableLocales.includes(locale)) {
result.push(locale);
continue;
}
// Check if any available locale has same language
const lang = this.fallbackChain.extractLanguage(locale);
const langMatch = availableLocales.find(
a => this.fallbackChain.extractLanguage(a) === lang
);
if (langMatch && !result.includes(langMatch)) {
result.push(langMatch);
}
}
// Ensure default is included
if (result.length === 0 && availableLocales.length > 0) {
result.push(availableLocales[0]);
}
return [...new Set(result)];
}
/**
* Determines canonical locale for content
*/
private determineCanonicalLocale(availableLocales: string[]): string {
// Prefer the original/default locale if available
if (availableLocales.includes(this.config.defaultLocale)) {
return this.config.defaultLocale;
}
// Find most complete translation (locale with most specific match)
for (const locale of availableLocales) {
if (locale.includes('-')) {
return locale;
}
}
return availableLocales[0] || this.config.defaultLocale;
}
/**
* Builds alternate link headers
*/
private buildAlternates(
path: string,
availableLocales: string[],
canonicalLocale: string
): AlternateLink[] {
return availableLocales.map(locale => {
const localizedPath = this.resolver.localizePath(path, locale);
return {
locale,
url: `${this.baseUrl}${localizedPath}`,
hrefLang: locale,
isDefault: locale === canonicalLocale
};
});
}
/**
* Generates hreflang tags for HTML head
*/
generateHreflangTags(result: CanonicalResult): string {
const tags: string[] = [];
// Add x-default
tags.push(`<link rel="alternate" hreflang="x-default" href="${result.canonicalUrl}" />`);
// Add alternates
for (const alt of result.alternates) {
tags.push(`<link rel="alternate" hreflang="${alt.hrefLang}" href="${alt.url}" />`);
}
// Add canonical
tags.push(`<link rel="canonical" href="${result.canonicalUrl}" />`);
return tags.join('\n');
}
/**
* Validates locale consistency across page
*/
validateLocaleConsistency(page: {
htmlLang: string;
contentLanguage: string;
canonical: string;
alternates: AlternateLink[];
}): { valid: boolean; issues: string[] } {
const issues: string[] = [];
// Check html lang matches content
if (page.htmlLang !== page.contentLanguage) {
issues.push(`html lang (${page.htmlLang}) doesn't match Content-Language (${page.contentLanguage})`);
}
// Check canonical is in alternates
const canonicalInAlternates = page.alternates.some(
a => a.url === page.canonical && a.isDefault
);
if (!canonicalInAlternates) {
issues.push('Canonical URL not properly marked in alternates');
}
// Check for duplicate hreflangs
const hrefLangs = page.alternates.map(a => a.hrefLang);
const duplicates = hrefLangs.filter((h, i) => hrefLangs.indexOf(h) !== i);
if (duplicates.length > 0) {
issues.push(`Duplicate hreflangs: ${duplicates.join(', ')}`);
}
return {
valid: issues.length === 0,
issues
};
}
}
src/content/TranslationStore.tsimport type { TranslationEntry } from '../core/types';
import { FallbackChain } from '../core/FallbackChain';
export class TranslationStore {
private translations: Map<string, TranslationEntry> = new Map();
private fallbackChain: FallbackChain;
private defaultLocale: string;
constructor(fallbackChain: FallbackChain, defaultLocale: string) {
this.fallbackChain = fallbackChain;
this.defaultLocale = defaultLocale;
}
/**
* Adds a translation entry
*/
add(entry: TranslationEntry): void {
const key = this.makeKey(entry.key, entry.locale, entry.context);
this.translations.set(key, entry);
}
/**
* Adds multiple translations
*/
addAll(entries: TranslationEntry[]): void {
for (const entry of entries) {
this.add(entry);
}
}
/**
* Gets translation with fallback chain
*/
get(key: string, locale: string, context?: string): string | null {
const chain = this.fallbackChain.buildChain(locale);
for (const chainLocale of chain) {
const lookupKey = this.makeKey(key, chainLocale, context);
const entry = this.translations.get(lookupKey);
if (entry) {
return entry.value;
}
}
return null;
}
/**
* Gets translation with interpolation
*/
translate(
key: string,
locale: string,
params: Record<string, string | number> = {},
context?: string
): string {
let value = this.get(key, locale, context);
if (!value) {
return key; // Return key as fallback
}
// Interpolate parameters
for (const [paramKey, paramValue] of Object.entries(params)) {
value = value.replace(new RegExp(`\\{${paramKey}\\}`, 'g'), String(paramValue));
}
return value;
}
/**
* Gets plural translation
*/
translatePlural(
key: string,
locale: string,
count: number,
params: Record<string, string | number> = {}
): string {
const pluralForm = this.getPluralForm(count, locale);
const pluralKey = `${key}.${pluralForm}`;
return this.translate(pluralKey, locale, { ...params, count });
}
/**
* Determines plural form based on locale rules
*/
private getPluralForm(count: number, locale: string): string {
const lang = locale.split('-')[0];
// Common plural rules
const rules: Record<string, (n: number) => string> = {
en: (n) => n === 1 ? 'one' : 'other',
fr: (n) => n <= 1 ? 'one' : 'other',
ru: (n) => {
const mod10 = n % 10;
const mod100 = n % 100;
if (mod10 === 1 && mod100 !== 11) return 'one';
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 10 || mod100 >= 20)) return 'few';
return 'other';
},
ar: (n) => {
if (n === 0) return 'zero';
if (n === 1) return 'one';
if (n === 2) return 'two';
if (n >= 3 && n <= 10) return 'few';
if (n >= 11 && n <= 99) return 'many';
return 'other';
},
zh: () => 'other',
ja: () => 'other'
};
const rule = rules[lang] || rules.en;
return rule(count);
}
/**
* Checks if translation exists
*/
has(key: string, locale: string, context?: string): boolean {
const chain = this.fallbackChain.buildChain(locale);
for (const chainLocale of chain) {
const lookupKey = this.makeKey(key, chainLocale, context);
if (this.translations.has(lookupKey)) {
return true;
}
}
return false;
}
/**
* Gets all available locales for a key
*/
getAvailableLocales(key: string): string[] {
const locales: string[] = [];
for (const [k, entry] of this.translations) {
if (entry.key === key) {
locales.push(entry.locale);
}
}
return locales;
}
private makeKey(key: string, locale: string, context?: string): string {
return context ? `${locale}:${context}:${key}` : `${locale}:${key}`;
}
}
src/content/MixedLanguagePage.tsimport type { ContentSegment, MixedLanguagePage as IMixedLanguagePage } from '../core/types';
export class MixedLanguagePageBuilder {
private id: string;
private defaultLocale: string;
private segments: ContentSegment[] = [];
constructor(id: string, defaultLocale: string) {
this.id = id;
this.defaultLocale = defaultLocale;
}
/**
* Adds a content segment
*/
addSegment(segment: Omit<ContentSegment, 'isTranslatable'> & { isTranslatable?: boolean }): this {
this.segments.push({
...segment,
isTranslatable: segment.isTranslatable ?? true
});
return this;
}
/**
* Builds the mixed language page
*/
build(): IMixedLanguagePage {
const availableLocales = this.getAvailableLocales();
const canonicalLocale = this.determineCanonicalLocale();
return {
id: this.id,
defaultLocale: this.defaultLocale,
segments: this.segments,
availableLocales,
canonicalLocale
};
}
/**
* Gets all locales used in segments
*/
private getAvailableLocales(): string[] {
const locales = new Set<string>();
locales.add(this.defaultLocale);
for (const segment of this.segments) {
locales.add(segment.locale);
}
return Array.from(locales);
}
/**
* Determines canonical locale based on content analysis
*/
private determineCanonicalLocale(): string {
// Count segment locales
const localeCounts = new Map<string, number>();
for (const segment of this.segments) {
const count = localeCounts.get(segment.locale) || 0;
localeCounts.set(segment.locale, count + 1);
}
// Find dominant locale
let dominantLocale = this.defaultLocale;
let maxCount = 0;
for (const [locale, count] of localeCounts) {
if (count > maxCount) {
maxCount = count;
dominantLocale = locale;
}
}
return dominantLocale;
}
}
export class MixedLanguageRenderer {
/**
* Renders a mixed language page for a target locale
*/
render(
page: IMixedLanguagePage,
targetLocale: string,
translator: (key: string, locale: string) => string | null
): { content: string; usedLocales: Map<string, number>; warnings: string[] } {
const warnings: string[] = [];
const usedLocales = new Map<string, number>();
const renderedSegments: string[] = [];
for (const segment of page.segments) {
let renderedContent: string;
let usedLocale: string;
if (segment.isTranslatable && segment.locale !== targetLocale) {
// Try to translate
const translated = translator(segment.content, targetLocale);
if (translated) {
renderedContent = translated;
usedLocale = targetLocale;
} else {
// Keep original with warning
renderedContent = segment.content;
usedLocale = segment.locale;
warnings.push(
`Segment "${segment.field}" not available in ${targetLocale}, using ${segment.locale}`
);
}
} else {
renderedContent = segment.content;
usedLocale = segment.locale;
}
renderedSegments.push(renderedContent);
const count = usedLocales.get(usedLocale) || 0;
usedLocales.set(usedLocale, count + 1);
}
return {
content: renderedSegments.join('\n'),
usedLocales,
warnings
};
}
/**
* Detects language mixing issues
*/
analyzeMixedLanguage(page: IMixedLanguagePage): {
issues: string[];
recommendations: string[];
primaryLocale: string;
mixingRatio: number;
} {
const issues: string[] = [];
const recommendations: string[] = [];
const localeCounts = new Map<string, number>();
// Count by locale
for (const segment of this.segments) {
const count = localeCounts.get(segment.locale) || 0;
localeCounts.set(segment.locale, count + 1);
}
// Find primary
let primaryLocale = page.defaultLocale;
let primaryCount = 0;
let totalSegments = page.segments.length;
for (const [locale, count] of localeCounts) {
if (count > primaryCount) {
primaryCount = count;
primaryLocale = locale;
}
}
// Calculate mixing ratio
const mixingRatio = totalSegments > 0 ? 1 - (primaryCount / totalSegments) : 0;
// Detect issues
if (mixingRatio > 0.3) {
issues.push(`High language mixing detected: ${(mixingRatio * 100).toFixed(1)}% of content is in secondary languages`);
recommendations.push(`Consider translating more content to ${primaryLocale}`);
}
// Check for untranslated translatable segments
const untranslatedTranslatable = page.segments.filter(
s => s.isTranslatable && s.locale !== page.defaultLocale
);
if (untranslatedTranslatable.length > 0) {
issues.push(`${untranslatedTranslatable.length} translatable segments are not in the default locale`);
}
// Check for inconsistent locale usage in same fields
const fieldLocales = new Map<string, Set<string>>();
for (const segment of page.segments) {
if (!fieldLocales.has(segment.field)) {
fieldLocales.set(segment.field, new Set());
}
fieldLocales.get(segment.field)!.add(segment.locale);
}
for (const [field, locales] of fieldLocales) {
if (locales.size > 1) {
issues.push(`Field "${field}" has inconsistent locale usage: ${Array.from(locales).join(', ')}`);
recommendations.push(`Standardize field "${field}" to use a single locale per page`);
}
}
return {
issues,
recommendations,
primaryLocale,
mixingRatio
};
}
private get segments(): ContentSegment[] {
// This would typically be stored, but for analysis we access the page directly
return [];
}
}
export function createMixedLanguagePage(
id: string,
defaultLocale: string
): MixedLanguagePageBuilder {
return new MixedLanguagePageBuilder(id, defaultLocale);
}
src/index.tsexport { FallbackChain } from './core/FallbackChain';
export { LocaleResolver } from './core/LocaleResolver';
export { CanonicalArbiter } from './core/CanonicalArbiter';
export { TranslationStore } from './content/TranslationStore';
export {
MixedLanguagePageBuilder,
MixedLanguageRenderer,
createMixedLanguagePage
} from './content/MixedLanguagePage';
export type {
Locale,
LocaleConfig,
CanonicalResult,
AlternateLink,
ContentSegment,
MixedLanguagePage,
TranslationEntry,
LocaleMatchResult
} from './core/types';
// Default configuration factory
export function createDefaultConfig(
supportedLocales: string[],
defaultLocale: string
): import('./core/types').LocaleConfig {
const fallbackChain: Record<string, string[]> = {};
for (const locale of supportedLocales) {
const lang = locale.split('-')[0];
if (!fallbackChain[locale]) {
fallbackChain[locale] = [];
}
// Add language-only fallback if different
if (lang !== locale) {
const langOnly = supportedLocales.find(l => l === lang);
if (langOnly && !fallbackChain[locale].includes(langOnly)) {
fallbackChain[locale].push(langOnly);
}
}
// Add default if not already there
if (locale !== defaultLocale) {
fallbackChain[locale].push(defaultLocale);
}
}
return {
defaultLocale,
supportedLocales,
fallbackChain,
aliases: {
'en-us': 'en-US',
'en-gb': 'en-GB',
'zh-cn': 'zh-CN',
'zh-tw': 'zh-TW',
'pt-br': 'pt-BR'
}
};
}
tests/localeResolver.test.tsimport { describe, it, expect } from 'vitest';
import { LocaleResolver } from '../src/core/LocaleResolver';
import { createDefaultConfig } from '../src';
describe('LocaleResolver', () => {
const config = createDefaultConfig(
['en-US', 'en-GB', 'es-ES', 'es-MX', 'fr-FR', 'zh-CN'],
'en-US'
);
const resolver = new LocaleResolver(config);
describe('parseAcceptLanguage', () => {
it('should parse simple Accept-Language header', () => {
const result = resolver.parseAcceptLanguage('en-US');
expect(result).toHaveLength(1);
expect(result[0].code).toBe('en-US');
expect(result[0].quality).toBe(1);
});
it('should parse complex Accept-Language header', () => {
const result = resolver.parseAcceptLanguage('en-US,en;q=0.9,es;q=0.8,fr;q=0.7');
expect(result).toHaveLength(4);
expect(result[0].code).toBe('en-US');
expect(result[0].quality).toBe(1);
expect(result[1].code).toBe('en');
expect(result[1].quality).toBe(0.9);
});
it('should handle empty header', () => {
const result = resolver.parseAcceptLanguage('');
expect(result).toHaveLength(0);
});
it('should sort by quality descending', () => {
const result = resolver.parseAcceptLanguage('fr;q=0.5,en;q=0.9,es;q=0.7');
expect(result[0].code).toBe('en');
expect(result[1].code).toBe('es');
expect(result[2].code).toBe('fr');
});
});
describe('resolveFromRequest', () => {
it('should prioritize user preference', () => {
const result = resolver.resolveFromRequest({
userPreference: 'fr-FR',
acceptLanguage: 'en-US',
cookie: 'es-ES'
});
expect(result.matched).toBe('fr-FR');
expect(result.source).toBe('exact');
});
it('should use fallback when preference not supported', () => {
const result = resolver.resolveFromRequest({
userPreference: 'de-DE', // Not supported
acceptLanguage: 'en-US'
});
expect(result.matched).toBe('en-US');
expect(result.fallbackUsed).toBe(true);
});
it('should fallback to language match', () => {
const result = resolver.resolveFromRequest({
acceptLanguage: 'es-AR;q=0.9' // Not directly supported, but 'es' is
});
expect(result.matched).toBe('es-ES');
expect(result.source).toBe('language');
});
});
describe('localizePath', () => {
it('should add locale prefix to path', () => {
expect(resolver.localizePath('/about', 'fr-FR')).toBe('/fr-FR/about');
});
it('should replace existing locale prefix', () => {
expect(resolver.localizePath('/en-US/about', 'fr-FR')).toBe('/fr-FR/about');
});
it('should not prefix default locale', () => {
expect(resolver.localizePath('/about', 'en-US')).toBe('/about');
});
it('should handle root path', () => {
expect(resolver.localizePath('/', 'fr-FR')).toBe('/fr-FR');
});
});
});
tests/fallbackChain.test.tsimport { describe, it, expect } from 'vitest';
import { FallbackChain } from '../src/core/FallbackChain';
describe('FallbackChain', () => {
const chain = new FallbackChain({
defaultLocale: 'en-US',
supportedLocales: ['en-US', 'en-GB', 'es-ES', 'es-MX', 'fr-FR', 'pt-BR'],
fallbackChain: {
'en-AU': ['en-GB', 'en-US'],
'es-AR': ['es-MX', 'es-ES'],
'fr-CA': ['fr-FR']
},
aliases: {
'en-us': 'en-US',
'es': 'es-ES'
}
});
describe('buildChain', () => {
it('should build chain for supported locale', () => {
const result = chain.buildChain('en-US');
expect(result[0]).toBe('en-US');
expect(result).toContain('en-GB'); // Sibling locale
});
it('should build chain with explicit fallbacks', () => {
const result = chain.buildChain('en-AU');
expect(result[0]).toBe('en-GB');
expect(result[1]).toBe('en-US');
});
it('should include default as final fallback', () => {
const result = chain.buildChain('zh-CN'); // Not supported
expect(result[result.length - 1]).toBe('en-US');
});
it('should include language siblings', () => {
const result = chain.buildChain('es-MX');
expect(result).toContain('es-ES');
});
});
describe('resolve', () => {
it('should find exact match', () => {
const result = chain.resolve(['fr-FR', 'en-US']);
expect(result.matched).toBe('fr-FR');
expect(result.source).toBe('exact');
expect(result.confidence).toBe(1);
});
it('should find language match', () => {
const result = chain.resolve(['pt-PT']); // Portuguese Portugal, only BR available
expect(result.matched).toBe('pt-BR');
expect(result.source).toBe('language');
expect(result.confidence).toBe(0.8);
});
it('should use fallback when available', () => {
const result = chain.resolve(['es-AR']); // Has explicit fallback
expect(result.matched).toBe('es-MX');
expect(result.source).toBe('fallback');
});
it('should default when no match', () => {
const result = chain.resolve(['ja-JP', 'ko-KR']); // None supported
expect(result.matched).toBe('en-US');
expect(result.source).toBe('default');
expect(result.confidence).toBe(0.1);
});
});
describe('normalizeLocale', () => {
it('should apply aliases', () => {
expect(chain.normalizeLocale('en-us')).toBe('en-US');
});
it('should normalize format', () => {
expect(chain.normalizeLocale('EN_us')).toBe('en-US');
});
it('should handle language-only', () => {
expect(chain.normalizeLocale('en')).toBe('en');
});
});
describe('getSiblingLocales', () => {
it('should return locales with same language', () => {
const siblings = chain.getSiblingLocales('en-AU');
expect(siblings).toContain('en-US');
expect(siblings).toContain('en-GB');
expect(siblings).not.toContain('es-ES');
});
});
});
tests/canonicalArbiter.test.tsimport { describe, it, expect } from 'vitest';
import { CanonicalArbiter } from '../src/core/CanonicalArbiter';
import { createDefaultConfig } from '../src';
describe('CanonicalArbiter', () => {
const config = createDefaultConfig(
['en-US', 'en-GB', 'es-ES', 'fr-FR'],
'en-US'
);
const arbiter = new CanonicalArbiter(config, 'https://example.com');
describe('arbitrate', () => {
it('should return canonical for default locale', () => {
const result = arbiter.arbitrate({
path: '/about',
requestedLocale: 'en-US'
});
expect(result.canonicalUrl).toBe('https://example.com/about');
expect(result.canonicalLocale).toBe('en-US');
expect(result.matchedLocale).toBe('en-US');
expect(result.fallbackUsed).toBe(false);
});
it('should localize URL for non-default locale', () => {
const result = arbiter.arbitrate({
path: '/about',
requestedLocale: 'fr-FR'
});
expect(result.canonicalUrl).toBe('https://example.com/fr-FR/about');
});
it('should handle fallback scenario', () => {
const result = arbiter.arbitrate({
path: '/about',
requestedLocale: 'en-AU', // Not supported
contentLocales: ['en-US', 'fr-FR']
});
expect(result.matchedLocale).toBe('en-US');
expect(result.fallbackUsed).toBe(true);
expect(result.fallbackChain).toContain('en-US');
});
it('should build correct alternates', () => {
const result = arbiter.arbitrate({
path: '/about',
contentLocales: ['en-US', 'es-ES', 'fr-FR']
});
expect(result.alternates).toHaveLength(3);
expect(result.alternates.find(a => a.locale === 'en-US')?.isDefault).toBe(true);
expect(result.alternates.find(a => a.locale === 'es-ES')?.url).toBe('https://example.com/es-ES/about');
});
it('should handle Accept-Language header', () => {
const result = arbiter.arbitrate({
path: '/about',
acceptLanguage: 'fr-FR,en-US;q=0.9'
});
expect(result.matchedLocale).toBe('fr-FR');
});
it('should respect content locale constraints', () => {
const result = arbiter.arbitrate({
path: '/about',
requestedLocale: 'es-ES',
contentLocales: ['en-US', 'fr-FR'] // No Spanish available
});
// Should fallback through chain
expect(result.matchedLocale).not.toBe('es-ES');
expect(result.fallbackUsed).toBe(true);
});
});
describe('generateHreflangTags', () => {
it('should generate proper hreflang tags', () => {
const result = arbiter.arbitrate({
path: '/about',
contentLocales: ['en-US', 'es-ES', 'fr-FR']
});
const tags = arbiter.generateHreflangTags(result);
expect(tags).toContain('hreflang="x-default"');
expect(tags).toContain('hreflang="en-US"');
expect(tags).toContain('hreflang="es-ES"');
expect(tags).toContain('rel="canonical"');
});
});
describe('validateLocaleConsistency', () => {
it('should detect consistent page', () => {
const result = arbiter.arbitrate({
path: '/about',
contentLocales: ['en-US', 'es-ES']
});
const validation = arbiter.validateLocaleConsistency({
htmlLang: 'en-US',
contentLanguage: 'en-US',
canonical: result.canonicalUrl,
alternates: result.alternates
});
expect(validation.valid).toBe(true);
expect(validation.issues).toHaveLength(0);
});
it('should detect mismatched html lang', () => {
const validation = arbiter.validateLocaleConsistency({
htmlLang: 'en-US',
contentLanguage: 'es-ES',
canonical: 'https://example.com/about',
alternates: []
});
expect(validation.valid).toBe(false);
expect(validation.issues).toContain(
'html lang (en-US) doesn\'t match Content-Language (es-ES)'
);
});
it('should detect duplicate hreflangs', () => {
const validation = arbiter.validateLocaleConsistency({
htmlLang: 'en-US',
contentLanguage: 'en-US',
canonical: 'https://example.com/about',
alternates: [
{ locale: 'en-US', url: 'https://example.com/about', hrefLang: 'en-US', isDefault: true },
{ locale: 'en-GB', url: 'https://example.com/en-GB/about', hrefLang: 'en-US', isDefault: false }
]
});
expect(validation.valid).toBe(false);
expect(validation.issues.some(i => i.includes('Duplicate'))).toBe(true);
});
});
});
tests/mixedLanguage.test.tsimport { describe, it, expect } from 'vitest';
import {
MixedLanguagePageBuilder,
MixedLanguageRenderer,
createMixedLanguagePage
} from '../src/content/MixedLanguagePage';
describe('MixedLanguagePage', () => {
describe('MixedLanguagePageBuilder', () => {
it('should build a mixed language page', () => {
const page = createMixedLanguagePage('page-1', 'en-US')
.addSegment({
locale: 'en-US',
content: 'Hello World',
field: 'title'
})
.addSegment({
locale: 'es-ES',
content: 'Un producto',
field: 'product_name'
})
.build();
expect(page.id).toBe('page-1');
expect(page.defaultLocale).toBe('en-US');
expect(page.segments).toHaveLength(2);
expect(page.availableLocales).toContain('en-US');
expect(page.availableLocales).toContain('es-ES');
});
it('should determine canonical locale by dominant content', () => {
const page = createMixedLanguagePage('page-2', 'en-US')
.addSegment({ locale: 'en-US', content: 'Title', field: 'title' })
.addSegment({ locale: 'en-US', content: 'Description', field: 'description' })
.addSegment({ locale: 'es-ES', content: 'Producto', field: 'product' })
.build();
expect(page.canonicalLocale).toBe('en-US');
});
it('should mark segments as translatable by default', () => {
const page = createMixedLanguagePage('page-3', 'en-US')
.addSegment({ locale: 'en-US', content: 'Content', field: 'body' })
.build();
expect(page.segments[0].isTranslatable).toBe(true);
});
it('should allow marking segments as non-translatable', () => {
const page = createMixedLanguagePage('page-4', 'en-US')
.addSegment({
locale: 'en-US',
content: 'Brand Name',
field: 'brand',
isTranslatable: false
})
.build();
expect(page.segments[0].isTranslatable).toBe(false);
});
});
describe('MixedLanguageRenderer', () => {
const renderer = new MixedLanguageRenderer();
it('should render page for target locale', () => {
const page = createMixedLanguagePage('page-1', 'en-US')
.addSegment({ locale: 'en-US', content: 'Title', field: 'title' })
.addSegment({ locale: 'es-ES', content: 'Descripción', field: 'description' })
.build();
const translator = (content: string, locale: string) => {
if (locale === 'es-ES' && content === 'Title') return 'Título';
if (locale === 'en-US' && content === 'Descripción') return 'Description';
return null;
};
const result = renderer.render(page, 'es-ES', translator);
expect(result.content).toContain('Título');
expect(result.usedLocales.has('es-ES')).toBe(true);
});
it('should generate warnings for missing translations', () => {
const page = createMixedLanguagePage('page-1', 'en-US')
.addSegment({ locale: 'en-US', content: 'Untranslated', field: 'title' })
.build();
const result = renderer.render(page, 'fr-FR', () => null);
expect(result.warnings).toHaveLength(1);
expect(result.warnings[0]).toContain('not available in fr-FR');
});
it('should keep non-translatable segments unchanged', () => {
const page = createMixedLanguagePage('page-1', 'en-US')
.addSegment({
locale: 'en-US',
content: 'BrandXYZ',
field: 'brand',
isTranslatable: false
})
.build();
const result = renderer.render(page, 'es-ES', () => 'Translated');
expect(result.content).toContain('BrandXYZ');
expect(result.content).not.toContain('Translated');
});
});
});
tests/translationStore.test.tsimport { describe, it, expect, beforeEach } from 'vitest';
import { TranslationStore } from '../src/content/TranslationStore';
import { FallbackChain } from '../src/core/FallbackChain';
describe('TranslationStore', () => {
let store: TranslationStore;
beforeEach(() => {
const fallbackChain = new FallbackChain({
defaultLocale: 'en-US',
supportedLocales: ['en-US', 'en-GB', 'es-ES', 'fr-FR'],
fallbackChain: {
'en-GB': ['en-US'],
'es-MX': ['es-ES']
},
aliases: {}
});
store = new TranslationStore(fallbackChain, 'en-US');
// Add test translations
store.addAll([
{ key: 'greeting', value: 'Hello', locale: 'en-US' },
{ key: 'greeting', value: 'Hiya', locale: 'en-GB' },
{ key: 'greeting', value: 'Hola', locale: 'es-ES' },
{ key: 'greeting', value: 'Bonjour', locale: 'fr-FR' },
{ key: 'farewell', value: 'Goodbye', locale: 'en-US' },
{ key: 'items.one', value: '{count} item', locale: 'en-US' },
{ key: 'items.other', value: '{count} items', locale: 'en-US' },
{ key: 'items.one', value: '{count} artículo', locale: 'es-ES' },
{ key: 'items.other', value: '{count} artículos', locale: 'es-ES' },
]);
});
describe('get', () => {
it('should get exact locale translation', () => {
expect(store.get('greeting', 'es-ES')).toBe('Hola');
expect(store.get('greeting', 'fr-FR')).toBe('Bonjour');
});
it('should fallback through chain', () => {
// en-AU -> en-GB -> en-US
expect(store.get('greeting', 'en-AU')).toBe('Hello'); // Falls back to en-US
});
it('should return null for missing translation', () => {
expect(store.get('nonexistent', 'en-US')).toBe(null);
});
});
describe('translate', () => {
it('should interpolate parameters', () => {
store.add({ key: 'welcome', value: 'Welcome, {name}!', locale: 'en-US' });
expect(store.translate('welcome', 'en-US', { name: 'John' })).toBe('Welcome, John!');
});
it('should return key for missing translation', () => {
expect(store.translate('missing.key', 'en-US')).toBe('missing.key');
});
it('should handle multiple parameters', () => {
store.add({
key: 'message',
value: '{greeting} {name}, you have {count} messages',
locale: 'en-US'
});
const result = store.translate('message', 'en-US', {
greeting: 'Hello',
name: 'Alice',
count: 5
});
expect(result).toBe('Hello Alice, you have 5 messages');
});
});
describe('translatePlural', () => {
it('should select correct plural form', () => {
expect(store.translatePlural('items', 'en-US', 1)).toBe('1 item');
expect(store.translatePlural('items', 'en-US', 5)).toBe('5 items');
});
it('should handle locale-specific plural rules', () => {
expect(store.translatePlural('items', 'es-ES', 1)).toBe('1 artículo');
expect(store.translatePlural('items', 'es-ES', 5)).toBe('5 artículos');
});
});
describe('has', () => {
it('should check translation existence', () => {
expect(store.has('greeting', 'en-US')).toBe(true);
expect(store.has('greeting', 'de-DE')).toBe(false);
});
it('should consider fallback chain', () => {
// en-AU falls back to en-US which has the translation
expect(store.has('greeting', 'en-AU')).toBe(true);
});
});
describe('getAvailableLocales', () => {
it('should list all locales for a key', () => {
const locales = store.getAvailableLocales('greeting');
expect(locales).toContain('en-US');
expect(locales).toContain('en-GB');
expect(locales).toContain('es-ES');
expect(locales).toContain('fr-FR');
});
});
});
tests/integration.test.tsimport { describe, it, expect } from 'vitest';
import {
CanonicalArbiter,
LocaleResolver,
TranslationStore,
FallbackChain,
createDefaultConfig,
createMixedLanguagePage,
MixedLanguageRenderer
} from '../src';
describe('Integration Tests', () => {
describe('E-commerce Product Page Scenario', () => {
const config = createDefaultConfig(
['en-US', 'en-GB', 'es-ES', 'fr-FR', 'de-DE'],
'en-US'
);
const fallbackChain = new FallbackChain(config);
const resolver = new LocaleResolver(config);
const arbiter = new CanonicalArbiter(config, 'https://shop.example.com');
const translationStore = new TranslationStore(fallbackChain, 'en-US');
// Setup translations
translationStore.addAll([
{ key: 'product.price', value: '${amount}', locale: 'en-US' },
{ key: 'product.price', value: '£{amount}', locale: 'en-GB' },
{ key: 'product.price', value: '{amount} €', locale: 'es-ES' },
{ key: 'product.price', value: '{amount} €', locale: 'fr-FR' },
{ key: 'product.addToCart', value: 'Add to Cart', locale: 'en-US' },
{ key: 'product.addToCart', value: 'Add to Basket', locale: 'en-GB' },
{ key: 'product.addToCart', value: 'Añadir al carrito', locale: 'es-ES' },
]);
it('should handle US English visitor', () => {
const canonicalResult = arbiter.arbitrate({
path: '/products/widget',
requestedLocale: 'en-US',
contentLocales: ['en-US', 'es-ES']
});
const price = translationStore.translate('product.price', 'en-US', { amount: '29.99' });
const button = translationStore.translate('product.addToCart', 'en-US');
expect(canonicalResult.canonicalUrl).toBe('https://shop.example.com/products/widget');
expect(canonicalResult.matchedLocale).toBe('en-US');
expect(price).toBe('$29.99');
expect(button).toBe('Add to Cart');
});
it('should handle UK English visitor with fallback', () => {
const canonicalResult = arbiter.arbitrate({
path: '/products/widget',
requestedLocale: 'en-GB',
contentLocales: ['en-US', 'es-ES'] // No en-GB content
});
const price = translationStore.translate('product.price', 'en-GB', { amount: '24.99' });
// Should fallback to en-US for content, but use en-GB for UI
expect(canonicalResult.matchedLocale).toBe('en-US');
expect(canonicalResult.fallbackUsed).toBe(true);
expect(price).toBe('£24.99');
});
it('should handle Spanish visitor', () => {
const canonicalResult = arbiter.arbitrate({
path: '/products/widget',
acceptLanguage: 'es-ES,en-US;q=0.8'
});
expect(canonicalResult.matchedLocale).toBe('es-ES');
expect(canonicalResult.canonicalUrl).toBe('https://shop.example.com/es-ES/products/widget');
});
it('should generate proper hreflang tags', () => {
const result = arbiter.arbitrate({
path: '/products/widget',
contentLocales: ['en-US', 'es-ES', 'fr-FR']
});
const tags = arbiter.generateHreflangTags(result);
expect(tags).toContain('hreflang="x-default"');
expect(tags).toContain('hreflang="en-US"');
expect(tags).toContain('hreflang="es-ES"');
expect(tags).toContain('hreflang="fr-FR"');
});
});
describe('Mixed Language Blog Post Scenario', () => {
const renderer = new MixedLanguageRenderer();
it('should handle mixed language content with translations', () => {
const blogPage = createMixedLanguagePage('post-123', 'en-US')
.addSegment({ locale: 'en-US', content: 'Travel Diary', field: 'title' })
.addSegment({ locale: 'en-US', content: 'My trip to Paris...', field: 'intro' })
.addSegment({ locale: 'fr-FR', content: 'C\'était magnifique!', field: 'quote' })
.addSegment({ locale: 'en-US', content: 'The food was amazing', field: 'conclusion' })
.build();
const translator = (content: string, locale: string) => {
if (locale === 'es-ES') {
if (content === 'Travel Diary') return 'Diario de Viaje';
if (content === 'My trip to Paris...') return 'Mi viaje a París...';
if (content === 'The food was amazing') return 'La comida estaba increíble';
}
return null;
};
const result = renderer.render(blogPage, 'es-ES', translator);
expect(result.content).toContain('Diario de Viaje');
expect(result.content).toContain('Mi viaje a París...');
expect(result.warnings.some(w => w.includes('quote') && w.includes('fr-FR'))).toBe(true);
});
});
describe('Accept-Language Negotiation Scenario', () => {
const config = createDefaultConfig(
['en-US', 'es-ES', 'pt-BR', 'fr-FR'],
'en-US'
);
const resolver = new LocaleResolver(config);
it('should handle complex Accept-Language negotiation', () => {
// Brazilian Portuguese user
const result = resolver.resolveFromRequest({
acceptLanguage: 'pt-BR,pt;q=0.9,en;q=0.8'
});
expect(result.matched).toBe('pt-BR');
expect(result.source).toBe('exact');
});
it('should negotiate European Portuguese to Brazilian', () => {
const result = resolver.resolveFromRequest({
acceptLanguage: 'pt-PT,pt;q=0.9,en;q=0.8'
});
expect(result.matched).toBe('pt-BR');
expect(result.source).toBe('language');
expect(result.confidence).toBe(0.8);
});
it('should handle wildcard preference', () => {
const result = resolver.resolveFromRequest({
acceptLanguage: '*'
});
expect(result.matched).toBe('en-US');
expect(result.source).toBe('default');
});
});
describe('SEO Canonical Consistency Scenario', () => {
const config = createDefaultConfig(
['en-US', 'es-ES', 'fr-FR'],
'en-US'
);
const arbiter = new CanonicalArbiter(config, 'https://blog.example.com');
it('should ensure consistent canonical for duplicate content', () => {
// Multiple URLs for same content
const paths = ['/article', '/article/', '/article?id=123'];
const canonicals = paths.map(path =>
arbiter.arbitrate({ path, contentLocales: ['en-US', 'es-ES'] }).canonicalUrl
);
// All should have same canonical
expect(new Set(canonicals).size).toBe(1);
expect(canonicals[0]).toBe('https://blog.example.com/article');
});
it('should validate complete page setup', () => {
const result = arbiter.arbitrate({
path: '/article',
contentLocales: ['en-US', 'es-ES']
});
const validation = arbiter.validateLocaleConsistency({
htmlLang: 'en-US',
contentLanguage: 'en-US',
canonical: result.canonicalUrl,
alternates: result.alternates
});
expect(validation.valid).toBe(true);
});
});
});
package.json{
"name": "multilingual-canonical-arbitration",
"version": "1.0.0",
"description": "Multilingual canonical arbitration with locale fallbacks and mixed-language support",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"lint": "eslint src tests --ext .ts"
},
"devDependencies": {
"@types/node": "^20.10.0",
"typescript": "^5.3.0",
"vitest": "^1.0.0",
"@vitest/coverage-v8": "^1.0.0"
},
"keywords": [
"i18n",
"l10n",
"multilingual",
"canonical",
"seo",
"locale",
"internationalization"
],
"license": "MIT"
}
tsconfig.json{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"lib": ["ES2022"],
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"resolveJsonModule": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "tests"]
}
vitest.config.tsimport { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'node',
include: ['tests/**/*.test.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
include: ['src/**/*.ts'],
exclude: ['src/index.ts']
}
}
});
import {
CanonicalArbiter,
LocaleResolver,
TranslationStore,
FallbackChain,
createDefaultConfig,
createMixedLanguagePage,
MixedLanguageRenderer
} from 'multilingual-canonical-arbitration';
// Setup
const config = createDefaultConfig(
['en-US', 'en-GB', 'es-ES', 'fr-FR', 'de-DE', 'ja-JP'],
'en-US'
);
const arbiter = new CanonicalArbiter(config, 'https://example.com');
const resolver = new LocaleResolver(config);
// Handle incoming request
function handleRequest(req: {
path: string;
acceptLanguage?: string;
cookie?: string;
}) {
// Resolve locale
const localeResult = resolver.resolveFromRequest({
acceptLanguage: req.acceptLanguage,
cookie: req.cookie,
urlPath: req.path
});
// Get canonical info
const canonicalResult = arbiter.arbitrate({
path: req.path,
requestedLocale: localeResult.matched,
contentLocales: ['en-US', 'es-ES', 'fr-FR']
});
return {
locale: localeResult.matched,
canonicalUrl: canonicalResult.canonicalUrl,
hreflangTags: arbiter.generateHreflangTags(canonicalResult),
alternates: canonicalResult.alternates
};
}
This comprehensive system provides: