@oxog/i18n 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +133 -0
- package/dist/index.d.mts +91 -19
- package/dist/index.d.ts +91 -19
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +24 -9
package/README.md
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# @oxog/i18n
|
|
2
|
+
|
|
3
|
+
A small, dependency-free and framework-agnostic internationalization library with
|
|
4
|
+
TypeScript key checking, CLDR plural rules, fallback locales and an optional ICU
|
|
5
|
+
MessageFormat plugin.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @oxog/i18n
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Ships ESM and CommonJS builds with matching type declarations. Node.js 18+ and modern
|
|
14
|
+
browsers (it relies on `Intl.PluralRules`, `Intl.NumberFormat` and `structuredClone`).
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { createI18n } from '@oxog/i18n';
|
|
20
|
+
|
|
21
|
+
const i18n = createI18n({
|
|
22
|
+
locale: 'en',
|
|
23
|
+
fallbackLocale: 'en',
|
|
24
|
+
messages: {
|
|
25
|
+
en: { greeting: 'Hello, {{name}}!', messages: { welcome: 'Welcome to our app' } },
|
|
26
|
+
es: { greeting: '¡Hola, {{name}}!', messages: { welcome: 'Bienvenido a nuestra aplicación' } },
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
i18n.t('greeting', { name: 'World' }); // "Hello, World!"
|
|
31
|
+
i18n.t('messages.welcome'); // "Welcome to our app"
|
|
32
|
+
|
|
33
|
+
i18n.setLocale('es');
|
|
34
|
+
i18n.t('greeting', { name: 'Mundo' }); // "¡Hola, Mundo!"
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Options
|
|
38
|
+
|
|
39
|
+
| Option | Description |
|
|
40
|
+
| --- | --- |
|
|
41
|
+
| `locale` | Active locale (required). |
|
|
42
|
+
| `fallbackLocale` | Catalog used when a key is missing in the active locale. |
|
|
43
|
+
| `messages` | `{ [locale]: catalog }`; catalogs may nest objects (`user.profile.title`). |
|
|
44
|
+
| `plugins` | Plugins such as `icuPlugin` or `markdownPlugin`. |
|
|
45
|
+
| `pluralizationRules` | Custom rules per locale or language, e.g. `{ ar: count => ... }`. |
|
|
46
|
+
| `formats` | Named `Intl.NumberFormat` / `Intl.DateTimeFormat` options (`{{value:number}}`). |
|
|
47
|
+
| `warnOnMissingTranslations` | Log missing keys outside production. |
|
|
48
|
+
| `onError` | Called with errors from plugins, formatters and listeners. |
|
|
49
|
+
|
|
50
|
+
A missing key returns the key itself. Lookups only use own string values: nested groups,
|
|
51
|
+
`constructor`, `toString` and other `Object.prototype` members are never returned as
|
|
52
|
+
translations, and `__proto__` keys in loaded JSON cannot modify `Object.prototype`.
|
|
53
|
+
|
|
54
|
+
## Interpolation
|
|
55
|
+
|
|
56
|
+
`{{name}}` placeholders are replaced with the matching parameter; unknown placeholders are
|
|
57
|
+
left as they are. `t()` returns plain text and does not escape HTML: render it as text (React
|
|
58
|
+
does) or escape it before inserting it as HTML.
|
|
59
|
+
|
|
60
|
+
## Pluralization
|
|
61
|
+
|
|
62
|
+
Pass `count` and group the forms under the key. Categories follow the CLDR rules of the
|
|
63
|
+
catalog's language via `Intl.PluralRules` (`zero`, `one`, `two`, `few`, `many`, `other`), so
|
|
64
|
+
Russian, Polish, Arabic, Welsh and every other language select the right form. An explicit
|
|
65
|
+
`zero` form is used for `count: 0` when present, and `other` is the last resort.
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
const i18n = createI18n({
|
|
69
|
+
locale: 'ru',
|
|
70
|
+
messages: {
|
|
71
|
+
ru: { apples: { one: '{{count}} яблоко', few: '{{count}} яблока', many: '{{count}} яблок', other: '{{count}} яблока' } },
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
i18n.t('apples', { count: 21 }); // "21 яблоко"
|
|
75
|
+
i18n.t('apples', { count: 5 }); // "5 яблок"
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
When the text comes from the fallback catalog, the fallback language's rules are used.
|
|
79
|
+
|
|
80
|
+
## ICU MessageFormat plugin
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import { createI18n, icuPlugin } from '@oxog/i18n';
|
|
84
|
+
|
|
85
|
+
const i18n = createI18n({
|
|
86
|
+
locale: 'en',
|
|
87
|
+
plugins: [icuPlugin],
|
|
88
|
+
messages: {
|
|
89
|
+
en: { inbox: 'Hello, {name}! You have {count, plural, =0 {no messages} one {# message} other {# messages}}.' },
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
i18n.t('inbox', { name: 'Ada', count: 2 }); // "Hello, Ada! You have 2 messages."
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Supports named arguments, `plural`/`selectordinal` with exact selectors and `offset`, and
|
|
97
|
+
nested `select`. `{{name}}` interpolation keeps working.
|
|
98
|
+
|
|
99
|
+
## Instance API
|
|
100
|
+
|
|
101
|
+
- `t(key, params?)` – translate.
|
|
102
|
+
- `setLocale(locale)`, `getLocale()`, `locale`, `fallbackLocale`.
|
|
103
|
+
- `hasTranslation(key, locale?)` – whether a string exists for the key.
|
|
104
|
+
- `addMessages(locale, messages)` – deep-merge messages (e.g. after a lazy `import()`).
|
|
105
|
+
- `subscribe(listener)` – called after a locale switch and after `addMessages()` for the
|
|
106
|
+
active or fallback locale; returns an unsubscribe function. `revision` increments on each
|
|
107
|
+
such change.
|
|
108
|
+
- `addPlugin(plugin)`, `removePlugin(name)`.
|
|
109
|
+
- `formatNumber(value, format?)`, `formatDate(date, format?)`, `formatRelativeTime(date, base?)`.
|
|
110
|
+
|
|
111
|
+
## TypeScript
|
|
112
|
+
|
|
113
|
+
Catalog types may be inferred, declared as `type`s or plain `interface`s, and nested:
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
interface MessageSchema {
|
|
117
|
+
greeting: string;
|
|
118
|
+
user: { profile: { title: string; description: string } };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const i18n = createI18n<MessageSchema>({ locale: 'en', messages: { en: { /* ... */ } as MessageSchema } });
|
|
122
|
+
|
|
123
|
+
i18n.t('greeting'); // ✅
|
|
124
|
+
i18n.t('user.profile.title'); // ✅
|
|
125
|
+
i18n.t('invalid.key'); // ❌ type error
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
With `as const` catalogs, placeholders become required parameters
|
|
129
|
+
(`'Hi {{name}}'` requires `{ name }`, `{{n:number}}` requires a number).
|
|
130
|
+
|
|
131
|
+
## License
|
|
132
|
+
|
|
133
|
+
MIT © Ersin Koç
|
package/dist/index.d.mts
CHANGED
|
@@ -5,65 +5,137 @@ type ParseKeys<T> = T extends `${infer _Start}{{${infer Param}}}${infer Rest}` ?
|
|
|
5
5
|
[K in Key]: Type extends 'number' ? number : Type extends 'boolean' ? boolean : Type extends 'date' ? Date : string;
|
|
6
6
|
} & ParseKeys<Rest> : {
|
|
7
7
|
[K in Param]: TranslationValue;
|
|
8
|
-
} & ParseKeys<Rest> :
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
8
|
+
} & ParseKeys<Rest> : object;
|
|
9
|
+
/**
|
|
10
|
+
* Shape of a translation catalog: string messages, optionally grouped in nested objects
|
|
11
|
+
* (`{ user: { profile: { title: '...' } } }`) or plural groups (`{ items: { one, other } }`).
|
|
12
|
+
*/
|
|
13
|
+
interface MessageTree {
|
|
14
|
+
[key: string]: string | MessageTree;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Default (untyped) message catalog type. Typed catalogs may be any object type,
|
|
18
|
+
* including plain `interface`s without an index signature.
|
|
19
|
+
*/
|
|
20
|
+
type Messages = MessageTree;
|
|
21
|
+
type PrevDepth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8];
|
|
22
|
+
type JoinKey<K extends string, P> = P extends string ? `${K}.${P}` : never;
|
|
23
|
+
/**
|
|
24
|
+
* Dotted translation keys of a catalog: leaf keys (`'user.profile.title'`) and the keys
|
|
25
|
+
* of nested groups (`'items'`, used for plural groups such as `{ items: { one, other } }`).
|
|
26
|
+
* Catalogs with a string index signature accept any string key.
|
|
27
|
+
*/
|
|
28
|
+
type TranslationKey<T, Depth extends number = 8> = [Depth] extends [never] ? never : T extends string ? never : string extends keyof T ? string : {
|
|
29
|
+
[K in keyof T & string]: NonNullable<T[K]> extends string ? K : NonNullable<T[K]> extends object ? K | JoinKey<K, TranslationKey<NonNullable<T[K]>, PrevDepth[Depth]>> : never;
|
|
30
|
+
}[keyof T & string];
|
|
31
|
+
/** Type of the catalog entry at a dotted key. */
|
|
32
|
+
type TranslationValueAt<T, P extends string> = P extends keyof T ? T[P] : P extends `${infer Head}.${infer Rest}` ? Head extends keyof T ? TranslationValueAt<NonNullable<T[Head]>, Rest> : unknown : unknown;
|
|
33
|
+
type TranslationArgs<V> = V extends string ? keyof ParseKeys<V> extends never ? [params?: TranslationParams] : [params: ParseKeys<V> & TranslationParams] : [params?: TranslationParams];
|
|
34
|
+
type TranslationFunction<TMessages extends object = Messages> = <TKey extends TranslationKey<TMessages>>(key: TKey, ...args: TranslationArgs<TranslationValueAt<TMessages, TKey>>) => string;
|
|
35
|
+
type LocaleMessages<TMessages extends object = Messages> = Record<LocaleCode, TMessages>;
|
|
36
|
+
/** Recursive `Partial`, used for incremental catalogs passed to `addMessages`. */
|
|
37
|
+
type DeepPartial<T> = T extends string ? T : {
|
|
38
|
+
[K in keyof T]?: DeepPartial<T[K]>;
|
|
39
|
+
};
|
|
40
|
+
interface I18nPlugin<TMessages extends object = Messages> {
|
|
13
41
|
name: string;
|
|
14
|
-
|
|
42
|
+
/** The optional message locale identifies the catalog that supplied the text after fallback. */
|
|
43
|
+
transform?: (key: string, value: string, params: TranslationParams, locale: LocaleCode, messageLocale?: LocaleCode) => string;
|
|
15
44
|
beforeLoad?: (locale: LocaleCode, messages: TMessages) => TMessages;
|
|
16
45
|
afterLoad?: (locale: LocaleCode, messages: TMessages) => void;
|
|
17
46
|
format?: (value: TranslationValue, format: string, locale: LocaleCode) => string;
|
|
47
|
+
/**
|
|
48
|
+
* Escapes every value inserted by `{{placeholder}}` interpolation. Plugins whose
|
|
49
|
+
* `transform` produces HTML (such as `markdownPlugin`) set it so parameters cannot inject
|
|
50
|
+
* markup into that HTML.
|
|
51
|
+
*/
|
|
52
|
+
escapeValue?: (value: string) => string;
|
|
18
53
|
}
|
|
19
|
-
interface I18nConfig<TMessages extends
|
|
54
|
+
interface I18nConfig<TMessages extends object = Messages> {
|
|
20
55
|
locale: LocaleCode;
|
|
21
56
|
fallbackLocale?: LocaleCode;
|
|
22
57
|
messages: LocaleMessages<TMessages>;
|
|
23
58
|
plugins?: I18nPlugin<TMessages>[];
|
|
24
59
|
warnOnMissingTranslations?: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* Custom plural rules keyed by locale or language (`'pt-BR'` or `'pt'`). They take
|
|
62
|
+
* precedence over the built-in CLDR rules (`Intl.PluralRules`) for those locales only.
|
|
63
|
+
*/
|
|
25
64
|
pluralizationRules?: Record<LocaleCode, (count: number) => string>;
|
|
26
65
|
formats?: {
|
|
27
66
|
number?: Record<string, Intl.NumberFormatOptions>;
|
|
28
67
|
date?: Record<string, Intl.DateTimeFormatOptions>;
|
|
29
68
|
};
|
|
69
|
+
onError?: (error: Error, context: string) => void;
|
|
30
70
|
}
|
|
31
|
-
interface I18nInstance<TMessages extends
|
|
71
|
+
interface I18nInstance<TMessages extends object = Messages> {
|
|
32
72
|
readonly locale: LocaleCode;
|
|
33
73
|
readonly fallbackLocale?: LocaleCode;
|
|
34
74
|
readonly messages: LocaleMessages<TMessages>;
|
|
35
75
|
readonly t: TranslationFunction<TMessages>;
|
|
76
|
+
/**
|
|
77
|
+
* Incremented whenever the visible translations change (locale switch, or messages
|
|
78
|
+
* added for the active or fallback locale). Useful as a snapshot for UI bindings.
|
|
79
|
+
*/
|
|
80
|
+
readonly revision?: number;
|
|
36
81
|
setLocale(locale: LocaleCode): void;
|
|
37
82
|
getLocale(): LocaleCode;
|
|
38
|
-
hasTranslation(key:
|
|
39
|
-
addMessages(locale: LocaleCode, messages:
|
|
83
|
+
hasTranslation(key: TranslationKey<TMessages>, locale?: LocaleCode): boolean;
|
|
84
|
+
addMessages(locale: LocaleCode, messages: DeepPartial<TMessages>): void;
|
|
40
85
|
addPlugin(plugin: I18nPlugin<TMessages>): void;
|
|
41
86
|
removePlugin(pluginName: string): void;
|
|
42
87
|
formatNumber(value: number, format?: string): string;
|
|
43
88
|
formatDate(value: Date, format?: string): string;
|
|
44
89
|
formatRelativeTime(value: Date, baseDate?: Date): string;
|
|
90
|
+
/**
|
|
91
|
+
* Subscribes to translation changes: called with the active locale after `setLocale`
|
|
92
|
+
* switches locale and after `addMessages` adds messages for the active or fallback locale.
|
|
93
|
+
*/
|
|
45
94
|
subscribe(listener: (locale: LocaleCode) => void): () => void;
|
|
46
95
|
}
|
|
47
|
-
type ExtractTranslationKeys<T> = T
|
|
48
|
-
type ExtractTranslationParams<TMessages extends
|
|
96
|
+
type ExtractTranslationKeys<T> = TranslationKey<T>;
|
|
97
|
+
type ExtractTranslationParams<TMessages extends object, TKey extends string> = TranslationValueAt<TMessages, TKey> extends infer V ? V extends string ? ParseKeys<V> & TranslationParams : TranslationParams : TranslationParams;
|
|
49
98
|
|
|
50
|
-
declare function createI18n<TMessages extends
|
|
99
|
+
declare function createI18n<TMessages extends object = Messages>(config: I18nConfig<TMessages>): I18nInstance<TMessages>;
|
|
51
100
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
101
|
+
/**
|
|
102
|
+
* Replaces `{{name}}` / `{{name:format}}` placeholders with `params`. When `escape` is given
|
|
103
|
+
* (e.g. by a plugin that produces HTML), every inserted value is passed through it.
|
|
104
|
+
*/
|
|
105
|
+
declare function interpolate(template: string, params: TranslationParams, formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>, locale?: string, escape?: (value: string) => string): string;
|
|
106
|
+
declare function deepMerge<T extends object>(target: T, source: Partial<T>): T;
|
|
107
|
+
declare function getNestedValue<T>(obj: Record<string, unknown>, path: string): T | undefined;
|
|
108
|
+
interface CacheOptions {
|
|
109
|
+
maxSize?: number;
|
|
110
|
+
}
|
|
111
|
+
declare function createCache<T>(options?: CacheOptions): {
|
|
56
112
|
get: (key: string) => T | undefined;
|
|
57
113
|
set: (key: string, value: T) => void;
|
|
58
114
|
clear: () => void;
|
|
115
|
+
size: () => number;
|
|
59
116
|
};
|
|
117
|
+
/**
|
|
118
|
+
* @deprecated Kept for backwards compatibility. Plural categories are now resolved with
|
|
119
|
+
* `Intl.PluralRules` (CLDR), which covers every locale; these hand-written rules are no
|
|
120
|
+
* longer used by `getPluralForm` or `createI18n`.
|
|
121
|
+
*/
|
|
60
122
|
declare const defaultPluralRules: Record<string, (count: number) => string>;
|
|
123
|
+
/**
|
|
124
|
+
* Returns the CLDR plural category (`zero`, `one`, `two`, `few`, `many` or `other`)
|
|
125
|
+
* for `count` in `locale`.
|
|
126
|
+
*
|
|
127
|
+
* Custom rules are looked up by the exact locale first and then by its language
|
|
128
|
+
* subtag (`pt-BR` → `pt`); otherwise `Intl.PluralRules` decides.
|
|
129
|
+
*/
|
|
61
130
|
declare function getPluralForm(locale: string, count: number, customRules?: Record<string, (count: number) => string>): string;
|
|
62
131
|
|
|
63
132
|
/**
|
|
64
|
-
* Markdown plugin for basic markdown syntax transformation
|
|
133
|
+
* Markdown plugin for basic markdown syntax transformation.
|
|
65
134
|
*/
|
|
66
135
|
declare const markdownPlugin: I18nPlugin;
|
|
136
|
+
/**
|
|
137
|
+
* ICU MessageFormat plugin for named arguments, plural forms and select branches.
|
|
138
|
+
*/
|
|
67
139
|
declare const icuPlugin: I18nPlugin;
|
|
68
140
|
|
|
69
|
-
export { type ExtractTranslationKeys, type ExtractTranslationParams, type I18nConfig, type I18nInstance, type I18nPlugin, type LocaleCode, type LocaleMessages, type Messages, type ParseKeys, type TranslationFunction, type TranslationParams, type TranslationValue, createCache, createI18n, deepMerge, defaultPluralRules, getNestedValue, getPluralForm, icuPlugin, interpolate, markdownPlugin };
|
|
141
|
+
export { type CacheOptions, type DeepPartial, type ExtractTranslationKeys, type ExtractTranslationParams, type I18nConfig, type I18nInstance, type I18nPlugin, type LocaleCode, type LocaleMessages, type MessageTree, type Messages, type ParseKeys, type TranslationFunction, type TranslationKey, type TranslationParams, type TranslationValue, type TranslationValueAt, createCache, createI18n, deepMerge, defaultPluralRules, getNestedValue, getPluralForm, icuPlugin, interpolate, markdownPlugin };
|
package/dist/index.d.ts
CHANGED
|
@@ -5,65 +5,137 @@ type ParseKeys<T> = T extends `${infer _Start}{{${infer Param}}}${infer Rest}` ?
|
|
|
5
5
|
[K in Key]: Type extends 'number' ? number : Type extends 'boolean' ? boolean : Type extends 'date' ? Date : string;
|
|
6
6
|
} & ParseKeys<Rest> : {
|
|
7
7
|
[K in Param]: TranslationValue;
|
|
8
|
-
} & ParseKeys<Rest> :
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
8
|
+
} & ParseKeys<Rest> : object;
|
|
9
|
+
/**
|
|
10
|
+
* Shape of a translation catalog: string messages, optionally grouped in nested objects
|
|
11
|
+
* (`{ user: { profile: { title: '...' } } }`) or plural groups (`{ items: { one, other } }`).
|
|
12
|
+
*/
|
|
13
|
+
interface MessageTree {
|
|
14
|
+
[key: string]: string | MessageTree;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Default (untyped) message catalog type. Typed catalogs may be any object type,
|
|
18
|
+
* including plain `interface`s without an index signature.
|
|
19
|
+
*/
|
|
20
|
+
type Messages = MessageTree;
|
|
21
|
+
type PrevDepth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8];
|
|
22
|
+
type JoinKey<K extends string, P> = P extends string ? `${K}.${P}` : never;
|
|
23
|
+
/**
|
|
24
|
+
* Dotted translation keys of a catalog: leaf keys (`'user.profile.title'`) and the keys
|
|
25
|
+
* of nested groups (`'items'`, used for plural groups such as `{ items: { one, other } }`).
|
|
26
|
+
* Catalogs with a string index signature accept any string key.
|
|
27
|
+
*/
|
|
28
|
+
type TranslationKey<T, Depth extends number = 8> = [Depth] extends [never] ? never : T extends string ? never : string extends keyof T ? string : {
|
|
29
|
+
[K in keyof T & string]: NonNullable<T[K]> extends string ? K : NonNullable<T[K]> extends object ? K | JoinKey<K, TranslationKey<NonNullable<T[K]>, PrevDepth[Depth]>> : never;
|
|
30
|
+
}[keyof T & string];
|
|
31
|
+
/** Type of the catalog entry at a dotted key. */
|
|
32
|
+
type TranslationValueAt<T, P extends string> = P extends keyof T ? T[P] : P extends `${infer Head}.${infer Rest}` ? Head extends keyof T ? TranslationValueAt<NonNullable<T[Head]>, Rest> : unknown : unknown;
|
|
33
|
+
type TranslationArgs<V> = V extends string ? keyof ParseKeys<V> extends never ? [params?: TranslationParams] : [params: ParseKeys<V> & TranslationParams] : [params?: TranslationParams];
|
|
34
|
+
type TranslationFunction<TMessages extends object = Messages> = <TKey extends TranslationKey<TMessages>>(key: TKey, ...args: TranslationArgs<TranslationValueAt<TMessages, TKey>>) => string;
|
|
35
|
+
type LocaleMessages<TMessages extends object = Messages> = Record<LocaleCode, TMessages>;
|
|
36
|
+
/** Recursive `Partial`, used for incremental catalogs passed to `addMessages`. */
|
|
37
|
+
type DeepPartial<T> = T extends string ? T : {
|
|
38
|
+
[K in keyof T]?: DeepPartial<T[K]>;
|
|
39
|
+
};
|
|
40
|
+
interface I18nPlugin<TMessages extends object = Messages> {
|
|
13
41
|
name: string;
|
|
14
|
-
|
|
42
|
+
/** The optional message locale identifies the catalog that supplied the text after fallback. */
|
|
43
|
+
transform?: (key: string, value: string, params: TranslationParams, locale: LocaleCode, messageLocale?: LocaleCode) => string;
|
|
15
44
|
beforeLoad?: (locale: LocaleCode, messages: TMessages) => TMessages;
|
|
16
45
|
afterLoad?: (locale: LocaleCode, messages: TMessages) => void;
|
|
17
46
|
format?: (value: TranslationValue, format: string, locale: LocaleCode) => string;
|
|
47
|
+
/**
|
|
48
|
+
* Escapes every value inserted by `{{placeholder}}` interpolation. Plugins whose
|
|
49
|
+
* `transform` produces HTML (such as `markdownPlugin`) set it so parameters cannot inject
|
|
50
|
+
* markup into that HTML.
|
|
51
|
+
*/
|
|
52
|
+
escapeValue?: (value: string) => string;
|
|
18
53
|
}
|
|
19
|
-
interface I18nConfig<TMessages extends
|
|
54
|
+
interface I18nConfig<TMessages extends object = Messages> {
|
|
20
55
|
locale: LocaleCode;
|
|
21
56
|
fallbackLocale?: LocaleCode;
|
|
22
57
|
messages: LocaleMessages<TMessages>;
|
|
23
58
|
plugins?: I18nPlugin<TMessages>[];
|
|
24
59
|
warnOnMissingTranslations?: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* Custom plural rules keyed by locale or language (`'pt-BR'` or `'pt'`). They take
|
|
62
|
+
* precedence over the built-in CLDR rules (`Intl.PluralRules`) for those locales only.
|
|
63
|
+
*/
|
|
25
64
|
pluralizationRules?: Record<LocaleCode, (count: number) => string>;
|
|
26
65
|
formats?: {
|
|
27
66
|
number?: Record<string, Intl.NumberFormatOptions>;
|
|
28
67
|
date?: Record<string, Intl.DateTimeFormatOptions>;
|
|
29
68
|
};
|
|
69
|
+
onError?: (error: Error, context: string) => void;
|
|
30
70
|
}
|
|
31
|
-
interface I18nInstance<TMessages extends
|
|
71
|
+
interface I18nInstance<TMessages extends object = Messages> {
|
|
32
72
|
readonly locale: LocaleCode;
|
|
33
73
|
readonly fallbackLocale?: LocaleCode;
|
|
34
74
|
readonly messages: LocaleMessages<TMessages>;
|
|
35
75
|
readonly t: TranslationFunction<TMessages>;
|
|
76
|
+
/**
|
|
77
|
+
* Incremented whenever the visible translations change (locale switch, or messages
|
|
78
|
+
* added for the active or fallback locale). Useful as a snapshot for UI bindings.
|
|
79
|
+
*/
|
|
80
|
+
readonly revision?: number;
|
|
36
81
|
setLocale(locale: LocaleCode): void;
|
|
37
82
|
getLocale(): LocaleCode;
|
|
38
|
-
hasTranslation(key:
|
|
39
|
-
addMessages(locale: LocaleCode, messages:
|
|
83
|
+
hasTranslation(key: TranslationKey<TMessages>, locale?: LocaleCode): boolean;
|
|
84
|
+
addMessages(locale: LocaleCode, messages: DeepPartial<TMessages>): void;
|
|
40
85
|
addPlugin(plugin: I18nPlugin<TMessages>): void;
|
|
41
86
|
removePlugin(pluginName: string): void;
|
|
42
87
|
formatNumber(value: number, format?: string): string;
|
|
43
88
|
formatDate(value: Date, format?: string): string;
|
|
44
89
|
formatRelativeTime(value: Date, baseDate?: Date): string;
|
|
90
|
+
/**
|
|
91
|
+
* Subscribes to translation changes: called with the active locale after `setLocale`
|
|
92
|
+
* switches locale and after `addMessages` adds messages for the active or fallback locale.
|
|
93
|
+
*/
|
|
45
94
|
subscribe(listener: (locale: LocaleCode) => void): () => void;
|
|
46
95
|
}
|
|
47
|
-
type ExtractTranslationKeys<T> = T
|
|
48
|
-
type ExtractTranslationParams<TMessages extends
|
|
96
|
+
type ExtractTranslationKeys<T> = TranslationKey<T>;
|
|
97
|
+
type ExtractTranslationParams<TMessages extends object, TKey extends string> = TranslationValueAt<TMessages, TKey> extends infer V ? V extends string ? ParseKeys<V> & TranslationParams : TranslationParams : TranslationParams;
|
|
49
98
|
|
|
50
|
-
declare function createI18n<TMessages extends
|
|
99
|
+
declare function createI18n<TMessages extends object = Messages>(config: I18nConfig<TMessages>): I18nInstance<TMessages>;
|
|
51
100
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
101
|
+
/**
|
|
102
|
+
* Replaces `{{name}}` / `{{name:format}}` placeholders with `params`. When `escape` is given
|
|
103
|
+
* (e.g. by a plugin that produces HTML), every inserted value is passed through it.
|
|
104
|
+
*/
|
|
105
|
+
declare function interpolate(template: string, params: TranslationParams, formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>, locale?: string, escape?: (value: string) => string): string;
|
|
106
|
+
declare function deepMerge<T extends object>(target: T, source: Partial<T>): T;
|
|
107
|
+
declare function getNestedValue<T>(obj: Record<string, unknown>, path: string): T | undefined;
|
|
108
|
+
interface CacheOptions {
|
|
109
|
+
maxSize?: number;
|
|
110
|
+
}
|
|
111
|
+
declare function createCache<T>(options?: CacheOptions): {
|
|
56
112
|
get: (key: string) => T | undefined;
|
|
57
113
|
set: (key: string, value: T) => void;
|
|
58
114
|
clear: () => void;
|
|
115
|
+
size: () => number;
|
|
59
116
|
};
|
|
117
|
+
/**
|
|
118
|
+
* @deprecated Kept for backwards compatibility. Plural categories are now resolved with
|
|
119
|
+
* `Intl.PluralRules` (CLDR), which covers every locale; these hand-written rules are no
|
|
120
|
+
* longer used by `getPluralForm` or `createI18n`.
|
|
121
|
+
*/
|
|
60
122
|
declare const defaultPluralRules: Record<string, (count: number) => string>;
|
|
123
|
+
/**
|
|
124
|
+
* Returns the CLDR plural category (`zero`, `one`, `two`, `few`, `many` or `other`)
|
|
125
|
+
* for `count` in `locale`.
|
|
126
|
+
*
|
|
127
|
+
* Custom rules are looked up by the exact locale first and then by its language
|
|
128
|
+
* subtag (`pt-BR` → `pt`); otherwise `Intl.PluralRules` decides.
|
|
129
|
+
*/
|
|
61
130
|
declare function getPluralForm(locale: string, count: number, customRules?: Record<string, (count: number) => string>): string;
|
|
62
131
|
|
|
63
132
|
/**
|
|
64
|
-
* Markdown plugin for basic markdown syntax transformation
|
|
133
|
+
* Markdown plugin for basic markdown syntax transformation.
|
|
65
134
|
*/
|
|
66
135
|
declare const markdownPlugin: I18nPlugin;
|
|
136
|
+
/**
|
|
137
|
+
* ICU MessageFormat plugin for named arguments, plural forms and select branches.
|
|
138
|
+
*/
|
|
67
139
|
declare const icuPlugin: I18nPlugin;
|
|
68
140
|
|
|
69
|
-
export { type ExtractTranslationKeys, type ExtractTranslationParams, type I18nConfig, type I18nInstance, type I18nPlugin, type LocaleCode, type LocaleMessages, type Messages, type ParseKeys, type TranslationFunction, type TranslationParams, type TranslationValue, createCache, createI18n, deepMerge, defaultPluralRules, getNestedValue, getPluralForm, icuPlugin, interpolate, markdownPlugin };
|
|
141
|
+
export { type CacheOptions, type DeepPartial, type ExtractTranslationKeys, type ExtractTranslationParams, type I18nConfig, type I18nInstance, type I18nPlugin, type LocaleCode, type LocaleMessages, type MessageTree, type Messages, type ParseKeys, type TranslationFunction, type TranslationKey, type TranslationParams, type TranslationValue, type TranslationValueAt, createCache, createI18n, deepMerge, defaultPluralRules, getNestedValue, getPluralForm, icuPlugin, interpolate, markdownPlugin };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';function w(r,n,o,i){if(typeof r!="string")return String(r);try{return r.replace(/\{\{([^}]+)\}\}/g,(a,l)=>{try{let[f,u]=l.trim().split(":").map(g=>g.trim());if(!(f in n))return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation parameter: ${f}`),a;let d=n[f];if(u&&o?.has(u))try{return o.get(u)(d,l.includes(":")?l.split(":").slice(1).join(":"):void 0,i)}catch(g){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter error for ${u}:`,g),String(d)}return d==null?"":d instanceof Date?d.toLocaleDateString():String(d)}catch(f){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Parameter interpolation error:",f),a}})}catch(a){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Template interpolation error:",a),r}}function N(r,n){if(!r||typeof r!="object")throw new Error("[i18n] Invalid target for deepMerge");if(!n||typeof n!="object")return r;try{let o={...r};for(let i in n)n[i]!==void 0&&(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!(n[i]instanceof Date)?o[i]=N(o[i]||{},n[i]):o[i]=n[i]);return o}catch(o){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] DeepMerge error:",o),r}}function I(r,n){if(!(!r||typeof r!="object"||!n||typeof n!="string"))try{let o=n.split("."),i=r;for(let a of o)if(i&&typeof i=="object"&&a in i)i=i[a];else return;return i}catch(o){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] getNestedValue error:",o);return}}function D(){let r=new Map;return {get:n=>r.get(n),set:(n,o)=>{r.set(n,o);},clear:()=>r.clear()}}var _={en:r=>r===0?"zero":r===1?"one":"other",es:r=>r===0?"zero":r===1?"one":"other",fr:r=>r===0||r===1?"one":"other",de:r=>r===1?"one":"other",ja:()=>"other",ko:()=>"other",zh:()=>"other"};function P(r,n,o){let i=o||_;return (i[r]||i.en)(n)}function k(r){if(!r)throw new Error("[i18n] Configuration is required");if(!r.locale)throw new Error("[i18n] Locale is required");if(!r.messages)throw new Error("[i18n] Messages are required");let n=r.locale,o=r.fallbackLocale,i={...r.messages},a=[...r.plugins||[]],l=new Set,f=D(),u=new Map;u.set("number",(e,s,t)=>{if(typeof e!="number")return String(e);let c=r.formats?.number?.[s||"default"]||{};return new Intl.NumberFormat(t||n,c).format(e)}),u.set("date",(e,s,t)=>{if(!(e instanceof Date))return String(e);let c=r.formats?.date?.[s||"default"]||{};return new Intl.DateTimeFormat(t||n,c).format(e)}),u.set("currency",(e,s,t)=>{if(typeof e!="number")return String(e);let c=(s||"currency:USD").split(":"),p=c.length>1&&c[1]||"USD";try{return new Intl.NumberFormat(t||n,{style:"currency",currency:p}).format(e)}catch{return `${p} ${e}`}}),a.forEach(e=>{e.format&&u.set(e.name,(s,t,c)=>e.format(s,t??"",c??n));});function d(e,s){let t=i[s];if(t)return e in t?t[e]:I(t,e)}function g(e,s,t=n){try{let c=`${t}:${e}:${JSON.stringify(s||{})}`,p=f.get(c);if(p)return p;let m=d(e,t);if(!m&&o&&t!==o&&(m=d(e,o)),s&&"count"in s&&typeof s.count=="number"){let E=P(t,s.count,r.pluralizationRules),M=`${e}.${E}`,b=d(M,t);if(!b&&o&&t!==o){let v=d(M,o);v&&(m=v);}else b&&(m=b);}if(!m)return r.warnOnMissingTranslations&&typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation: ${e} for locale: ${t}`),e;let h=m;for(let E of a)if(E.transform)try{h=E.transform(e,h,s||{},t);}catch(M){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Plugin ${E.name} transform error:`,M);}return h=w(h,s||{},u,n),f.set(c,h),h}catch(c){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Translation error for key ${e}:`,c),e}}let y=(e,...s)=>{let t=s[0];return g(String(e),t)};function T(e){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");e!==n&&(n=e,f.clear(),l.forEach(s=>{try{s(e);}catch(t){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Locale change listener error:",t);}}));}function $(e,s){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");if(!s||typeof s!="object")throw new Error("[i18n] Invalid messages provided");try{i[e]||(i[e]={});let t=s;for(let c of a)if(c.beforeLoad)try{t=c.beforeLoad(e,t);}catch(p){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Plugin ${c.name} beforeLoad error:`,p);}i[e]=N(i[e],t);for(let c of a)if(c.afterLoad)try{c.afterLoad(e,i[e]);}catch(p){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Plugin ${c.name} afterLoad error:`,p);}f.clear();}catch(t){throw typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Error adding messages:",t),t}}function V(e,s){let t=s||n;return d(String(e),t)!==void 0}function S(e){a.push(e),e.format&&u.set(e.name,(s,t,c)=>e.format(s,t??"",c??n)),f.clear();}function x(e){let s=a.findIndex(t=>t.name===e);s!==-1&&(a.splice(s,1),u.delete(e),f.clear());}function C(e){return l.add(e),()=>l.delete(e)}function O(e,s){return u.get("number")(e,s,n)}function F(e,s){return u.get("date")(e,s,n)}function R(e,s=new Date){let t=Math.floor((e.getTime()-s.getTime())/1e3),c=new Intl.RelativeTimeFormat(n,{numeric:"auto"}),p=[["year",60*60*24*365],["month",60*60*24*30],["week",60*60*24*7],["day",60*60*24],["hour",60*60],["minute",60],["second",1]];for(let[m,h]of p)if(Math.abs(t)>=h)return c.format(Math.round(t/h),m);return c.format(0,"second")}return {get locale(){return n},get fallbackLocale(){return o},get messages(){return i},t:y,setLocale:T,getLocale:()=>n,hasTranslation:V,addMessages:$,addPlugin:S,removePlugin:x,subscribe:C,formatNumber:O,formatDate:F,formatRelativeTime:R}}var q={name:"markdown",transform:(r,n,o,i)=>n.replace(/\*\*(.*?)\*\*/g,"<strong>$1</strong>").replace(/\*(.*?)\*/g,"<em>$1</em>").replace(/`(.*?)`/g,"<code>$1</code>").replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2">$1</a>')};function L(r,n){let o=r.match(n);if(!o)return null;let i=o.index+o[0].length,a=1,l=i;for(;l<r.length&&a>0;)r[l]==="{"?a++:r[l]==="}"&&a--,l++;if(a===0){let f=r.substring(o.index,l),u=r.substring(i,l-1);return {match:f,content:u}}return null}var A={name:"icu",transform:(r,n,o,i)=>{let a=n;if(o&&"count"in o){let l=o.count,f=L(a,/\{count,\s*plural,\s*/);if(f){let u=f.content,d=u.match(/=0\s*\{([^}]+)\}/),g=u.match(/=1\s*\{([^}]+)\}/)||u.match(/one\s*\{([^}]+)\}/),y=u.match(/other\s*\{([^}]+)\}/),T=f.match;l===0&&d?T=d[1]:l===1&&g?T=g[1]:y&&(T=y[1].replace(/#/g,String(l))),a=a.replace(f.match,T);}}if(o&&"gender"in o){let l=o.gender,f=L(a,/\{gender,\s*select,\s*/);if(f){let u=f.content,d=u.match(new RegExp(`${l}\\s*\\{([^}]+)\\}`)),g=u.match(/other\s*\{([^}]+)\}/),y=f.match;d?y=d[1]:g&&(y=g[1]),a=a.replace(f.match,y);}}return o&&"name"in o&&(a=a.replace(/\{name\}/g,String(o.name))),a}};exports.createCache=D;exports.createI18n=k;exports.deepMerge=N;exports.defaultPluralRules=_;exports.getNestedValue=I;exports.getPluralForm=P;exports.icuPlugin=A;exports.interpolate=w;exports.markdownPlugin=q;//# sourceMappingURL=index.js.map
|
|
1
|
+
'use strict';function V(r,t,s,o,n){if(typeof r!="string")return String(r);try{return r.replace(/\{\{([^}]+)\}\}/g,(u,d)=>{let p=c(d);return p===void 0?u:n?n(p):p})}catch(u){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Template interpolation error:",u),r}function c(u){try{let[d,p]=u.trim().split(":").map(h=>h.trim());if(!Object.prototype.hasOwnProperty.call(t,d)){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation parameter: ${d}`);return}let m=t[d];if(p&&s?.has(p))try{let h=s.get(p);if(!h)return String(m);let f=h(m,u.includes(":")?u.split(":").slice(1).join(":"):void 0,o);return typeof f!="string"?(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter '${p}' must return a string, got ${typeof f}`),String(m)):f}catch(h){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter error for ${p}:`,h),String(m)}return m==null?"":m instanceof Date?m.toLocaleDateString(o||"en-US",{year:"numeric",month:"2-digit",day:"2-digit"}):String(m)}catch(d){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Parameter interpolation error:",d);return}}}function M(r,t){if(!r||typeof r!="object")throw new Error("[i18n] Invalid target for deepMerge");if(!t||typeof t!="object")return r;try{let s={...r};for(let o in t){if(o==="__proto__"||o==="constructor"||o==="prototype"){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Blocked attempt to set dangerous property: ${o}`);continue}if(!Object.prototype.hasOwnProperty.call(t,o))continue;let n=t[o];if(n!==void 0)if(typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof Date)){let c=s[o];s[o]=M(c&&typeof c=="object"?c:{},n);}else s[o]=n;}return s}catch(s){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] DeepMerge error:",s),r}}function A(r,t){if(!(!r||typeof r!="object"||!t||typeof t!="string"))try{let s=t.split("."),o=r;for(let n of s)if(o&&typeof o=="object"&&Object.prototype.hasOwnProperty.call(o,n))o=o[n];else return;return o}catch(s){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] getNestedValue error:",s);return}}function F(r){let t=new Map,s=r?.maxSize??1e3;return {get:o=>{let n=t.get(o);return n!==void 0&&(t.delete(o),t.set(o,n)),n},set:(o,n)=>{if(t.has(o))t.delete(o);else if(t.size>=s){let c=t.keys().next().value;c!==void 0&&t.delete(c);}t.set(o,n);},clear:()=>t.clear(),size:()=>t.size}}var te={en:r=>r===0?"zero":r===1?"one":"other",es:r=>r===0?"zero":r===1?"one":"other",fr:r=>r===0||r===1?"one":"other",de:r=>r===1?"one":"other",ja:()=>"other",ko:()=>"other",zh:()=>"other"},S=new Map;function X(r){let t=S.get(r);if(!t){try{let s=r.replace(/_/g,"-");t=new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(s).length>0?s:"en");}catch{t=new Intl.PluralRules("en");}S.set(r,t);}return t}function K(r,t,s){if(s){let o=r.split(/[-_]/)[0],n=Object.prototype.hasOwnProperty.call(s,r)?s[r]:Object.prototype.hasOwnProperty.call(s,o)?s[o]:void 0;if(typeof n=="function")return n(t)}return X(r).select(t)}function Y(r){if(!r)throw new Error("[i18n] Configuration is required");if(!r.locale||typeof r.locale!="string"||r.locale.trim()==="")throw new Error("[i18n] Locale must be a non-empty string");if(!r.messages)throw new Error("[i18n] Messages are required");if(typeof r.messages!="object"||Array.isArray(r.messages)||r.messages===null)throw new Error("[i18n] Messages must be an object");let t=Object.keys(r.messages).length>0;if(t||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Messages object is empty - all translations will return keys"),t&&!(r.locale in r.messages)&&!r.fallbackLocale){let e=Object.keys(r.messages).join(", ");throw new Error(`[i18n] Locale '${r.locale}' not found in messages and no fallback locale provided. Available locales: ${e}`)}if(!(r.locale in r.messages)&&r.fallbackLocale&&typeof process<"u"&&process.env?.NODE_ENV!=="production"){let e=Object.keys(r.messages).join(", ");console.warn(`[i18n] Locale '${r.locale}' not found in messages, will use fallback locale '${r.fallbackLocale}'. Available locales: ${e}`);}if(r.fallbackLocale&&!(r.fallbackLocale in r.messages)){let e=Object.keys(r.messages).join(", ");typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Fallback locale '${r.fallbackLocale}' not found in messages. Available locales: ${e}`);}let s=r.locale,o=r.fallbackLocale,n=structuredClone(r.messages),c=[...r.plugins||[]],u=new Set,d=F(),p=0,m=()=>{p++,u.forEach(e=>{try{e(s);}catch(i){h(i,"Locale change listener");}});},h=(e,i)=>{let a=e instanceof Error?e:new Error(String(e));if(r.onError)try{r.onError(a,i);}catch{}typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] ${i}:`,a);},f=new Map;f.set("number",(e,i,a)=>{if(typeof e!="number")return String(e);let l=r.formats?.number?.[i||"default"]||{};return new Intl.NumberFormat(a||s,l).format(e)}),f.set("date",(e,i,a)=>{if(!(e instanceof Date))return String(e);let l=r.formats?.date?.[i||"default"]||{};return new Intl.DateTimeFormat(a||s,l).format(e)}),f.set("currency",(e,i,a)=>{if(typeof e!="number")return String(e);let l=(i||"currency:USD").split(":"),g=l.length>1&&l[1]||"USD";try{return new Intl.NumberFormat(a||s,{style:"currency",currency:g}).format(e)}catch(w){return h(w,`Currency formatter error for currency '${g}'`),`${g} ${e}`}}),c.forEach(e=>{e.format&&f.set(e.name,(i,a,l)=>e.format(i,a??"",l??s));});function P(e,i){if(!Object.prototype.hasOwnProperty.call(n,i))return;let a=n[i];if(!a||typeof a!="object")return;let l=Object.prototype.hasOwnProperty.call(a,e)?a[e]:A(a,e);return typeof l=="string"?l:void 0}function L(e,i,a){let l=o&&o!==a?[a,o]:[a],g=i&&Object.prototype.hasOwnProperty.call(i,"count")?i.count:void 0;for(let w of l){if(typeof g=="number"){let O=new Set;g===0&&O.add("zero"),O.add(K(w,g,r.pluralizationRules)),O.add("other");for(let $ of O){let v=P(`${e}.${$}`,w);if(v)return {message:v,messageLocale:w}}}let _=P(e,w);if(_)return {message:_,messageLocale:w}}}function N(e,i,a=s){try{let l="";if(i){let y=Object.keys(i);if(y.length>0)try{if(y.length===1){let b=y[0];l=`${b}:${JSON.stringify(i[b])}`;}else {let b=y.sort(),D={};for(let C of b)D[C]=i[C];l=JSON.stringify(D);}}catch{typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Failed to serialize params for caching, using fallback key"),l=y.sort().join(",");}}let g=`${a}:${e}:${l}`,w=d.get(g);if(w!==void 0)return w;let _=L(e,i,a);if(!_)return r.warnOnMissingTranslations&&typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation: ${e} for locale: ${a}`),e;let{message:O,messageLocale:$}=_,v=O;for(let y of c)if(y.transform)try{let b=y.transform(e,v,i||{},a,$);if(typeof b!="string"){h(new Error(`Plugin transform must return a string, got ${typeof b}`),`Plugin ${y.name} transform validation`);continue}v=b;}catch(b){h(b,`Plugin ${y.name} transform`);}let R=c.filter(y=>typeof y.escapeValue=="function");return v=V(v,i||{},f,s,R.length>0?y=>R.reduce((b,D)=>D.escapeValue(b),y):void 0),d.set(g,v),v}catch(l){return h(l,`Translation error for key ${e}`),e}}let x=(e,i)=>N(String(e),i);function T(e){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");n[e]||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Locale '${e}' not found in messages. Available locales: ${Object.keys(n).join(", ")}`),e!==s&&(s=e,d.clear(),m());}function I(e,i){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");if(!i||typeof i!="object")throw new Error("[i18n] Invalid messages provided");try{n[e]||(n[e]={});let a=i;for(let l of c)if(l.beforeLoad)try{let g=l.beforeLoad(e,a);if(!g||typeof g!="object"||Array.isArray(g)){h(new Error(`Plugin beforeLoad must return an object, got ${typeof g}`),`Plugin ${l.name} beforeLoad validation`);continue}a=g;}catch(g){h(g,`Plugin ${l.name} beforeLoad`);}n[e]=M(n[e],a);for(let l of c)if(l.afterLoad)try{l.afterLoad(e,n[e]);}catch(g){h(g,`Plugin ${l.name} afterLoad`);}d.clear(),(e===s||e===o)&&m();}catch(a){throw h(a,"Error adding messages"),a}}function U(e,i){let a=i||s;return P(String(e),a)!==void 0}function H(e){let i=c.findIndex(a=>a.name===e.name);i!==-1&&(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Plugin '${e.name}' already registered. Replacing existing plugin.`),c.splice(i,1)),c.push(e),e.format&&f.set(e.name,(a,l,g)=>e.format(a,l??"",g??s)),d.clear();}function q(e){let i=c.findIndex(a=>a.name===e);i!==-1&&(c.splice(i,1),f.delete(e),d.clear());}function J(e){return u.add(e),()=>u.delete(e)}function B(e,i){let a=f.get("number");if(!a)throw new Error("[i18n] Number formatter not available. Please add a plugin that provides number formatting.");return a(e,i,s)}function G(e,i){let a=f.get("date");if(!a)throw new Error("[i18n] Date formatter not available. Please add a plugin that provides date formatting.");return a(e,i,s)}function Q(e,i=new Date){if(!(e instanceof Date)||isNaN(e.getTime()))throw new Error("[i18n] Invalid date provided to formatRelativeTime");if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("[i18n] Invalid base date provided to formatRelativeTime");let a=Math.floor((e.getTime()-i.getTime())/1e3),l=new Intl.RelativeTimeFormat(s,{numeric:"auto"}),g=[["year",60*60*24*365],["month",60*60*24*30],["week",60*60*24*7],["day",60*60*24],["hour",60*60],["minute",60],["second",1]];for(let[w,_]of g)if(Math.abs(a)>=_)return l.format(Math.round(a/_),w);return l.format(0,"second")}return {get locale(){return s},get fallbackLocale(){return o},get messages(){return n},get revision(){return p},t:x,setLocale:T,getLocale:()=>s,hasTranslation:U,addMessages:I,addPlugin:H,removePlugin:q,subscribe:J,formatNumber:B,formatDate:G,formatRelativeTime:Q}}var E=class extends Error{},j=class{constructor(t){this.source=t;}cursor=0;parse(){return this.message(0,false).parts}take(t){t.lastIndex=this.cursor;let s=t.exec(this.source)?.[0];return s!==void 0&&(this.cursor+=s.length),s}expect(t){let s=this.take(t);if(s===void 0)throw new E;return s}space(){this.take(/\s+/y);}number(){let t=Number(this.expect(/[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/y));if(!Number.isFinite(t))throw new E;return t}quote(){let t="";for(this.cursor++;this.cursor<this.source.length;){let s=this.source.charAt(this.cursor++);if(s==="'"&&!this.take(/'/y))break;t+=s;}return t}message(t,s){if(t>64)throw new E;let o=[],n="";function c(){n&&o.push(n),n="";}for(;this.cursor<this.source.length;){let u=this.source.charAt(this.cursor);if(u==="}"){if(t===0)throw new E;return this.cursor++,c(),{parts:o,closed:true}}if(u==="{"){let d=this.take(/\{\{[^{}]*\}\}/y);d!==void 0?n+=d:(c(),o.push(this.argument(t)));}else u==="'"&&this.take(/''/y)?n+="'":u==="'"&&(["{","}"].includes(this.source.charAt(this.cursor+1))||s&&this.source.charAt(this.cursor+1)==="#")?n+=this.quote():(this.cursor++,u==="#"&&s?(c(),o.push({kind:"number"})):n+=u);}return c(),{parts:o,closed:false}}argument(t){let s=this.cursor++;this.space();let o=this.expect(/[\p{ID_Continue}]+/uy);if(this.space(),this.take(/\}/y))return {kind:"value",name:o,source:this.source.slice(s,this.cursor)};this.expect(/,/y),this.space();let n=this.expect(/selectordinal|plural|select/y);this.space(),this.expect(/,/y),this.space();let c=n!=="select"&&this.take(/offset\s*:\s*/y)?this.number():0;this.space();let u=new Map;for(;!this.take(/\}/y);){let d=n!=="select"&&this.take(/=/y)?"="+this.number():this.expect(/[\p{ID_Continue}]+/uy);this.space(),this.expect(/\{/y);let p=this.message(t+1,n!=="select");if(!p.closed)throw new E;u.has(d)||u.set(d,p.parts),this.space();}if(!u.has("other"))throw new E;return {kind:n,name:o,choices:u,offset:c,source:this.source.slice(s,this.cursor)}}};function Z(r){try{return Intl.getCanonicalLocales(r.replace(/_/g,"-"))[0]??"en"}catch{return "en"}}function ee(r,t,s){let o=Z(s),n={maximumSignificantDigits:21},c,u,d;function p(m,h){return m.map(f=>{if(typeof f=="string")return f;if(f.kind==="number")return h===void 0?"#":(d??=new Intl.NumberFormat(o,n)).format(h);if(!Object.hasOwn(t,f.name))return f.source;let P=t[f.name];if(f.kind==="value")return String(P);if(f.kind==="select"){let I=f.choices.get(String(P))??f.choices.get("other");return I?p(I):f.source}if(typeof P!="number"||!Number.isFinite(P))return f.source;let L=P-f.offset;if(!Number.isFinite(L))return f.source;let N=f.choices.get("="+P);if(N)return p(N,L);let x=f.kind==="plural"?c??=new Intl.PluralRules(o,n):u??=new Intl.PluralRules(o,{...n,type:"ordinal"}),T=f.choices.get(x.select(L))??f.choices.get("other");return T?p(T,L):f.source}).join("")}return p(r)}function z(){return {name:"icu",transform:(r,t,s,o,n)=>{if(!/[{']/.test(t))return t;try{return ee(new j(t).parse(),s,n??o)}catch(c){if(c instanceof E)return t;throw c}}}}function k(r){let t={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};return r.replace(/[&<>"'/]/g,s=>t[s])}function re(r){let t=r.trim().toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:")||t.startsWith("vbscript:")||t.startsWith("file:")?"#":k(r)}function W(){return {name:"markdown",escapeValue:k,transform:(r,t,s,o)=>{let n=t,c=[],u=0;n=n.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(d,p,m)=>{let h=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<a href="${re(m)}">${k(p)}</a>`,u++,h}),n=n.replace(/\*\*(.*?)\*\*/g,(d,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<strong>${k(p)}</strong>`,u++,m}),n=n.replace(/\*(.*?)\*/g,(d,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<em>${k(p)}</em>`,u++,m}),n=n.replace(/`(.*?)`/g,(d,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<code>${k(p)}</code>`,u++,m}),n=k(n);for(let d=0;d<c.length;d++)n=n.replace(`__MARKDOWN_PLACEHOLDER_${d}__`,c[d]);return n}}}var le=W(),fe=z();exports.createCache=F;exports.createI18n=Y;exports.deepMerge=M;exports.defaultPluralRules=te;exports.getNestedValue=A;exports.getPluralForm=K;exports.icuPlugin=fe;exports.interpolate=V;exports.markdownPlugin=le;//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts","../src/core.ts","../src/plugins.ts"],"names":["interpolate","template","params","formatters","locale","match","key","paramKey","format","s","value","error","deepMerge","target","source","result","getNestedValue","obj","path","keys","current","createCache","cache","defaultPluralRules","count","getPluralForm","customRules","rules","createI18n","config","currentLocale","fallbackLocale","messages","plugins","listeners","translationCache","options","parts","currency","plugin","getMessage","localeMessages","translate","cacheKey","cached","message","pluralForm","pluralKey","pluralMessage","fallbackPluralMessage","t","args","setLocale","listener","addMessages","newMessages","processedMessages","hasTranslation","checkLocale","addPlugin","removePlugin","pluginName","index","p","subscribe","formatNumber","formatDate","formatRelativeTime","baseDate","diffInSeconds","rtf","units","unit","secondsInUnit","markdownPlugin","_key","_params","_locale","parseICUBalanced","text","startPattern","start","braceCount","i","fullMatch","content","icuPlugin","pluralInfo","zeroMatch","oneMatch","otherMatch","replacement","gender","selectInfo","genderMatch"],"mappings":"aAEO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EACQ,CACR,GAAI,OAAOH,CAAAA,EAAa,QAA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AA,CAAcF,CAAAA,CAAS,CAAC,CAAA,CACfC,CAAAA,GACTC,EAAcD,CAAAA,CAAW,CAAC,EAAE,OAAA,CAAQ,IAAA,CAAM,OAAOlE,CAAK,CAAC,GAGzDT,CAAAA,CAASA,CAAAA,CAAO,OAAA,CAAQwE,CAAAA,CAAW,KAAA,CAAOI,CAAW,EACvD,CACF,CAGA,GAAIf,CAAAA,EAAW,QAAA,GAAYA,EAAS,CAClC,IAAMgB,CAAAA,CAAShB,CAAAA,CAAQ,MAAA,CAGjBiB,CAAAA,CAAaf,EAAiB/D,CAAAA,CAAQ,wBAAwB,EACpE,GAAI8E,CAAAA,CAAY,CACd,IAAMlE,CAAAA,CAAQkE,CAAAA,CAAW,OAAA,CACnBC,CAAAA,CAAcnE,CAAAA,CAAM,MAAM,IAAI,MAAA,CAAO,GAAGiE,CAAM,CAAA,iBAAA,CAAmB,CAAC,CAAA,CAClEF,CAAAA,CAAa/D,EAAM,KAAA,CAAM,qBAAqB,EAEhDgE,CAAAA,CAAcE,CAAAA,CAAW,MACzBC,CAAAA,CACFH,CAAAA,CAAcG,EAAY,CAAC,CAAA,CAClBJ,CAAAA,GACTC,CAAAA,CAAcD,CAAAA,CAAW,CAAC,GAG5B3E,CAAAA,CAASA,CAAAA,CAAO,QAAQ8E,CAAAA,CAAW,KAAA,CAAOF,CAAW,EACvD,CACF,CAGA,OAAIf,CAAAA,EAAW,MAAA,GAAUA,IACvB7D,CAAAA,CAASA,CAAAA,CAAO,QAAQ,WAAA,CAAa,MAAA,CAAO6D,EAAQ,IAAI,CAAC,CAAA,CAAA,CAGpD7D,CACT,CACF","file":"index.js","sourcesContent":["import type { TranslationParams, TranslationValue } from './types';\n\nexport function interpolate(\n template: string,\n params: TranslationParams,\n formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>,\n locale?: string\n): string {\n if (typeof template !== 'string') {\n return String(template);\n }\n \n try {\n return template.replace(/\\{\\{([^}]+)\\}\\}/g, (match, key) => {\n try {\n const [paramKey, format] = key.trim().split(':').map((s: string) => s.trim());\n \n if (!(paramKey in params)) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation parameter: ${paramKey}`);\n }\n return match; // Return original placeholder for missing parameters\n }\n \n const value = params[paramKey];\n \n if (format && formatters?.has(format)) {\n try {\n const formatter = formatters.get(format)!;\n return formatter(value, key.includes(':') ? key.split(':').slice(1).join(':') : undefined, locale);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter error for ${format}:`, error);\n }\n return String(value);\n }\n }\n \n if (value === null || value === undefined) {\n return '';\n }\n \n if (value instanceof Date) {\n return value.toLocaleDateString();\n }\n \n return String(value);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Parameter interpolation error:', error);\n }\n return match;\n }\n });\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Template interpolation error:', error);\n }\n return template;\n }\n}\n\nexport function deepMerge<T extends Record<string, any>>(\n target: T,\n source: Partial<T>\n): T {\n if (!target || typeof target !== 'object') {\n throw new Error('[i18n] Invalid target for deepMerge');\n }\n \n if (!source || typeof source !== 'object') {\n return target;\n }\n \n try {\n const result = { ...target };\n \n for (const key in source) {\n if (source[key] !== undefined) {\n if (\n typeof source[key] === 'object' &&\n source[key] !== null &&\n !Array.isArray(source[key]) &&\n !(source[key] as any instanceof Date)\n ) {\n result[key] = deepMerge(\n result[key] || ({} as any),\n source[key] as any\n ) as any;\n } else {\n result[key] = source[key] as any;\n }\n }\n }\n \n return result;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] DeepMerge error:', error);\n }\n return target;\n }\n}\n\nexport function getNestedValue<T>(\n obj: Record<string, any>,\n path: string\n): T | undefined {\n if (!obj || typeof obj !== 'object' || !path || typeof path !== 'string') {\n return undefined;\n }\n \n try {\n const keys = path.split('.');\n let current = obj;\n \n for (const key of keys) {\n if (current && typeof current === 'object' && key in current) {\n current = current[key];\n } else {\n return undefined;\n }\n }\n \n return current as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] getNestedValue error:', error);\n }\n return undefined;\n }\n}\n\nexport function createCache<T>(): {\n get: (key: string) => T | undefined;\n set: (key: string, value: T) => void;\n clear: () => void;\n} {\n const cache = new Map<string, T>();\n \n return {\n get: (key: string) => cache.get(key),\n set: (key: string, value: T) => {\n cache.set(key, value);\n },\n clear: () => cache.clear(),\n };\n}\n\nexport const defaultPluralRules: Record<string, (count: number) => string> = {\n en: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n es: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n fr: (count: number) => {\n if (count === 0 || count === 1) return 'one';\n return 'other';\n },\n de: (count: number) => {\n if (count === 1) return 'one';\n return 'other';\n },\n ja: () => 'other',\n ko: () => 'other',\n zh: () => 'other',\n};\n\nexport function getPluralForm(\n locale: string,\n count: number,\n customRules?: Record<string, (count: number) => string>\n): string {\n const rules = customRules || defaultPluralRules;\n const rule = rules[locale] || rules.en;\n return rule(count);\n}","import type {\n I18nConfig,\n I18nInstance,\n I18nPlugin,\n LocaleCode,\n Messages,\n TranslationFunction,\n TranslationParams,\n TranslationValue,\n} from './types';\nimport {\n createCache,\n deepMerge,\n getNestedValue,\n getPluralForm,\n interpolate,\n} from './utils';\n\nexport function createI18n<TMessages extends Messages = Messages>(\n config: I18nConfig<TMessages>\n): I18nInstance<TMessages> {\n // Validate config\n if (!config) {\n throw new Error('[i18n] Configuration is required');\n }\n if (!config.locale) {\n throw new Error('[i18n] Locale is required');\n }\n if (!config.messages) {\n throw new Error('[i18n] Messages are required');\n }\n\n let currentLocale = config.locale;\n const fallbackLocale = config.fallbackLocale;\n const messages = { ...config.messages };\n const plugins = [...(config.plugins || [])];\n const listeners = new Set<(locale: LocaleCode) => void>();\n const translationCache = createCache<string>();\n \n const formatters = new Map<string, (value: TranslationValue, format?: string, locale?: string) => string>();\n \n // Built-in formatters\n formatters.set('number', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const options = config.formats?.number?.[format || 'default'] || {};\n return new Intl.NumberFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('date', (value, format, locale) => {\n if (!(value instanceof Date)) return String(value);\n const options = config.formats?.date?.[format || 'default'] || {};\n return new Intl.DateTimeFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('currency', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const parts = (format || 'currency:USD').split(':');\n const currency = parts.length > 1 ? parts[1] || 'USD' : 'USD';\n try {\n return new Intl.NumberFormat(locale || currentLocale, {\n style: 'currency',\n currency,\n }).format(value);\n } catch (error) {\n return `${currency} ${value}`;\n }\n });\n \n // Register plugin formatters\n plugins.forEach(plugin => {\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) => \n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n });\n \n function getMessage(key: string, locale: LocaleCode): string | undefined {\n const localeMessages = messages[locale];\n if (!localeMessages) return undefined;\n \n // First try direct key access (for flat keys like 'user.role.admin')\n if (key in localeMessages) {\n return localeMessages[key] as string;\n }\n \n // Then try nested access (for nested objects like user.role.admin)\n return getNestedValue<string>(localeMessages, key);\n }\n \n function translate(\n key: string,\n params?: TranslationParams,\n locale: LocaleCode = currentLocale\n ): string {\n try {\n const cacheKey = `${locale}:${key}:${JSON.stringify(params || {})}`;\n const cached = translationCache.get(cacheKey);\n if (cached) return cached;\n \n let message = getMessage(key, locale);\n \n // Try fallback locale\n if (!message && fallbackLocale && locale !== fallbackLocale) {\n message = getMessage(key, fallbackLocale);\n }\n \n // Handle pluralization before checking if message exists\n if (params && 'count' in params && typeof params.count === 'number') {\n const pluralForm = getPluralForm(locale, params.count, config.pluralizationRules);\n const pluralKey = `${key}.${pluralForm}`;\n const pluralMessage = getMessage(pluralKey, locale);\n \n // Try fallback locale for plural\n if (!pluralMessage && fallbackLocale && locale !== fallbackLocale) {\n const fallbackPluralMessage = getMessage(pluralKey, fallbackLocale);\n if (fallbackPluralMessage) {\n message = fallbackPluralMessage;\n }\n } else if (pluralMessage) {\n message = pluralMessage;\n }\n }\n\n if (!message) {\n if (config.warnOnMissingTranslations && typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation: ${key} for locale: ${locale}`);\n }\n return key;\n }\n \n // Apply plugins\n let result = message;\n for (const plugin of plugins) {\n if (plugin.transform) {\n try {\n result = plugin.transform(key as keyof TMessages, result, params || {}, locale);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Plugin ${plugin.name} transform error:`, error);\n }\n }\n }\n }\n \n // Always interpolate to handle empty parameters \n result = interpolate(result, params || {}, formatters, currentLocale);\n \n translationCache.set(cacheKey, result);\n return result;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Translation error for key ${key}:`, error);\n }\n return key;\n }\n }\n \n const t: TranslationFunction<TMessages> = (key, ...args) => {\n const params = args[0] as TranslationParams | undefined;\n return translate(String(key), params);\n };\n \n function setLocale(locale: LocaleCode): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n \n if (locale !== currentLocale) {\n currentLocale = locale;\n translationCache.clear();\n listeners.forEach(listener => {\n try {\n listener(locale);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Locale change listener error:', error);\n }\n }\n });\n }\n }\n \n function addMessages(locale: LocaleCode, newMessages: Partial<TMessages>): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n \n if (!newMessages || typeof newMessages !== 'object') {\n throw new Error('[i18n] Invalid messages provided');\n }\n \n try {\n if (!messages[locale]) {\n messages[locale] = {} as TMessages;\n }\n \n // Apply beforeLoad plugins\n let processedMessages = newMessages;\n for (const plugin of plugins) {\n if (plugin.beforeLoad) {\n try {\n processedMessages = plugin.beforeLoad(locale, processedMessages as TMessages) as Partial<TMessages>;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Plugin ${plugin.name} beforeLoad error:`, error);\n }\n }\n }\n }\n \n messages[locale] = deepMerge(messages[locale], processedMessages);\n \n // Apply afterLoad plugins\n for (const plugin of plugins) {\n if (plugin.afterLoad) {\n try {\n plugin.afterLoad(locale, messages[locale]);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Plugin ${plugin.name} afterLoad error:`, error);\n }\n }\n }\n }\n \n translationCache.clear();\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Error adding messages:', error);\n }\n throw error;\n }\n }\n \n function hasTranslation(key: keyof TMessages, locale?: LocaleCode): boolean {\n const checkLocale = locale || currentLocale;\n const message = getMessage(String(key), checkLocale);\n return message !== undefined;\n }\n \n function addPlugin(plugin: I18nPlugin<TMessages>): void {\n plugins.push(plugin);\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) => \n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n translationCache.clear();\n }\n \n function removePlugin(pluginName: string): void {\n const index = plugins.findIndex(p => p.name === pluginName);\n if (index !== -1) {\n plugins.splice(index, 1);\n formatters.delete(pluginName);\n translationCache.clear();\n }\n }\n \n function subscribe(listener: (locale: LocaleCode) => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n \n function formatNumber(value: number, format?: string): string {\n const formatter = formatters.get('number')!;\n return formatter(value, format, currentLocale);\n }\n \n function formatDate(value: Date, format?: string): string {\n const formatter = formatters.get('date')!;\n return formatter(value, format, currentLocale);\n }\n \n function formatRelativeTime(value: Date, baseDate: Date = new Date()): string {\n const diffInSeconds = Math.floor((value.getTime() - baseDate.getTime()) / 1000);\n const rtf = new Intl.RelativeTimeFormat(currentLocale, { numeric: 'auto' });\n \n const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [\n ['year', 60 * 60 * 24 * 365],\n ['month', 60 * 60 * 24 * 30],\n ['week', 60 * 60 * 24 * 7],\n ['day', 60 * 60 * 24],\n ['hour', 60 * 60],\n ['minute', 60],\n ['second', 1],\n ];\n \n for (const [unit, secondsInUnit] of units) {\n if (Math.abs(diffInSeconds) >= secondsInUnit) {\n return rtf.format(Math.round(diffInSeconds / secondsInUnit), unit);\n }\n }\n \n return rtf.format(0, 'second');\n }\n \n return {\n get locale() {\n return currentLocale;\n },\n get fallbackLocale() {\n return fallbackLocale;\n },\n get messages() {\n return messages;\n },\n t,\n setLocale,\n getLocale: () => currentLocale,\n hasTranslation,\n addMessages,\n addPlugin,\n removePlugin,\n subscribe,\n formatNumber,\n formatDate,\n formatRelativeTime,\n };\n}","import type { I18nPlugin } from './types';\n\n/**\n * Markdown plugin for basic markdown syntax transformation\n */\nexport const markdownPlugin: I18nPlugin = {\n name: 'markdown',\n transform: (_key, value, _params, _locale) => {\n return value\n .replace(/\\*\\*(.*?)\\*\\*/g, '<strong>$1</strong>')\n .replace(/\\*(.*?)\\*/g, '<em>$1</em>')\n .replace(/`(.*?)`/g, '<code>$1</code>')\n .replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, '<a href=\"$2\">$1</a>');\n },\n};\n\n/**\n * ICU plugin for basic ICU message format support\n */\nfunction parseICUBalanced(text: string, startPattern: RegExp): { match: string; content: string } | null {\n const match = text.match(startPattern);\n if (!match) return null;\n \n const start = match.index! + match[0].length;\n let braceCount = 1;\n let i = start;\n \n while (i < text.length && braceCount > 0) {\n if (text[i] === '{') braceCount++;\n else if (text[i] === '}') braceCount--;\n i++;\n }\n \n if (braceCount === 0) {\n const fullMatch = text.substring(match.index!, i);\n const content = text.substring(start, i - 1);\n return { match: fullMatch, content };\n }\n \n return null;\n}\n\nexport const icuPlugin: I18nPlugin = {\n name: 'icu',\n transform: (_key, value, _params, _locale) => {\n let result = value;\n \n // Handle basic ICU plural patterns\n if (_params && 'count' in _params) {\n const count = _params.count as number;\n \n // Pattern: {count, plural, =0 {no items} =1 {one item} other {# items}}\n const pluralInfo = parseICUBalanced(result, /\\{count,\\s*plural,\\s*/);\n if (pluralInfo) {\n const rules = pluralInfo.content;\n \n // Parse rules - handle =0, =1, one, other\n const zeroMatch = rules.match(/=0\\s*\\{([^}]+)\\}/);\n const oneMatch = rules.match(/=1\\s*\\{([^}]+)\\}/) || rules.match(/one\\s*\\{([^}]+)\\}/);\n const otherMatch = rules.match(/other\\s*\\{([^}]+)\\}/);\n \n let replacement = pluralInfo.match;\n if (count === 0 && zeroMatch) {\n replacement = zeroMatch[1];\n } else if (count === 1 && oneMatch) {\n replacement = oneMatch[1];\n } else if (otherMatch) {\n replacement = otherMatch[1].replace(/#/g, String(count));\n }\n \n result = result.replace(pluralInfo.match, replacement);\n }\n }\n \n // Handle basic ICU select patterns\n if (_params && 'gender' in _params) {\n const gender = _params.gender as string;\n \n // Pattern: {gender, select, male {He} female {She} other {They}}\n const selectInfo = parseICUBalanced(result, /\\{gender,\\s*select,\\s*/);\n if (selectInfo) {\n const rules = selectInfo.content;\n const genderMatch = rules.match(new RegExp(`${gender}\\\\s*\\\\{([^}]+)\\\\}`));\n const otherMatch = rules.match(/other\\s*\\{([^}]+)\\}/);\n \n let replacement = selectInfo.match;\n if (genderMatch) {\n replacement = genderMatch[1];\n } else if (otherMatch) {\n replacement = otherMatch[1];\n }\n \n result = result.replace(selectInfo.match, replacement);\n }\n }\n \n // Handle simple parameter replacement\n if (_params && 'name' in _params) {\n result = result.replace(/\\{name\\}/g, String(_params.name));\n }\n \n return result;\n },\n};"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils.ts","../src/core.ts","../src/plugins/icu.ts","../src/plugins/markdown.ts","../src/plugins.ts"],"names":["interpolate","template","params","formatters","locale","escape","match","key","replacement","replacePlaceholder","error","paramKey","format","s","value","formatter","formatted","deepMerge","target","source","result","existing","getNestedValue","obj","path","keys","current","createCache","options","cache","maxSize","firstKey","defaultPluralRules","count","pluralRulesCache","pluralRulesFor","rules","tag","getPluralForm","customRules","language","rule","createI18n","config","hasMessages","availableLocales","currentLocale","fallbackLocale","messages","plugins","listeners","translationCache","revision","notify","listener","handleError","context","err","parts","currency","plugin","getMessage","localeMessages","resolveMessage","locales","candidate","forms","form","pluralMessage","message","translate","paramKeys","sortedKeys","sortedParams","k","cacheKey","cached","resolved","messageLocale","transformed","escapers","escaped","t","setLocale","addMessages","newMessages","processedMessages","hasTranslation","checkLocale","addPlugin","existingIndex","p","removePlugin","pluginName","index","subscribe","formatNumber","formatDate","formatRelativeTime","baseDate","diffInSeconds","rtf","units","unit","secondsInUnit","InvalidPattern","MessageParser","pattern","token","number","literal","depth","pound","flush","legacy","start","name","kind","offset","choices","selector","option","intlLocale","numberOptions","cardinal","ordinal","numbers","render","part","selection","adjusted","exact","createICUPlugin","_key","escapeHtml","text","htmlEscapeMap","char","sanitizeHref","href","trimmed","createMarkdownPlugin","_params","_locale","placeholders","placeholderIndex","_","placeholder","i","markdownPlugin","icuPlugin"],"mappings":"aAMO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EACAC,CAAAA,CACQ,CACR,GAAI,OAAOJ,CAAAA,EAAa,SACtB,OAAO,MAAA,CAAOA,CAAQ,CAAA,CAGxB,GAAI,CACF,OAAOA,CAAAA,CAAS,QAAQ,kBAAA,CAAoB,CAACK,EAAOC,CAAAA,GAAQ,CAC1D,IAAMC,CAAAA,CAAcC,CAAAA,CAAmBF,CAAG,CAAA,CAC1C,OAAIC,IAAgB,KAAA,CAAA,CAAkBF,CAAAA,CAC/BD,EAASA,CAAAA,CAAOG,CAAW,EAAIA,CACxC,CAAC,CACH,CAAA,MAASE,C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8H,CAAAA,CAAGX,CAAAA,GAAS,CAC/C,IAAMY,CAAAA,CAAc,0BAA0BF,CAAgB,CAAA,EAAA,CAAA,CAC9D,OAAAD,CAAAA,CAAaC,CAAgB,EAAI,CAAA,MAAA,EAASX,CAAAA,CAAWC,CAAI,CAAC,CAAA,OAAA,CAAA,CAC1DU,IACOE,CACT,CAAC,EAGD/H,CAAAA,CAASkH,CAAAA,CAAWlH,CAAM,CAAA,CAG1B,IAAA,IAASgI,EAAI,CAAA,CAAGA,CAAAA,CAAIJ,EAAa,MAAA,CAAQI,CAAAA,EAAAA,CACvChI,EAASA,CAAAA,CAAO,OAAA,CAAQ,0BAA0BgI,CAAC,CAAA,EAAA,CAAA,CAAMJ,EAAaI,CAAC,CAAC,EAG1E,OAAOhI,CACT,CACF,CACF,KCxFaiI,EAAAA,CAA6BR,CAAAA,EAAqB,CAKlDS,EAAAA,CAAwBlB,CAAAA","file":"index.js","sourcesContent":["import type { TranslationParams, TranslationValue } from './types';\n\n/**\n * Replaces `{{name}}` / `{{name:format}}` placeholders with `params`. When `escape` is given\n * (e.g. by a plugin that produces HTML), every inserted value is passed through it.\n */\nexport function interpolate(\n template: string,\n params: TranslationParams,\n formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>,\n locale?: string,\n escape?: (value: string) => string\n): string {\n if (typeof template !== 'string') {\n return String(template);\n }\n \n try {\n return template.replace(/\\{\\{([^}]+)\\}\\}/g, (match, key) => {\n const replacement = replacePlaceholder(key);\n if (replacement === undefined) return match;\n return escape ? escape(replacement) : replacement;\n });\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Template interpolation error:', error);\n }\n return template;\n }\n\n function replacePlaceholder(key: string): string | undefined {\n try {\n const [paramKey, format] = key.trim().split(':').map((s: string) => s.trim());\n \n if (!Object.prototype.hasOwnProperty.call(params, paramKey)) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation parameter: ${paramKey}`);\n }\n return undefined; // Keep the original placeholder for missing parameters\n }\n \n const value = params[paramKey];\n \n if (format && formatters?.has(format)) {\n try {\n const formatter = formatters.get(format);\n if (!formatter) {\n return String(value);\n }\n const formatted = formatter(value, key.includes(':') ? key.split(':').slice(1).join(':') : undefined, locale);\n // Validate formatter returns a string\n if (typeof formatted !== 'string') {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter '${format}' must return a string, got ${typeof formatted}`);\n }\n return String(value);\n }\n return formatted;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter error for ${format}:`, error);\n }\n return String(value);\n }\n }\n \n if (value === null || value === undefined) {\n return '';\n }\n \n if (value instanceof Date) {\n // Use the provided locale parameter for locale-aware formatting\n return value.toLocaleDateString(locale || 'en-US', {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit'\n });\n }\n \n return String(value);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Parameter interpolation error:', error);\n }\n return undefined;\n }\n }\n}\n\nexport function deepMerge<T extends object>(\n target: T,\n source: Partial<T>\n): T {\n if (!target || typeof target !== 'object') {\n throw new Error('[i18n] Invalid target for deepMerge');\n }\n\n if (!source || typeof source !== 'object') {\n return target;\n }\n\n try {\n const result: Record<string, unknown> = { ...(target as Record<string, unknown>) };\n\n for (const key in source) {\n // SECURITY: Protect against prototype pollution\n // Block dangerous keys that could modify Object.prototype\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n key === 'prototype'\n ) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Blocked attempt to set dangerous property: ${key}`);\n }\n continue;\n }\n\n // Only process own properties (not inherited ones)\n if (!Object.prototype.hasOwnProperty.call(source, key)) {\n continue;\n }\n\n const value: unknown = source[key];\n if (value !== undefined) {\n if (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n ) {\n const existing = result[key];\n result[key] = deepMerge(\n existing && typeof existing === 'object' ? (existing as object) : {},\n value as Partial<object>\n );\n } else {\n result[key] = value;\n }\n }\n }\n\n return result as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] DeepMerge error:', error);\n }\n return target;\n }\n}\n\nexport function getNestedValue<T>(\n obj: Record<string, unknown>,\n path: string\n): T | undefined {\n if (!obj || typeof obj !== 'object' || !path || typeof path !== 'string') {\n return undefined;\n }\n \n try {\n const keys = path.split('.');\n let current: unknown = obj;\n \n for (const key of keys) {\n if (current && typeof current === 'object' && Object.prototype.hasOwnProperty.call(current, key)) {\n current = (current as Record<string, unknown>)[key];\n } else {\n return undefined;\n }\n }\n \n return current as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] getNestedValue error:', error);\n }\n return undefined;\n }\n}\n\nexport interface CacheOptions {\n maxSize?: number;\n}\n\nexport function createCache<T>(options?: CacheOptions): {\n get: (key: string) => T | undefined;\n set: (key: string, value: T) => void;\n clear: () => void;\n size: () => number;\n} {\n const cache = new Map<string, T>();\n const maxSize = options?.maxSize ?? 1000; // Default to 1000 entries\n\n return {\n get: (key: string) => {\n const value = cache.get(key);\n if (value !== undefined) {\n // LRU: Move to end by deleting and re-adding\n cache.delete(key);\n cache.set(key, value);\n }\n return value;\n },\n set: (key: string, value: T) => {\n // If key exists, delete it first (will re-add at end)\n if (cache.has(key)) {\n cache.delete(key);\n } else if (cache.size >= maxSize) {\n // Remove oldest entry (first entry in Map)\n const firstKey = cache.keys().next().value;\n if (firstKey !== undefined) {\n cache.delete(firstKey);\n }\n }\n cache.set(key, value);\n },\n clear: () => cache.clear(),\n size: () => cache.size,\n };\n}\n\n/**\n * @deprecated Kept for backwards compatibility. Plural categories are now resolved with\n * `Intl.PluralRules` (CLDR), which covers every locale; these hand-written rules are no\n * longer used by `getPluralForm` or `createI18n`.\n */\nexport const defaultPluralRules: Record<string, (count: number) => string> = {\n en: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n es: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n fr: (count: number) => {\n if (count === 0 || count === 1) return 'one';\n return 'other';\n },\n de: (count: number) => {\n if (count === 1) return 'one';\n return 'other';\n },\n ja: () => 'other',\n ko: () => 'other',\n zh: () => 'other',\n};\n\nconst pluralRulesCache = new Map<string, Intl.PluralRules>();\n\nfunction pluralRulesFor(locale: string): Intl.PluralRules {\n let rules = pluralRulesCache.get(locale);\n if (!rules) {\n try {\n const tag = locale.replace(/_/g, '-');\n // Unsupported locales use English rules instead of the runtime's default locale,\n // so results do not depend on the machine the code runs on.\n rules = new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(tag).length > 0 ? tag : 'en');\n } catch {\n rules = new Intl.PluralRules('en');\n }\n pluralRulesCache.set(locale, rules);\n }\n return rules;\n}\n\n/**\n * Returns the CLDR plural category (`zero`, `one`, `two`, `few`, `many` or `other`)\n * for `count` in `locale`.\n *\n * Custom rules are looked up by the exact locale first and then by its language\n * subtag (`pt-BR` → `pt`); otherwise `Intl.PluralRules` decides.\n */\nexport function getPluralForm(\n locale: string,\n count: number,\n customRules?: Record<string, (count: number) => string>\n): string {\n if (customRules) {\n const language = locale.split(/[-_]/)[0];\n const rule = Object.prototype.hasOwnProperty.call(customRules, locale)\n ? customRules[locale]\n : Object.prototype.hasOwnProperty.call(customRules, language)\n ? customRules[language]\n : undefined;\n if (typeof rule === 'function') return rule(count);\n }\n return pluralRulesFor(locale).select(count);\n}\n","import type {\n DeepPartial,\n I18nConfig,\n I18nInstance,\n I18nPlugin,\n LocaleCode,\n Messages,\n TranslationFunction,\n TranslationKey,\n TranslationParams,\n TranslationValue,\n} from './types';\nimport {\n createCache,\n deepMerge,\n getNestedValue,\n getPluralForm,\n interpolate,\n} from './utils';\n\nexport function createI18n<TMessages extends object = Messages>(\n config: I18nConfig<TMessages>\n): I18nInstance<TMessages> {\n // Validate config\n if (!config) {\n throw new Error('[i18n] Configuration is required');\n }\n if (!config.locale || typeof config.locale !== 'string' || config.locale.trim() === '') {\n throw new Error('[i18n] Locale must be a non-empty string');\n }\n if (!config.messages) {\n throw new Error('[i18n] Messages are required');\n }\n if (typeof config.messages !== 'object' || Array.isArray(config.messages) || config.messages === null) {\n throw new Error('[i18n] Messages must be an object');\n }\n // Warn if messages is empty but allow it for graceful degradation\n const hasMessages = Object.keys(config.messages).length > 0;\n if (!hasMessages) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn('[i18n] Messages object is empty - all translations will return keys');\n }\n }\n // Validate that the current locale exists in messages, unless a fallback is provided or messages is empty\n if (hasMessages && !(config.locale in config.messages) && !config.fallbackLocale) {\n const availableLocales = Object.keys(config.messages).join(', ');\n throw new Error(`[i18n] Locale '${config.locale}' not found in messages and no fallback locale provided. Available locales: ${availableLocales}`);\n }\n // Warn if current locale doesn't exist but fallback does\n if (!(config.locale in config.messages) && config.fallbackLocale) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n const availableLocales = Object.keys(config.messages).join(', ');\n console.warn(`[i18n] Locale '${config.locale}' not found in messages, will use fallback locale '${config.fallbackLocale}'. Available locales: ${availableLocales}`);\n }\n }\n // Validate fallback locale if provided\n if (config.fallbackLocale && !(config.fallbackLocale in config.messages)) {\n const availableLocales = Object.keys(config.messages).join(', ');\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Fallback locale '${config.fallbackLocale}' not found in messages. Available locales: ${availableLocales}`);\n }\n }\n\n let currentLocale = config.locale;\n const fallbackLocale = config.fallbackLocale;\n // Deep copy messages to prevent mutations to the original config\n const messages = structuredClone(config.messages);\n const plugins = [...(config.plugins || [])];\n const listeners = new Set<(locale: LocaleCode) => void>();\n const translationCache = createCache<string>();\n let revision = 0;\n\n const notify = (): void => {\n revision++;\n listeners.forEach(listener => {\n try {\n listener(currentLocale);\n } catch (error) {\n handleError(error, 'Locale change listener');\n }\n });\n };\n\n // Helper function for consistent error handling\n const handleError = (error: unknown, context: string): void => {\n const err = error instanceof Error ? error : new Error(String(error));\n // Call user-provided error handler in production\n if (config.onError) {\n try {\n config.onError(err, context);\n } catch {\n // Silently fail if error handler itself errors\n }\n }\n // Log in development\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] ${context}:`, err);\n }\n };\n\n const formatters = new Map<string, (value: TranslationValue, format?: string, locale?: string) => string>();\n \n // Built-in formatters\n formatters.set('number', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const options = config.formats?.number?.[format || 'default'] || {};\n return new Intl.NumberFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('date', (value, format, locale) => {\n if (!(value instanceof Date)) return String(value);\n const options = config.formats?.date?.[format || 'default'] || {};\n return new Intl.DateTimeFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('currency', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const parts = (format || 'currency:USD').split(':');\n const currency = parts.length > 1 ? parts[1] || 'USD' : 'USD';\n try {\n return new Intl.NumberFormat(locale || currentLocale, {\n style: 'currency',\n currency,\n }).format(value);\n } catch (error) {\n handleError(error, `Currency formatter error for currency '${currency}'`);\n return `${currency} ${value}`;\n }\n });\n \n // Register plugin formatters\n plugins.forEach(plugin => {\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) => \n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n });\n \n function getMessage(key: string, locale: LocaleCode): string | undefined {\n if (!Object.prototype.hasOwnProperty.call(messages, locale)) return undefined;\n const localeMessages = messages[locale] as Record<string, unknown> | undefined;\n if (!localeMessages || typeof localeMessages !== 'object') return undefined;\n\n // First try direct key access (for flat keys like 'user.role.admin'),\n // then nested access (for nested objects like { user: { role: { admin } } }).\n // Only own string values count: nested groups and Object.prototype members\n // ('constructor', 'toString', ...) are not translations.\n const value = Object.prototype.hasOwnProperty.call(localeMessages, key)\n ? localeMessages[key]\n : getNestedValue<unknown>(localeMessages, key);\n return typeof value === 'string' ? value : undefined;\n }\n\n function resolveMessage(\n key: string,\n params: TranslationParams | undefined,\n locale: LocaleCode\n ): { message: string; messageLocale: LocaleCode } | undefined {\n const locales = fallbackLocale && fallbackLocale !== locale ? [locale, fallbackLocale] : [locale];\n const count = params && Object.prototype.hasOwnProperty.call(params, 'count') ? params.count : undefined;\n\n for (const candidate of locales) {\n if (typeof count === 'number') {\n // Explicit zero form first (a common convention), then the CLDR category of the\n // catalog's own language, then the mandatory \"other\" form.\n const forms = new Set<string>();\n if (count === 0) forms.add('zero');\n forms.add(getPluralForm(candidate, count, config.pluralizationRules));\n forms.add('other');\n for (const form of forms) {\n const pluralMessage = getMessage(`${key}.${form}`, candidate);\n if (pluralMessage) return { message: pluralMessage, messageLocale: candidate };\n }\n }\n const message = getMessage(key, candidate);\n if (message) return { message, messageLocale: candidate };\n }\n return undefined;\n }\n\n function translate(\n key: string,\n params?: TranslationParams,\n locale: LocaleCode = currentLocale\n ): string {\n try {\n // Generate cache key with deterministic param serialization\n // Sort keys to ensure consistent caching regardless of property order\n let paramKey = '';\n if (params) {\n const paramKeys = Object.keys(params);\n if (paramKeys.length > 0) {\n try {\n // Fast path for single parameter\n if (paramKeys.length === 1) {\n const key = paramKeys[0];\n paramKey = `${key}:${JSON.stringify(params[key])}`;\n } else {\n // Sort only when multiple parameters exist\n const sortedKeys = paramKeys.sort();\n const sortedParams: Record<string, unknown> = {};\n for (const k of sortedKeys) {\n sortedParams[k] = params[k];\n }\n paramKey = JSON.stringify(sortedParams);\n }\n } catch (stringifyError) {\n // Handle circular references or other JSON.stringify errors\n // Use a simpler key based on param keys only\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn('[i18n] Failed to serialize params for caching, using fallback key');\n }\n paramKey = paramKeys.sort().join(',');\n }\n }\n }\n\n const cacheKey = `${locale}:${key}:${paramKey}`;\n const cached = translationCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const resolved = resolveMessage(key, params, locale);\n if (!resolved) {\n if (config.warnOnMissingTranslations && typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation: ${key} for locale: ${locale}`);\n }\n return key;\n }\n const { message, messageLocale } = resolved;\n\n // Apply plugins\n let result = message;\n for (const plugin of plugins) {\n if (plugin.transform) {\n try {\n const transformed = plugin.transform(key, result, params || {}, locale, messageLocale);\n // Validate plugin returns a string\n if (typeof transformed !== 'string') {\n handleError(\n new Error(`Plugin transform must return a string, got ${typeof transformed}`),\n `Plugin ${plugin.name} transform validation`\n );\n // Skip invalid transformation\n continue;\n }\n result = transformed;\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} transform`);\n }\n }\n }\n \n // Always interpolate to handle empty parameters. Plugins that emit HTML escape the\n // inserted values (otherwise a parameter could inject markup into that HTML).\n const escapers = plugins.filter(plugin => typeof plugin.escapeValue === 'function');\n result = interpolate(\n result,\n params || {},\n formatters,\n currentLocale,\n escapers.length > 0\n ? value => escapers.reduce((escaped, plugin) => plugin.escapeValue!(escaped), value)\n : undefined\n );\n \n translationCache.set(cacheKey, result);\n return result;\n } catch (error) {\n handleError(error, `Translation error for key ${key}`);\n return key;\n }\n }\n \n const t = ((key: string, params?: TranslationParams) =>\n translate(String(key), params)) as TranslationFunction<TMessages>;\n \n function setLocale(locale: LocaleCode): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n\n // Warn if locale doesn't exist in messages\n if (!messages[locale]) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(\n `[i18n] Locale '${locale}' not found in messages. Available locales: ${Object.keys(messages).join(', ')}`\n );\n }\n }\n\n if (locale !== currentLocale) {\n currentLocale = locale;\n translationCache.clear();\n notify();\n }\n }\n \n function addMessages(locale: LocaleCode, newMessages: DeepPartial<TMessages>): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n \n if (!newMessages || typeof newMessages !== 'object') {\n throw new Error('[i18n] Invalid messages provided');\n }\n \n try {\n if (!messages[locale]) {\n messages[locale] = {} as TMessages;\n }\n \n // Apply beforeLoad plugins\n let processedMessages = newMessages;\n for (const plugin of plugins) {\n if (plugin.beforeLoad) {\n try {\n const result = plugin.beforeLoad(locale, processedMessages as TMessages);\n // Validate plugin returns an object\n if (!result || typeof result !== 'object' || Array.isArray(result)) {\n handleError(\n new Error(`Plugin beforeLoad must return an object, got ${typeof result}`),\n `Plugin ${plugin.name} beforeLoad validation`\n );\n // Skip invalid transformation\n continue;\n }\n processedMessages = result as DeepPartial<TMessages>;\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} beforeLoad`);\n }\n }\n }\n \n messages[locale] = deepMerge(\n messages[locale] as Record<string, unknown>,\n processedMessages as Record<string, unknown>\n ) as TMessages;\n \n // Apply afterLoad plugins\n for (const plugin of plugins) {\n if (plugin.afterLoad) {\n try {\n plugin.afterLoad(locale, messages[locale]);\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} afterLoad`);\n }\n }\n }\n \n translationCache.clear();\n // Lazily loaded catalogs must re-render subscribers (e.g. React) that show the\n // active locale; other locales do not change any visible text.\n if (locale === currentLocale || locale === fallbackLocale) {\n notify();\n }\n } catch (error) {\n handleError(error, 'Error adding messages');\n throw error;\n }\n }\n \n function hasTranslation(key: TranslationKey<TMessages>, locale?: LocaleCode): boolean {\n const checkLocale = locale || currentLocale;\n const message = getMessage(String(key), checkLocale);\n return message !== undefined;\n }\n \n function addPlugin(plugin: I18nPlugin<TMessages>): void {\n // Check for duplicate plugin names\n const existingIndex = plugins.findIndex(p => p.name === plugin.name);\n if (existingIndex !== -1) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Plugin '${plugin.name}' already registered. Replacing existing plugin.`);\n }\n // Remove existing plugin first\n plugins.splice(existingIndex, 1);\n }\n\n plugins.push(plugin);\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) =>\n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n translationCache.clear();\n }\n \n function removePlugin(pluginName: string): void {\n const index = plugins.findIndex(p => p.name === pluginName);\n if (index !== -1) {\n plugins.splice(index, 1);\n formatters.delete(pluginName);\n translationCache.clear();\n }\n }\n \n function subscribe(listener: (locale: LocaleCode) => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n \n function formatNumber(value: number, format?: string): string {\n const formatter = formatters.get('number');\n if (!formatter) {\n throw new Error('[i18n] Number formatter not available. Please add a plugin that provides number formatting.');\n }\n return formatter(value, format, currentLocale);\n }\n\n function formatDate(value: Date, format?: string): string {\n const formatter = formatters.get('date');\n if (!formatter) {\n throw new Error('[i18n] Date formatter not available. Please add a plugin that provides date formatting.');\n }\n return formatter(value, format, currentLocale);\n }\n \n function formatRelativeTime(value: Date, baseDate: Date = new Date()): string {\n // Validate that value is a valid Date\n if (!(value instanceof Date) || isNaN(value.getTime())) {\n throw new Error('[i18n] Invalid date provided to formatRelativeTime');\n }\n // Validate that baseDate is a valid Date\n if (!(baseDate instanceof Date) || isNaN(baseDate.getTime())) {\n throw new Error('[i18n] Invalid base date provided to formatRelativeTime');\n }\n\n const diffInSeconds = Math.floor((value.getTime() - baseDate.getTime()) / 1000);\n const rtf = new Intl.RelativeTimeFormat(currentLocale, { numeric: 'auto' });\n \n const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [\n ['year', 60 * 60 * 24 * 365],\n ['month', 60 * 60 * 24 * 30],\n ['week', 60 * 60 * 24 * 7],\n ['day', 60 * 60 * 24],\n ['hour', 60 * 60],\n ['minute', 60],\n ['second', 1],\n ];\n \n for (const [unit, secondsInUnit] of units) {\n if (Math.abs(diffInSeconds) >= secondsInUnit) {\n return rtf.format(Math.round(diffInSeconds / secondsInUnit), unit);\n }\n }\n \n return rtf.format(0, 'second');\n }\n \n return {\n get locale() {\n return currentLocale;\n },\n get fallbackLocale() {\n return fallbackLocale;\n },\n get messages() {\n return messages;\n },\n get revision() {\n return revision;\n },\n t,\n setLocale,\n getLocale: () => currentLocale,\n hasTranslation,\n addMessages,\n addPlugin,\n removePlugin,\n subscribe,\n formatNumber,\n formatDate,\n formatRelativeTime,\n };\n}\n","import type { I18nPlugin, TranslationParams } from '../types';\n\ntype ChoiceKind = 'plural' | 'select' | 'selectordinal';\ntype Part = string\n | { kind: 'value'; name: string; source: string }\n | { kind: 'number' }\n | { kind: ChoiceKind; name: string; source: string; choices: Map<string, Part[]>; offset: number };\n\nclass InvalidPattern extends Error {}\n\nclass MessageParser {\n private cursor = 0;\n\n constructor(private readonly source: string) {}\n\n parse(): Part[] {\n return this.message(0, false).parts;\n }\n\n private take(pattern: RegExp): string | undefined {\n pattern.lastIndex = this.cursor;\n const token = pattern.exec(this.source)?.[0];\n if (token !== undefined) this.cursor += token.length;\n return token;\n }\n\n private expect(pattern: RegExp): string {\n const token = this.take(pattern);\n if (token === undefined) throw new InvalidPattern();\n return token;\n }\n\n private space(): void {\n this.take(/\\s+/y);\n }\n\n private number(): number {\n const number = Number(this.expect(/[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?/y));\n if (!Number.isFinite(number)) throw new InvalidPattern();\n return number;\n }\n\n private quote(): string {\n let literal = '';\n this.cursor++;\n while (this.cursor < this.source.length) {\n const current = this.source.charAt(this.cursor++);\n if (current === \"'\" && !this.take(/'/y)) break;\n literal += current;\n }\n return literal;\n }\n\n private message(depth: number, pound: boolean): { parts: Part[]; closed: boolean } {\n if (depth > 64) throw new InvalidPattern();\n const parts: Part[] = [];\n let literal = '';\n function flush() {\n if (literal) parts.push(literal);\n literal = '';\n }\n while (this.cursor < this.source.length) {\n const current = this.source.charAt(this.cursor);\n if (current === '}') {\n if (depth === 0) throw new InvalidPattern();\n this.cursor++;\n flush();\n return { parts, closed: true };\n }\n if (current === '{') {\n const legacy = this.take(/\\{\\{[^{}]*\\}\\}/y);\n if (legacy !== undefined) literal += legacy;\n else {\n flush();\n parts.push(this.argument(depth));\n }\n } else if (current === \"'\" && this.take(/''/y)) {\n literal += \"'\";\n } else if (current === \"'\" && (\n ['{', '}'].includes(this.source.charAt(this.cursor + 1)) ||\n (pound && this.source.charAt(this.cursor + 1) === '#')\n )) {\n literal += this.quote();\n } else {\n this.cursor++;\n if (current === '#' && pound) {\n flush();\n parts.push({ kind: 'number' });\n } else literal += current;\n }\n }\n flush();\n return { parts, closed: false };\n }\n\n private argument(depth: number): Part {\n const start = this.cursor++;\n this.space();\n const name = this.expect(/[\\p{ID_Continue}]+/uy);\n this.space();\n if (this.take(/\\}/y)) return { kind: 'value', name, source: this.source.slice(start, this.cursor) };\n this.expect(/,/y);\n this.space();\n const kind = this.expect(/selectordinal|plural|select/y) as ChoiceKind; // The scanner accepts only these three literals.\n this.space();\n this.expect(/,/y);\n this.space();\n const offset = kind !== 'select' && this.take(/offset\\s*:\\s*/y) ? this.number() : 0;\n this.space();\n const choices = new Map<string, Part[]>();\n while (!this.take(/\\}/y)) {\n const selector = kind !== 'select' && this.take(/=/y)\n ? '=' + this.number()\n : this.expect(/[\\p{ID_Continue}]+/uy);\n this.space();\n this.expect(/\\{/y);\n const option = this.message(depth + 1, kind !== 'select');\n if (!option.closed) throw new InvalidPattern();\n if (!choices.has(selector)) choices.set(selector, option.parts);\n this.space();\n }\n if (!choices.has('other')) throw new InvalidPattern();\n return { kind, name, choices, offset, source: this.source.slice(start, this.cursor) };\n }\n}\n\nfunction language(locale: string): string {\n try {\n return Intl.getCanonicalLocales(locale.replace(/_/g, '-'))[0] ?? 'en';\n } catch {\n return 'en';\n }\n}\n\nfunction format(parts: Part[], params: TranslationParams, locale: string): string {\n const intlLocale = language(locale);\n const numberOptions = { maximumSignificantDigits: 21 };\n let cardinal: Intl.PluralRules | undefined;\n let ordinal: Intl.PluralRules | undefined;\n let numbers: Intl.NumberFormat | undefined;\n\n function render(message: Part[], pound?: number): string {\n return message.map(part => {\n if (typeof part === 'string') return part;\n if (part.kind === 'number') {\n return pound === undefined ? '#' : (numbers ??= new Intl.NumberFormat(intlLocale, numberOptions)).format(pound);\n }\n if (!Object.hasOwn(params, part.name)) return part.source;\n const value = params[part.name];\n if (part.kind === 'value') return String(value);\n if (part.kind === 'select') {\n const selection = part.choices.get(String(value)) ?? part.choices.get('other');\n return selection ? render(selection) : part.source;\n }\n if (typeof value !== 'number' || !Number.isFinite(value)) return part.source;\n const adjusted = value - part.offset;\n if (!Number.isFinite(adjusted)) return part.source;\n const exact = part.choices.get('=' + value);\n if (exact) return render(exact, adjusted);\n const rules = part.kind === 'plural'\n ? (cardinal ??= new Intl.PluralRules(intlLocale, numberOptions))\n : (ordinal ??= new Intl.PluralRules(intlLocale, { ...numberOptions, type: 'ordinal' }));\n const selection = part.choices.get(rules.select(adjusted)) ?? part.choices.get('other');\n return selection ? render(selection, adjusted) : part.source;\n }).join('');\n }\n\n return render(parts);\n}\n\nexport function createICUPlugin(): I18nPlugin {\n return {\n name: 'icu',\n transform: (_key, value, params, locale, messageLocale) => {\n if (!/[{']/.test(value)) return value;\n try {\n return format(new MessageParser(value).parse(), params, messageLocale ?? locale);\n } catch (error) {\n if (error instanceof InvalidPattern) return value;\n throw error;\n }\n },\n };\n}\n","import type { I18nPlugin } from '../types';\n\n/**\n * Escapes HTML special characters to prevent XSS attacks\n */\nfunction escapeHtml(text: string): string {\n const htmlEscapeMap: Record<string, string> = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '/': '/',\n };\n return text.replace(/[&<>\"'/]/g, (char) => htmlEscapeMap[char]);\n}\n\n/**\n * Sanitizes href attribute to prevent javascript: and data: URIs\n */\nfunction sanitizeHref(href: string): string {\n const trimmed = href.trim().toLowerCase();\n // Block javascript:, data:, vbscript:, and other dangerous protocols\n if (\n trimmed.startsWith('javascript:') ||\n trimmed.startsWith('data:') ||\n trimmed.startsWith('vbscript:') ||\n trimmed.startsWith('file:')\n ) {\n return '#';\n }\n return escapeHtml(href);\n}\n\n/**\n * Converts `**bold**`, `*italic*`, `` `code` `` and `[text](url)` to HTML and escapes the\n * rest of the message. Interpolated `{{values}}` are HTML-escaped too. Register it after\n * `icuPlugin` so ICU arguments are escaped as part of the message.\n */\nexport function createMarkdownPlugin(): I18nPlugin {\n return {\n name: 'markdown',\n escapeValue: escapeHtml,\n transform: (_key, value, _params, _locale) => {\n // Simple markdown transformations with XSS protection\n // We need to be careful not to double-escape\n let result = value;\n\n // Store placeholders for processed markdown to avoid conflicts\n const placeholders: string[] = [];\n let placeholderIndex = 0;\n\n // [text](url) -> <a href=\"url\">text</a>\n result = result.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, (_, text, href) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<a href=\"${sanitizeHref(href)}\">${escapeHtml(text)}</a>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // **bold** -> <strong>text</strong>\n result = result.replace(/\\*\\*(.*?)\\*\\*/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<strong>${escapeHtml(text)}</strong>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // *italic* -> <em>text</em>\n result = result.replace(/\\*(.*?)\\*/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<em>${escapeHtml(text)}</em>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // `code` -> <code>text</code>\n result = result.replace(/`(.*?)`/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<code>${escapeHtml(text)}</code>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // Escape any remaining text that wasn't part of markdown\n result = escapeHtml(result);\n\n // Restore placeholders\n for (let i = 0; i < placeholders.length; i++) {\n result = result.replace(`__MARKDOWN_PLACEHOLDER_${i}__`, placeholders[i]);\n }\n\n return result;\n },\n };\n}","import { createICUPlugin } from './plugins/icu';\nimport { createMarkdownPlugin } from './plugins/markdown';\nimport type { I18nPlugin } from './types';\n\n/**\n * Markdown plugin for basic markdown syntax transformation.\n */\nexport const markdownPlugin: I18nPlugin = createMarkdownPlugin();\n\n/**\n * ICU MessageFormat plugin for named arguments, plural forms and select branches.\n */\nexport const icuPlugin: I18nPlugin = createICUPlugin();\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function w(r,n,o,i){if(typeof r!="string")return String(r);try{return r.replace(/\{\{([^}]+)\}\}/g,(a,l)=>{try{let[f,u]=l.trim().split(":").map(g=>g.trim());if(!(f in n))return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation parameter: ${f}`),a;let d=n[f];if(u&&o?.has(u))try{return o.get(u)(d,l.includes(":")?l.split(":").slice(1).join(":"):void 0,i)}catch(g){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter error for ${u}:`,g),String(d)}return d==null?"":d instanceof Date?d.toLocaleDateString():String(d)}catch(f){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Parameter interpolation error:",f),a}})}catch(a){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Template interpolation error:",a),r}}function N(r,n){if(!r||typeof r!="object")throw new Error("[i18n] Invalid target for deepMerge");if(!n||typeof n!="object")return r;try{let o={...r};for(let i in n)n[i]!==void 0&&(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!(n[i]instanceof Date)?o[i]=N(o[i]||{},n[i]):o[i]=n[i]);return o}catch(o){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] DeepMerge error:",o),r}}function I(r,n){if(!(!r||typeof r!="object"||!n||typeof n!="string"))try{let o=n.split("."),i=r;for(let a of o)if(i&&typeof i=="object"&&a in i)i=i[a];else return;return i}catch(o){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] getNestedValue error:",o);return}}function D(){let r=new Map;return {get:n=>r.get(n),set:(n,o)=>{r.set(n,o);},clear:()=>r.clear()}}var _={en:r=>r===0?"zero":r===1?"one":"other",es:r=>r===0?"zero":r===1?"one":"other",fr:r=>r===0||r===1?"one":"other",de:r=>r===1?"one":"other",ja:()=>"other",ko:()=>"other",zh:()=>"other"};function P(r,n,o){let i=o||_;return (i[r]||i.en)(n)}function k(r){if(!r)throw new Error("[i18n] Configuration is required");if(!r.locale)throw new Error("[i18n] Locale is required");if(!r.messages)throw new Error("[i18n] Messages are required");let n=r.locale,o=r.fallbackLocale,i={...r.messages},a=[...r.plugins||[]],l=new Set,f=D(),u=new Map;u.set("number",(e,s,t)=>{if(typeof e!="number")return String(e);let c=r.formats?.number?.[s||"default"]||{};return new Intl.NumberFormat(t||n,c).format(e)}),u.set("date",(e,s,t)=>{if(!(e instanceof Date))return String(e);let c=r.formats?.date?.[s||"default"]||{};return new Intl.DateTimeFormat(t||n,c).format(e)}),u.set("currency",(e,s,t)=>{if(typeof e!="number")return String(e);let c=(s||"currency:USD").split(":"),p=c.length>1&&c[1]||"USD";try{return new Intl.NumberFormat(t||n,{style:"currency",currency:p}).format(e)}catch{return `${p} ${e}`}}),a.forEach(e=>{e.format&&u.set(e.name,(s,t,c)=>e.format(s,t??"",c??n));});function d(e,s){let t=i[s];if(t)return e in t?t[e]:I(t,e)}function g(e,s,t=n){try{let c=`${t}:${e}:${JSON.stringify(s||{})}`,p=f.get(c);if(p)return p;let m=d(e,t);if(!m&&o&&t!==o&&(m=d(e,o)),s&&"count"in s&&typeof s.count=="number"){let E=P(t,s.count,r.pluralizationRules),M=`${e}.${E}`,b=d(M,t);if(!b&&o&&t!==o){let v=d(M,o);v&&(m=v);}else b&&(m=b);}if(!m)return r.warnOnMissingTranslations&&typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation: ${e} for locale: ${t}`),e;let h=m;for(let E of a)if(E.transform)try{h=E.transform(e,h,s||{},t);}catch(M){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Plugin ${E.name} transform error:`,M);}return h=w(h,s||{},u,n),f.set(c,h),h}catch(c){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Translation error for key ${e}:`,c),e}}let y=(e,...s)=>{let t=s[0];return g(String(e),t)};function T(e){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");e!==n&&(n=e,f.clear(),l.forEach(s=>{try{s(e);}catch(t){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Locale change listener error:",t);}}));}function $(e,s){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");if(!s||typeof s!="object")throw new Error("[i18n] Invalid messages provided");try{i[e]||(i[e]={});let t=s;for(let c of a)if(c.beforeLoad)try{t=c.beforeLoad(e,t);}catch(p){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Plugin ${c.name} beforeLoad error:`,p);}i[e]=N(i[e],t);for(let c of a)if(c.afterLoad)try{c.afterLoad(e,i[e]);}catch(p){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Plugin ${c.name} afterLoad error:`,p);}f.clear();}catch(t){throw typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Error adding messages:",t),t}}function V(e,s){let t=s||n;return d(String(e),t)!==void 0}function S(e){a.push(e),e.format&&u.set(e.name,(s,t,c)=>e.format(s,t??"",c??n)),f.clear();}function x(e){let s=a.findIndex(t=>t.name===e);s!==-1&&(a.splice(s,1),u.delete(e),f.clear());}function C(e){return l.add(e),()=>l.delete(e)}function O(e,s){return u.get("number")(e,s,n)}function F(e,s){return u.get("date")(e,s,n)}function R(e,s=new Date){let t=Math.floor((e.getTime()-s.getTime())/1e3),c=new Intl.RelativeTimeFormat(n,{numeric:"auto"}),p=[["year",60*60*24*365],["month",60*60*24*30],["week",60*60*24*7],["day",60*60*24],["hour",60*60],["minute",60],["second",1]];for(let[m,h]of p)if(Math.abs(t)>=h)return c.format(Math.round(t/h),m);return c.format(0,"second")}return {get locale(){return n},get fallbackLocale(){return o},get messages(){return i},t:y,setLocale:T,getLocale:()=>n,hasTranslation:V,addMessages:$,addPlugin:S,removePlugin:x,subscribe:C,formatNumber:O,formatDate:F,formatRelativeTime:R}}var q={name:"markdown",transform:(r,n,o,i)=>n.replace(/\*\*(.*?)\*\*/g,"<strong>$1</strong>").replace(/\*(.*?)\*/g,"<em>$1</em>").replace(/`(.*?)`/g,"<code>$1</code>").replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2">$1</a>')};function L(r,n){let o=r.match(n);if(!o)return null;let i=o.index+o[0].length,a=1,l=i;for(;l<r.length&&a>0;)r[l]==="{"?a++:r[l]==="}"&&a--,l++;if(a===0){let f=r.substring(o.index,l),u=r.substring(i,l-1);return {match:f,content:u}}return null}var A={name:"icu",transform:(r,n,o,i)=>{let a=n;if(o&&"count"in o){let l=o.count,f=L(a,/\{count,\s*plural,\s*/);if(f){let u=f.content,d=u.match(/=0\s*\{([^}]+)\}/),g=u.match(/=1\s*\{([^}]+)\}/)||u.match(/one\s*\{([^}]+)\}/),y=u.match(/other\s*\{([^}]+)\}/),T=f.match;l===0&&d?T=d[1]:l===1&&g?T=g[1]:y&&(T=y[1].replace(/#/g,String(l))),a=a.replace(f.match,T);}}if(o&&"gender"in o){let l=o.gender,f=L(a,/\{gender,\s*select,\s*/);if(f){let u=f.content,d=u.match(new RegExp(`${l}\\s*\\{([^}]+)\\}`)),g=u.match(/other\s*\{([^}]+)\}/),y=f.match;d?y=d[1]:g&&(y=g[1]),a=a.replace(f.match,y);}}return o&&"name"in o&&(a=a.replace(/\{name\}/g,String(o.name))),a}};export{D as createCache,k as createI18n,N as deepMerge,_ as defaultPluralRules,I as getNestedValue,P as getPluralForm,A as icuPlugin,w as interpolate,q as markdownPlugin};//# sourceMappingURL=index.mjs.map
|
|
1
|
+
function V(r,t,s,o,n){if(typeof r!="string")return String(r);try{return r.replace(/\{\{([^}]+)\}\}/g,(u,d)=>{let p=c(d);return p===void 0?u:n?n(p):p})}catch(u){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Template interpolation error:",u),r}function c(u){try{let[d,p]=u.trim().split(":").map(h=>h.trim());if(!Object.prototype.hasOwnProperty.call(t,d)){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation parameter: ${d}`);return}let m=t[d];if(p&&s?.has(p))try{let h=s.get(p);if(!h)return String(m);let f=h(m,u.includes(":")?u.split(":").slice(1).join(":"):void 0,o);return typeof f!="string"?(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter '${p}' must return a string, got ${typeof f}`),String(m)):f}catch(h){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter error for ${p}:`,h),String(m)}return m==null?"":m instanceof Date?m.toLocaleDateString(o||"en-US",{year:"numeric",month:"2-digit",day:"2-digit"}):String(m)}catch(d){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Parameter interpolation error:",d);return}}}function M(r,t){if(!r||typeof r!="object")throw new Error("[i18n] Invalid target for deepMerge");if(!t||typeof t!="object")return r;try{let s={...r};for(let o in t){if(o==="__proto__"||o==="constructor"||o==="prototype"){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Blocked attempt to set dangerous property: ${o}`);continue}if(!Object.prototype.hasOwnProperty.call(t,o))continue;let n=t[o];if(n!==void 0)if(typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof Date)){let c=s[o];s[o]=M(c&&typeof c=="object"?c:{},n);}else s[o]=n;}return s}catch(s){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] DeepMerge error:",s),r}}function A(r,t){if(!(!r||typeof r!="object"||!t||typeof t!="string"))try{let s=t.split("."),o=r;for(let n of s)if(o&&typeof o=="object"&&Object.prototype.hasOwnProperty.call(o,n))o=o[n];else return;return o}catch(s){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] getNestedValue error:",s);return}}function F(r){let t=new Map,s=r?.maxSize??1e3;return {get:o=>{let n=t.get(o);return n!==void 0&&(t.delete(o),t.set(o,n)),n},set:(o,n)=>{if(t.has(o))t.delete(o);else if(t.size>=s){let c=t.keys().next().value;c!==void 0&&t.delete(c);}t.set(o,n);},clear:()=>t.clear(),size:()=>t.size}}var te={en:r=>r===0?"zero":r===1?"one":"other",es:r=>r===0?"zero":r===1?"one":"other",fr:r=>r===0||r===1?"one":"other",de:r=>r===1?"one":"other",ja:()=>"other",ko:()=>"other",zh:()=>"other"},S=new Map;function X(r){let t=S.get(r);if(!t){try{let s=r.replace(/_/g,"-");t=new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(s).length>0?s:"en");}catch{t=new Intl.PluralRules("en");}S.set(r,t);}return t}function K(r,t,s){if(s){let o=r.split(/[-_]/)[0],n=Object.prototype.hasOwnProperty.call(s,r)?s[r]:Object.prototype.hasOwnProperty.call(s,o)?s[o]:void 0;if(typeof n=="function")return n(t)}return X(r).select(t)}function Y(r){if(!r)throw new Error("[i18n] Configuration is required");if(!r.locale||typeof r.locale!="string"||r.locale.trim()==="")throw new Error("[i18n] Locale must be a non-empty string");if(!r.messages)throw new Error("[i18n] Messages are required");if(typeof r.messages!="object"||Array.isArray(r.messages)||r.messages===null)throw new Error("[i18n] Messages must be an object");let t=Object.keys(r.messages).length>0;if(t||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Messages object is empty - all translations will return keys"),t&&!(r.locale in r.messages)&&!r.fallbackLocale){let e=Object.keys(r.messages).join(", ");throw new Error(`[i18n] Locale '${r.locale}' not found in messages and no fallback locale provided. Available locales: ${e}`)}if(!(r.locale in r.messages)&&r.fallbackLocale&&typeof process<"u"&&process.env?.NODE_ENV!=="production"){let e=Object.keys(r.messages).join(", ");console.warn(`[i18n] Locale '${r.locale}' not found in messages, will use fallback locale '${r.fallbackLocale}'. Available locales: ${e}`);}if(r.fallbackLocale&&!(r.fallbackLocale in r.messages)){let e=Object.keys(r.messages).join(", ");typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Fallback locale '${r.fallbackLocale}' not found in messages. Available locales: ${e}`);}let s=r.locale,o=r.fallbackLocale,n=structuredClone(r.messages),c=[...r.plugins||[]],u=new Set,d=F(),p=0,m=()=>{p++,u.forEach(e=>{try{e(s);}catch(i){h(i,"Locale change listener");}});},h=(e,i)=>{let a=e instanceof Error?e:new Error(String(e));if(r.onError)try{r.onError(a,i);}catch{}typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] ${i}:`,a);},f=new Map;f.set("number",(e,i,a)=>{if(typeof e!="number")return String(e);let l=r.formats?.number?.[i||"default"]||{};return new Intl.NumberFormat(a||s,l).format(e)}),f.set("date",(e,i,a)=>{if(!(e instanceof Date))return String(e);let l=r.formats?.date?.[i||"default"]||{};return new Intl.DateTimeFormat(a||s,l).format(e)}),f.set("currency",(e,i,a)=>{if(typeof e!="number")return String(e);let l=(i||"currency:USD").split(":"),g=l.length>1&&l[1]||"USD";try{return new Intl.NumberFormat(a||s,{style:"currency",currency:g}).format(e)}catch(w){return h(w,`Currency formatter error for currency '${g}'`),`${g} ${e}`}}),c.forEach(e=>{e.format&&f.set(e.name,(i,a,l)=>e.format(i,a??"",l??s));});function P(e,i){if(!Object.prototype.hasOwnProperty.call(n,i))return;let a=n[i];if(!a||typeof a!="object")return;let l=Object.prototype.hasOwnProperty.call(a,e)?a[e]:A(a,e);return typeof l=="string"?l:void 0}function L(e,i,a){let l=o&&o!==a?[a,o]:[a],g=i&&Object.prototype.hasOwnProperty.call(i,"count")?i.count:void 0;for(let w of l){if(typeof g=="number"){let O=new Set;g===0&&O.add("zero"),O.add(K(w,g,r.pluralizationRules)),O.add("other");for(let $ of O){let v=P(`${e}.${$}`,w);if(v)return {message:v,messageLocale:w}}}let _=P(e,w);if(_)return {message:_,messageLocale:w}}}function N(e,i,a=s){try{let l="";if(i){let y=Object.keys(i);if(y.length>0)try{if(y.length===1){let b=y[0];l=`${b}:${JSON.stringify(i[b])}`;}else {let b=y.sort(),D={};for(let C of b)D[C]=i[C];l=JSON.stringify(D);}}catch{typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Failed to serialize params for caching, using fallback key"),l=y.sort().join(",");}}let g=`${a}:${e}:${l}`,w=d.get(g);if(w!==void 0)return w;let _=L(e,i,a);if(!_)return r.warnOnMissingTranslations&&typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation: ${e} for locale: ${a}`),e;let{message:O,messageLocale:$}=_,v=O;for(let y of c)if(y.transform)try{let b=y.transform(e,v,i||{},a,$);if(typeof b!="string"){h(new Error(`Plugin transform must return a string, got ${typeof b}`),`Plugin ${y.name} transform validation`);continue}v=b;}catch(b){h(b,`Plugin ${y.name} transform`);}let R=c.filter(y=>typeof y.escapeValue=="function");return v=V(v,i||{},f,s,R.length>0?y=>R.reduce((b,D)=>D.escapeValue(b),y):void 0),d.set(g,v),v}catch(l){return h(l,`Translation error for key ${e}`),e}}let x=(e,i)=>N(String(e),i);function T(e){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");n[e]||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Locale '${e}' not found in messages. Available locales: ${Object.keys(n).join(", ")}`),e!==s&&(s=e,d.clear(),m());}function I(e,i){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");if(!i||typeof i!="object")throw new Error("[i18n] Invalid messages provided");try{n[e]||(n[e]={});let a=i;for(let l of c)if(l.beforeLoad)try{let g=l.beforeLoad(e,a);if(!g||typeof g!="object"||Array.isArray(g)){h(new Error(`Plugin beforeLoad must return an object, got ${typeof g}`),`Plugin ${l.name} beforeLoad validation`);continue}a=g;}catch(g){h(g,`Plugin ${l.name} beforeLoad`);}n[e]=M(n[e],a);for(let l of c)if(l.afterLoad)try{l.afterLoad(e,n[e]);}catch(g){h(g,`Plugin ${l.name} afterLoad`);}d.clear(),(e===s||e===o)&&m();}catch(a){throw h(a,"Error adding messages"),a}}function U(e,i){let a=i||s;return P(String(e),a)!==void 0}function H(e){let i=c.findIndex(a=>a.name===e.name);i!==-1&&(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Plugin '${e.name}' already registered. Replacing existing plugin.`),c.splice(i,1)),c.push(e),e.format&&f.set(e.name,(a,l,g)=>e.format(a,l??"",g??s)),d.clear();}function q(e){let i=c.findIndex(a=>a.name===e);i!==-1&&(c.splice(i,1),f.delete(e),d.clear());}function J(e){return u.add(e),()=>u.delete(e)}function B(e,i){let a=f.get("number");if(!a)throw new Error("[i18n] Number formatter not available. Please add a plugin that provides number formatting.");return a(e,i,s)}function G(e,i){let a=f.get("date");if(!a)throw new Error("[i18n] Date formatter not available. Please add a plugin that provides date formatting.");return a(e,i,s)}function Q(e,i=new Date){if(!(e instanceof Date)||isNaN(e.getTime()))throw new Error("[i18n] Invalid date provided to formatRelativeTime");if(!(i instanceof Date)||isNaN(i.getTime()))throw new Error("[i18n] Invalid base date provided to formatRelativeTime");let a=Math.floor((e.getTime()-i.getTime())/1e3),l=new Intl.RelativeTimeFormat(s,{numeric:"auto"}),g=[["year",60*60*24*365],["month",60*60*24*30],["week",60*60*24*7],["day",60*60*24],["hour",60*60],["minute",60],["second",1]];for(let[w,_]of g)if(Math.abs(a)>=_)return l.format(Math.round(a/_),w);return l.format(0,"second")}return {get locale(){return s},get fallbackLocale(){return o},get messages(){return n},get revision(){return p},t:x,setLocale:T,getLocale:()=>s,hasTranslation:U,addMessages:I,addPlugin:H,removePlugin:q,subscribe:J,formatNumber:B,formatDate:G,formatRelativeTime:Q}}var E=class extends Error{},j=class{constructor(t){this.source=t;}cursor=0;parse(){return this.message(0,false).parts}take(t){t.lastIndex=this.cursor;let s=t.exec(this.source)?.[0];return s!==void 0&&(this.cursor+=s.length),s}expect(t){let s=this.take(t);if(s===void 0)throw new E;return s}space(){this.take(/\s+/y);}number(){let t=Number(this.expect(/[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/y));if(!Number.isFinite(t))throw new E;return t}quote(){let t="";for(this.cursor++;this.cursor<this.source.length;){let s=this.source.charAt(this.cursor++);if(s==="'"&&!this.take(/'/y))break;t+=s;}return t}message(t,s){if(t>64)throw new E;let o=[],n="";function c(){n&&o.push(n),n="";}for(;this.cursor<this.source.length;){let u=this.source.charAt(this.cursor);if(u==="}"){if(t===0)throw new E;return this.cursor++,c(),{parts:o,closed:true}}if(u==="{"){let d=this.take(/\{\{[^{}]*\}\}/y);d!==void 0?n+=d:(c(),o.push(this.argument(t)));}else u==="'"&&this.take(/''/y)?n+="'":u==="'"&&(["{","}"].includes(this.source.charAt(this.cursor+1))||s&&this.source.charAt(this.cursor+1)==="#")?n+=this.quote():(this.cursor++,u==="#"&&s?(c(),o.push({kind:"number"})):n+=u);}return c(),{parts:o,closed:false}}argument(t){let s=this.cursor++;this.space();let o=this.expect(/[\p{ID_Continue}]+/uy);if(this.space(),this.take(/\}/y))return {kind:"value",name:o,source:this.source.slice(s,this.cursor)};this.expect(/,/y),this.space();let n=this.expect(/selectordinal|plural|select/y);this.space(),this.expect(/,/y),this.space();let c=n!=="select"&&this.take(/offset\s*:\s*/y)?this.number():0;this.space();let u=new Map;for(;!this.take(/\}/y);){let d=n!=="select"&&this.take(/=/y)?"="+this.number():this.expect(/[\p{ID_Continue}]+/uy);this.space(),this.expect(/\{/y);let p=this.message(t+1,n!=="select");if(!p.closed)throw new E;u.has(d)||u.set(d,p.parts),this.space();}if(!u.has("other"))throw new E;return {kind:n,name:o,choices:u,offset:c,source:this.source.slice(s,this.cursor)}}};function Z(r){try{return Intl.getCanonicalLocales(r.replace(/_/g,"-"))[0]??"en"}catch{return "en"}}function ee(r,t,s){let o=Z(s),n={maximumSignificantDigits:21},c,u,d;function p(m,h){return m.map(f=>{if(typeof f=="string")return f;if(f.kind==="number")return h===void 0?"#":(d??=new Intl.NumberFormat(o,n)).format(h);if(!Object.hasOwn(t,f.name))return f.source;let P=t[f.name];if(f.kind==="value")return String(P);if(f.kind==="select"){let I=f.choices.get(String(P))??f.choices.get("other");return I?p(I):f.source}if(typeof P!="number"||!Number.isFinite(P))return f.source;let L=P-f.offset;if(!Number.isFinite(L))return f.source;let N=f.choices.get("="+P);if(N)return p(N,L);let x=f.kind==="plural"?c??=new Intl.PluralRules(o,n):u??=new Intl.PluralRules(o,{...n,type:"ordinal"}),T=f.choices.get(x.select(L))??f.choices.get("other");return T?p(T,L):f.source}).join("")}return p(r)}function z(){return {name:"icu",transform:(r,t,s,o,n)=>{if(!/[{']/.test(t))return t;try{return ee(new j(t).parse(),s,n??o)}catch(c){if(c instanceof E)return t;throw c}}}}function k(r){let t={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};return r.replace(/[&<>"'/]/g,s=>t[s])}function re(r){let t=r.trim().toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:")||t.startsWith("vbscript:")||t.startsWith("file:")?"#":k(r)}function W(){return {name:"markdown",escapeValue:k,transform:(r,t,s,o)=>{let n=t,c=[],u=0;n=n.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(d,p,m)=>{let h=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<a href="${re(m)}">${k(p)}</a>`,u++,h}),n=n.replace(/\*\*(.*?)\*\*/g,(d,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<strong>${k(p)}</strong>`,u++,m}),n=n.replace(/\*(.*?)\*/g,(d,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<em>${k(p)}</em>`,u++,m}),n=n.replace(/`(.*?)`/g,(d,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${u}__`;return c[u]=`<code>${k(p)}</code>`,u++,m}),n=k(n);for(let d=0;d<c.length;d++)n=n.replace(`__MARKDOWN_PLACEHOLDER_${d}__`,c[d]);return n}}}var le=W(),fe=z();export{F as createCache,Y as createI18n,M as deepMerge,te as defaultPluralRules,A as getNestedValue,K as getPluralForm,fe as icuPlugin,V as interpolate,le as markdownPlugin};//# sourceMappingURL=index.mjs.map
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts","../src/core.ts","../src/plugins.ts"],"names":["interpolate","template","params","formatters","locale","match","key","paramKey","format","s","value","error","deepMerge","target","source","result","getNestedValue","obj","path","keys","current","createCache","cache","defaultPluralRules","count","getPluralForm","customRules","rules","createI18n","config","currentLocale","fallbackLocale","messages","plugins","listeners","translationCache","options","parts","currency","plugin","getMessage","localeMessages","translate","cacheKey","cached","message","pluralForm","pluralKey","pluralMessage","fallbackPluralMessage","t","args","setLocale","listener","addMessages","newMessages","processedMessages","hasTranslation","checkLocale","addPlugin","removePlugin","pluginName","index","p","subscribe","formatNumber","formatDate","formatRelativeTime","baseDate","diffInSeconds","rtf","units","unit","secondsInUnit","markdownPlugin","_key","_params","_locale","parseICUBalanced","text","startPattern","start","braceCount","i","fullMatch","content","icuPlugin","pluralInfo","zeroMatch","oneMatch","otherMatch","replacement","gender","selectInfo","genderMatch"],"mappings":"AAEO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EACQ,CACR,GAAI,OAAOH,CAAAA,EAAa,QAAA,CACtB,OAAO,MAAA,CAAOA,CAAQ,EAGxB,GAAI,CACF,OAAOA,CAAAA,CAAS,OAAA,CAAQ,kBAAA,CAAoB,CAACI,CAAAA,CAAOC,CAAAA,GAAQ,CAC1D,GAAI,CACF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A,CAAAA,CAAO,OAAA,CAAQwE,CAAAA,CAAW,KAAA,CAAOI,CAAW,EACvD,CACF,CAGA,GAAIf,CAAAA,EAAW,QAAA,GAAYA,EAAS,CAClC,IAAMgB,CAAAA,CAAShB,CAAAA,CAAQ,MAAA,CAGjBiB,CAAAA,CAAaf,EAAiB/D,CAAAA,CAAQ,wBAAwB,EACpE,GAAI8E,CAAAA,CAAY,CACd,IAAMlE,CAAAA,CAAQkE,CAAAA,CAAW,OAAA,CACnBC,CAAAA,CAAcnE,CAAAA,CAAM,MAAM,IAAI,MAAA,CAAO,GAAGiE,CAAM,CAAA,iBAAA,CAAmB,CAAC,CAAA,CAClEF,CAAAA,CAAa/D,EAAM,KAAA,CAAM,qBAAqB,EAEhDgE,CAAAA,CAAcE,CAAAA,CAAW,MACzBC,CAAAA,CACFH,CAAAA,CAAcG,EAAY,CAAC,CAAA,CAClBJ,CAAAA,GACTC,CAAAA,CAAcD,CAAAA,CAAW,CAAC,GAG5B3E,CAAAA,CAASA,CAAAA,CAAO,QAAQ8E,CAAAA,CAAW,KAAA,CAAOF,CAAW,EACvD,CACF,CAGA,OAAIf,CAAAA,EAAW,MAAA,GAAUA,IACvB7D,CAAAA,CAASA,CAAAA,CAAO,QAAQ,WAAA,CAAa,MAAA,CAAO6D,EAAQ,IAAI,CAAC,CAAA,CAAA,CAGpD7D,CACT,CACF","file":"index.mjs","sourcesContent":["import type { TranslationParams, TranslationValue } from './types';\n\nexport function interpolate(\n template: string,\n params: TranslationParams,\n formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>,\n locale?: string\n): string {\n if (typeof template !== 'string') {\n return String(template);\n }\n \n try {\n return template.replace(/\\{\\{([^}]+)\\}\\}/g, (match, key) => {\n try {\n const [paramKey, format] = key.trim().split(':').map((s: string) => s.trim());\n \n if (!(paramKey in params)) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation parameter: ${paramKey}`);\n }\n return match; // Return original placeholder for missing parameters\n }\n \n const value = params[paramKey];\n \n if (format && formatters?.has(format)) {\n try {\n const formatter = formatters.get(format)!;\n return formatter(value, key.includes(':') ? key.split(':').slice(1).join(':') : undefined, locale);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter error for ${format}:`, error);\n }\n return String(value);\n }\n }\n \n if (value === null || value === undefined) {\n return '';\n }\n \n if (value instanceof Date) {\n return value.toLocaleDateString();\n }\n \n return String(value);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Parameter interpolation error:', error);\n }\n return match;\n }\n });\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Template interpolation error:', error);\n }\n return template;\n }\n}\n\nexport function deepMerge<T extends Record<string, any>>(\n target: T,\n source: Partial<T>\n): T {\n if (!target || typeof target !== 'object') {\n throw new Error('[i18n] Invalid target for deepMerge');\n }\n \n if (!source || typeof source !== 'object') {\n return target;\n }\n \n try {\n const result = { ...target };\n \n for (const key in source) {\n if (source[key] !== undefined) {\n if (\n typeof source[key] === 'object' &&\n source[key] !== null &&\n !Array.isArray(source[key]) &&\n !(source[key] as any instanceof Date)\n ) {\n result[key] = deepMerge(\n result[key] || ({} as any),\n source[key] as any\n ) as any;\n } else {\n result[key] = source[key] as any;\n }\n }\n }\n \n return result;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] DeepMerge error:', error);\n }\n return target;\n }\n}\n\nexport function getNestedValue<T>(\n obj: Record<string, any>,\n path: string\n): T | undefined {\n if (!obj || typeof obj !== 'object' || !path || typeof path !== 'string') {\n return undefined;\n }\n \n try {\n const keys = path.split('.');\n let current = obj;\n \n for (const key of keys) {\n if (current && typeof current === 'object' && key in current) {\n current = current[key];\n } else {\n return undefined;\n }\n }\n \n return current as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] getNestedValue error:', error);\n }\n return undefined;\n }\n}\n\nexport function createCache<T>(): {\n get: (key: string) => T | undefined;\n set: (key: string, value: T) => void;\n clear: () => void;\n} {\n const cache = new Map<string, T>();\n \n return {\n get: (key: string) => cache.get(key),\n set: (key: string, value: T) => {\n cache.set(key, value);\n },\n clear: () => cache.clear(),\n };\n}\n\nexport const defaultPluralRules: Record<string, (count: number) => string> = {\n en: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n es: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n fr: (count: number) => {\n if (count === 0 || count === 1) return 'one';\n return 'other';\n },\n de: (count: number) => {\n if (count === 1) return 'one';\n return 'other';\n },\n ja: () => 'other',\n ko: () => 'other',\n zh: () => 'other',\n};\n\nexport function getPluralForm(\n locale: string,\n count: number,\n customRules?: Record<string, (count: number) => string>\n): string {\n const rules = customRules || defaultPluralRules;\n const rule = rules[locale] || rules.en;\n return rule(count);\n}","import type {\n I18nConfig,\n I18nInstance,\n I18nPlugin,\n LocaleCode,\n Messages,\n TranslationFunction,\n TranslationParams,\n TranslationValue,\n} from './types';\nimport {\n createCache,\n deepMerge,\n getNestedValue,\n getPluralForm,\n interpolate,\n} from './utils';\n\nexport function createI18n<TMessages extends Messages = Messages>(\n config: I18nConfig<TMessages>\n): I18nInstance<TMessages> {\n // Validate config\n if (!config) {\n throw new Error('[i18n] Configuration is required');\n }\n if (!config.locale) {\n throw new Error('[i18n] Locale is required');\n }\n if (!config.messages) {\n throw new Error('[i18n] Messages are required');\n }\n\n let currentLocale = config.locale;\n const fallbackLocale = config.fallbackLocale;\n const messages = { ...config.messages };\n const plugins = [...(config.plugins || [])];\n const listeners = new Set<(locale: LocaleCode) => void>();\n const translationCache = createCache<string>();\n \n const formatters = new Map<string, (value: TranslationValue, format?: string, locale?: string) => string>();\n \n // Built-in formatters\n formatters.set('number', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const options = config.formats?.number?.[format || 'default'] || {};\n return new Intl.NumberFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('date', (value, format, locale) => {\n if (!(value instanceof Date)) return String(value);\n const options = config.formats?.date?.[format || 'default'] || {};\n return new Intl.DateTimeFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('currency', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const parts = (format || 'currency:USD').split(':');\n const currency = parts.length > 1 ? parts[1] || 'USD' : 'USD';\n try {\n return new Intl.NumberFormat(locale || currentLocale, {\n style: 'currency',\n currency,\n }).format(value);\n } catch (error) {\n return `${currency} ${value}`;\n }\n });\n \n // Register plugin formatters\n plugins.forEach(plugin => {\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) => \n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n });\n \n function getMessage(key: string, locale: LocaleCode): string | undefined {\n const localeMessages = messages[locale];\n if (!localeMessages) return undefined;\n \n // First try direct key access (for flat keys like 'user.role.admin')\n if (key in localeMessages) {\n return localeMessages[key] as string;\n }\n \n // Then try nested access (for nested objects like user.role.admin)\n return getNestedValue<string>(localeMessages, key);\n }\n \n function translate(\n key: string,\n params?: TranslationParams,\n locale: LocaleCode = currentLocale\n ): string {\n try {\n const cacheKey = `${locale}:${key}:${JSON.stringify(params || {})}`;\n const cached = translationCache.get(cacheKey);\n if (cached) return cached;\n \n let message = getMessage(key, locale);\n \n // Try fallback locale\n if (!message && fallbackLocale && locale !== fallbackLocale) {\n message = getMessage(key, fallbackLocale);\n }\n \n // Handle pluralization before checking if message exists\n if (params && 'count' in params && typeof params.count === 'number') {\n const pluralForm = getPluralForm(locale, params.count, config.pluralizationRules);\n const pluralKey = `${key}.${pluralForm}`;\n const pluralMessage = getMessage(pluralKey, locale);\n \n // Try fallback locale for plural\n if (!pluralMessage && fallbackLocale && locale !== fallbackLocale) {\n const fallbackPluralMessage = getMessage(pluralKey, fallbackLocale);\n if (fallbackPluralMessage) {\n message = fallbackPluralMessage;\n }\n } else if (pluralMessage) {\n message = pluralMessage;\n }\n }\n\n if (!message) {\n if (config.warnOnMissingTranslations && typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation: ${key} for locale: ${locale}`);\n }\n return key;\n }\n \n // Apply plugins\n let result = message;\n for (const plugin of plugins) {\n if (plugin.transform) {\n try {\n result = plugin.transform(key as keyof TMessages, result, params || {}, locale);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Plugin ${plugin.name} transform error:`, error);\n }\n }\n }\n }\n \n // Always interpolate to handle empty parameters \n result = interpolate(result, params || {}, formatters, currentLocale);\n \n translationCache.set(cacheKey, result);\n return result;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Translation error for key ${key}:`, error);\n }\n return key;\n }\n }\n \n const t: TranslationFunction<TMessages> = (key, ...args) => {\n const params = args[0] as TranslationParams | undefined;\n return translate(String(key), params);\n };\n \n function setLocale(locale: LocaleCode): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n \n if (locale !== currentLocale) {\n currentLocale = locale;\n translationCache.clear();\n listeners.forEach(listener => {\n try {\n listener(locale);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Locale change listener error:', error);\n }\n }\n });\n }\n }\n \n function addMessages(locale: LocaleCode, newMessages: Partial<TMessages>): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n \n if (!newMessages || typeof newMessages !== 'object') {\n throw new Error('[i18n] Invalid messages provided');\n }\n \n try {\n if (!messages[locale]) {\n messages[locale] = {} as TMessages;\n }\n \n // Apply beforeLoad plugins\n let processedMessages = newMessages;\n for (const plugin of plugins) {\n if (plugin.beforeLoad) {\n try {\n processedMessages = plugin.beforeLoad(locale, processedMessages as TMessages) as Partial<TMessages>;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Plugin ${plugin.name} beforeLoad error:`, error);\n }\n }\n }\n }\n \n messages[locale] = deepMerge(messages[locale], processedMessages);\n \n // Apply afterLoad plugins\n for (const plugin of plugins) {\n if (plugin.afterLoad) {\n try {\n plugin.afterLoad(locale, messages[locale]);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Plugin ${plugin.name} afterLoad error:`, error);\n }\n }\n }\n }\n \n translationCache.clear();\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Error adding messages:', error);\n }\n throw error;\n }\n }\n \n function hasTranslation(key: keyof TMessages, locale?: LocaleCode): boolean {\n const checkLocale = locale || currentLocale;\n const message = getMessage(String(key), checkLocale);\n return message !== undefined;\n }\n \n function addPlugin(plugin: I18nPlugin<TMessages>): void {\n plugins.push(plugin);\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) => \n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n translationCache.clear();\n }\n \n function removePlugin(pluginName: string): void {\n const index = plugins.findIndex(p => p.name === pluginName);\n if (index !== -1) {\n plugins.splice(index, 1);\n formatters.delete(pluginName);\n translationCache.clear();\n }\n }\n \n function subscribe(listener: (locale: LocaleCode) => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n \n function formatNumber(value: number, format?: string): string {\n const formatter = formatters.get('number')!;\n return formatter(value, format, currentLocale);\n }\n \n function formatDate(value: Date, format?: string): string {\n const formatter = formatters.get('date')!;\n return formatter(value, format, currentLocale);\n }\n \n function formatRelativeTime(value: Date, baseDate: Date = new Date()): string {\n const diffInSeconds = Math.floor((value.getTime() - baseDate.getTime()) / 1000);\n const rtf = new Intl.RelativeTimeFormat(currentLocale, { numeric: 'auto' });\n \n const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [\n ['year', 60 * 60 * 24 * 365],\n ['month', 60 * 60 * 24 * 30],\n ['week', 60 * 60 * 24 * 7],\n ['day', 60 * 60 * 24],\n ['hour', 60 * 60],\n ['minute', 60],\n ['second', 1],\n ];\n \n for (const [unit, secondsInUnit] of units) {\n if (Math.abs(diffInSeconds) >= secondsInUnit) {\n return rtf.format(Math.round(diffInSeconds / secondsInUnit), unit);\n }\n }\n \n return rtf.format(0, 'second');\n }\n \n return {\n get locale() {\n return currentLocale;\n },\n get fallbackLocale() {\n return fallbackLocale;\n },\n get messages() {\n return messages;\n },\n t,\n setLocale,\n getLocale: () => currentLocale,\n hasTranslation,\n addMessages,\n addPlugin,\n removePlugin,\n subscribe,\n formatNumber,\n formatDate,\n formatRelativeTime,\n };\n}","import type { I18nPlugin } from './types';\n\n/**\n * Markdown plugin for basic markdown syntax transformation\n */\nexport const markdownPlugin: I18nPlugin = {\n name: 'markdown',\n transform: (_key, value, _params, _locale) => {\n return value\n .replace(/\\*\\*(.*?)\\*\\*/g, '<strong>$1</strong>')\n .replace(/\\*(.*?)\\*/g, '<em>$1</em>')\n .replace(/`(.*?)`/g, '<code>$1</code>')\n .replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, '<a href=\"$2\">$1</a>');\n },\n};\n\n/**\n * ICU plugin for basic ICU message format support\n */\nfunction parseICUBalanced(text: string, startPattern: RegExp): { match: string; content: string } | null {\n const match = text.match(startPattern);\n if (!match) return null;\n \n const start = match.index! + match[0].length;\n let braceCount = 1;\n let i = start;\n \n while (i < text.length && braceCount > 0) {\n if (text[i] === '{') braceCount++;\n else if (text[i] === '}') braceCount--;\n i++;\n }\n \n if (braceCount === 0) {\n const fullMatch = text.substring(match.index!, i);\n const content = text.substring(start, i - 1);\n return { match: fullMatch, content };\n }\n \n return null;\n}\n\nexport const icuPlugin: I18nPlugin = {\n name: 'icu',\n transform: (_key, value, _params, _locale) => {\n let result = value;\n \n // Handle basic ICU plural patterns\n if (_params && 'count' in _params) {\n const count = _params.count as number;\n \n // Pattern: {count, plural, =0 {no items} =1 {one item} other {# items}}\n const pluralInfo = parseICUBalanced(result, /\\{count,\\s*plural,\\s*/);\n if (pluralInfo) {\n const rules = pluralInfo.content;\n \n // Parse rules - handle =0, =1, one, other\n const zeroMatch = rules.match(/=0\\s*\\{([^}]+)\\}/);\n const oneMatch = rules.match(/=1\\s*\\{([^}]+)\\}/) || rules.match(/one\\s*\\{([^}]+)\\}/);\n const otherMatch = rules.match(/other\\s*\\{([^}]+)\\}/);\n \n let replacement = pluralInfo.match;\n if (count === 0 && zeroMatch) {\n replacement = zeroMatch[1];\n } else if (count === 1 && oneMatch) {\n replacement = oneMatch[1];\n } else if (otherMatch) {\n replacement = otherMatch[1].replace(/#/g, String(count));\n }\n \n result = result.replace(pluralInfo.match, replacement);\n }\n }\n \n // Handle basic ICU select patterns\n if (_params && 'gender' in _params) {\n const gender = _params.gender as string;\n \n // Pattern: {gender, select, male {He} female {She} other {They}}\n const selectInfo = parseICUBalanced(result, /\\{gender,\\s*select,\\s*/);\n if (selectInfo) {\n const rules = selectInfo.content;\n const genderMatch = rules.match(new RegExp(`${gender}\\\\s*\\\\{([^}]+)\\\\}`));\n const otherMatch = rules.match(/other\\s*\\{([^}]+)\\}/);\n \n let replacement = selectInfo.match;\n if (genderMatch) {\n replacement = genderMatch[1];\n } else if (otherMatch) {\n replacement = otherMatch[1];\n }\n \n result = result.replace(selectInfo.match, replacement);\n }\n }\n \n // Handle simple parameter replacement\n if (_params && 'name' in _params) {\n result = result.replace(/\\{name\\}/g, String(_params.name));\n }\n \n return result;\n },\n};"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils.ts","../src/core.ts","../src/plugins/icu.ts","../src/plugins/markdown.ts","../src/plugins.ts"],"names":["interpolate","template","params","formatters","locale","escape","match","key","replacement","replacePlaceholder","error","paramKey","format","s","value","formatter","formatted","deepMerge","target","source","result","existing","getNestedValue","obj","path","keys","current","createCache","options","cache","maxSize","firstKey","defaultPluralRules","count","pluralRulesCache","pluralRulesFor","rules","tag","getPluralForm","customRules","language","rule","createI18n","config","hasMessages","availableLocales","currentLocale","fallbackLocale","messages","plugins","listeners","translationCache","revision","notify","listener","handleError","context","err","parts","currency","plugin","getMessage","localeMessages","resolveMessage","locales","candidate","forms","form","pluralMessage","message","translate","paramKeys","sortedKeys","sortedParams","k","cacheKey","cached","resolved","messageLocale","transformed","escapers","escaped","t","setLocale","addMessages","newMessages","processedMessages","hasTranslation","checkLocale","addPlugin","existingIndex","p","removePlugin","pluginName","index","subscribe","formatNumber","formatDate","formatRelativeTime","baseDate","diffInSeconds","rtf","units","unit","secondsInUnit","InvalidPattern","MessageParser","pattern","token","number","literal","depth","pound","flush","legacy","start","name","kind","offset","choices","selector","option","intlLocale","numberOptions","cardinal","ordinal","numbers","render","part","selection","adjusted","exact","createICUPlugin","_key","escapeHtml","text","htmlEscapeMap","char","sanitizeHref","href","trimmed","createMarkdownPlugin","_params","_locale","placeholders","placeholderIndex","_","placeholder","i","markdownPlugin","icuPlugin"],"mappings":"AAMO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EACAC,CAAAA,CACQ,CACR,GAAI,OAAOJ,CAAAA,EAAa,SACtB,OAAO,MAAA,CAAOA,CAAQ,CAAA,CAGxB,GAAI,CACF,OAAOA,CAAAA,CAAS,QAAQ,kBAAA,CAAoB,CAACK,EAAOC,CAAAA,GAAQ,CAC1D,IAAMC,CAAAA,CAAcC,CAAAA,CAAmBF,CAAG,CAAA,CAC1C,OAAIC,IAAgB,KAAA,CAAA,CAAkBF,CAAAA,CAC/BD,EAASA,CAAAA,CAAOG,CAAW,EAAIA,CACxC,CAAC,CACH,CAAA,MAASE,CAAAA,CAAO,CACd,OAAI,OAAO,QAAY,GAAA,EAAe,OAAA,CAAQ,KAAK,QAAA,GAAa,YAAA,EAC9D,QAAQ,KAAA,CAAM,sCAAA,CAAwCA,CAAK,CAAA,CAEtDT,CACT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ASX,CAAAA,CAAWC,CAAI,CAAC,CAAA,OAAA,CAAA,CAC1DU,IACOE,CACT,CAAC,EAGD/H,CAAAA,CAASkH,CAAAA,CAAWlH,CAAM,CAAA,CAG1B,IAAA,IAASgI,EAAI,CAAA,CAAGA,CAAAA,CAAIJ,EAAa,MAAA,CAAQI,CAAAA,EAAAA,CACvChI,EAASA,CAAAA,CAAO,OAAA,CAAQ,0BAA0BgI,CAAC,CAAA,EAAA,CAAA,CAAMJ,EAAaI,CAAC,CAAC,EAG1E,OAAOhI,CACT,CACF,CACF,KCxFaiI,EAAAA,CAA6BR,CAAAA,EAAqB,CAKlDS,EAAAA,CAAwBlB,CAAAA","file":"index.mjs","sourcesContent":["import type { TranslationParams, TranslationValue } from './types';\n\n/**\n * Replaces `{{name}}` / `{{name:format}}` placeholders with `params`. When `escape` is given\n * (e.g. by a plugin that produces HTML), every inserted value is passed through it.\n */\nexport function interpolate(\n template: string,\n params: TranslationParams,\n formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>,\n locale?: string,\n escape?: (value: string) => string\n): string {\n if (typeof template !== 'string') {\n return String(template);\n }\n \n try {\n return template.replace(/\\{\\{([^}]+)\\}\\}/g, (match, key) => {\n const replacement = replacePlaceholder(key);\n if (replacement === undefined) return match;\n return escape ? escape(replacement) : replacement;\n });\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Template interpolation error:', error);\n }\n return template;\n }\n\n function replacePlaceholder(key: string): string | undefined {\n try {\n const [paramKey, format] = key.trim().split(':').map((s: string) => s.trim());\n \n if (!Object.prototype.hasOwnProperty.call(params, paramKey)) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation parameter: ${paramKey}`);\n }\n return undefined; // Keep the original placeholder for missing parameters\n }\n \n const value = params[paramKey];\n \n if (format && formatters?.has(format)) {\n try {\n const formatter = formatters.get(format);\n if (!formatter) {\n return String(value);\n }\n const formatted = formatter(value, key.includes(':') ? key.split(':').slice(1).join(':') : undefined, locale);\n // Validate formatter returns a string\n if (typeof formatted !== 'string') {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter '${format}' must return a string, got ${typeof formatted}`);\n }\n return String(value);\n }\n return formatted;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] Formatter error for ${format}:`, error);\n }\n return String(value);\n }\n }\n \n if (value === null || value === undefined) {\n return '';\n }\n \n if (value instanceof Date) {\n // Use the provided locale parameter for locale-aware formatting\n return value.toLocaleDateString(locale || 'en-US', {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit'\n });\n }\n \n return String(value);\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] Parameter interpolation error:', error);\n }\n return undefined;\n }\n }\n}\n\nexport function deepMerge<T extends object>(\n target: T,\n source: Partial<T>\n): T {\n if (!target || typeof target !== 'object') {\n throw new Error('[i18n] Invalid target for deepMerge');\n }\n\n if (!source || typeof source !== 'object') {\n return target;\n }\n\n try {\n const result: Record<string, unknown> = { ...(target as Record<string, unknown>) };\n\n for (const key in source) {\n // SECURITY: Protect against prototype pollution\n // Block dangerous keys that could modify Object.prototype\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n key === 'prototype'\n ) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Blocked attempt to set dangerous property: ${key}`);\n }\n continue;\n }\n\n // Only process own properties (not inherited ones)\n if (!Object.prototype.hasOwnProperty.call(source, key)) {\n continue;\n }\n\n const value: unknown = source[key];\n if (value !== undefined) {\n if (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n ) {\n const existing = result[key];\n result[key] = deepMerge(\n existing && typeof existing === 'object' ? (existing as object) : {},\n value as Partial<object>\n );\n } else {\n result[key] = value;\n }\n }\n }\n\n return result as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] DeepMerge error:', error);\n }\n return target;\n }\n}\n\nexport function getNestedValue<T>(\n obj: Record<string, unknown>,\n path: string\n): T | undefined {\n if (!obj || typeof obj !== 'object' || !path || typeof path !== 'string') {\n return undefined;\n }\n \n try {\n const keys = path.split('.');\n let current: unknown = obj;\n \n for (const key of keys) {\n if (current && typeof current === 'object' && Object.prototype.hasOwnProperty.call(current, key)) {\n current = (current as Record<string, unknown>)[key];\n } else {\n return undefined;\n }\n }\n \n return current as T;\n } catch (error) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error('[i18n] getNestedValue error:', error);\n }\n return undefined;\n }\n}\n\nexport interface CacheOptions {\n maxSize?: number;\n}\n\nexport function createCache<T>(options?: CacheOptions): {\n get: (key: string) => T | undefined;\n set: (key: string, value: T) => void;\n clear: () => void;\n size: () => number;\n} {\n const cache = new Map<string, T>();\n const maxSize = options?.maxSize ?? 1000; // Default to 1000 entries\n\n return {\n get: (key: string) => {\n const value = cache.get(key);\n if (value !== undefined) {\n // LRU: Move to end by deleting and re-adding\n cache.delete(key);\n cache.set(key, value);\n }\n return value;\n },\n set: (key: string, value: T) => {\n // If key exists, delete it first (will re-add at end)\n if (cache.has(key)) {\n cache.delete(key);\n } else if (cache.size >= maxSize) {\n // Remove oldest entry (first entry in Map)\n const firstKey = cache.keys().next().value;\n if (firstKey !== undefined) {\n cache.delete(firstKey);\n }\n }\n cache.set(key, value);\n },\n clear: () => cache.clear(),\n size: () => cache.size,\n };\n}\n\n/**\n * @deprecated Kept for backwards compatibility. Plural categories are now resolved with\n * `Intl.PluralRules` (CLDR), which covers every locale; these hand-written rules are no\n * longer used by `getPluralForm` or `createI18n`.\n */\nexport const defaultPluralRules: Record<string, (count: number) => string> = {\n en: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n es: (count: number) => {\n if (count === 0) return 'zero';\n if (count === 1) return 'one';\n return 'other';\n },\n fr: (count: number) => {\n if (count === 0 || count === 1) return 'one';\n return 'other';\n },\n de: (count: number) => {\n if (count === 1) return 'one';\n return 'other';\n },\n ja: () => 'other',\n ko: () => 'other',\n zh: () => 'other',\n};\n\nconst pluralRulesCache = new Map<string, Intl.PluralRules>();\n\nfunction pluralRulesFor(locale: string): Intl.PluralRules {\n let rules = pluralRulesCache.get(locale);\n if (!rules) {\n try {\n const tag = locale.replace(/_/g, '-');\n // Unsupported locales use English rules instead of the runtime's default locale,\n // so results do not depend on the machine the code runs on.\n rules = new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(tag).length > 0 ? tag : 'en');\n } catch {\n rules = new Intl.PluralRules('en');\n }\n pluralRulesCache.set(locale, rules);\n }\n return rules;\n}\n\n/**\n * Returns the CLDR plural category (`zero`, `one`, `two`, `few`, `many` or `other`)\n * for `count` in `locale`.\n *\n * Custom rules are looked up by the exact locale first and then by its language\n * subtag (`pt-BR` → `pt`); otherwise `Intl.PluralRules` decides.\n */\nexport function getPluralForm(\n locale: string,\n count: number,\n customRules?: Record<string, (count: number) => string>\n): string {\n if (customRules) {\n const language = locale.split(/[-_]/)[0];\n const rule = Object.prototype.hasOwnProperty.call(customRules, locale)\n ? customRules[locale]\n : Object.prototype.hasOwnProperty.call(customRules, language)\n ? customRules[language]\n : undefined;\n if (typeof rule === 'function') return rule(count);\n }\n return pluralRulesFor(locale).select(count);\n}\n","import type {\n DeepPartial,\n I18nConfig,\n I18nInstance,\n I18nPlugin,\n LocaleCode,\n Messages,\n TranslationFunction,\n TranslationKey,\n TranslationParams,\n TranslationValue,\n} from './types';\nimport {\n createCache,\n deepMerge,\n getNestedValue,\n getPluralForm,\n interpolate,\n} from './utils';\n\nexport function createI18n<TMessages extends object = Messages>(\n config: I18nConfig<TMessages>\n): I18nInstance<TMessages> {\n // Validate config\n if (!config) {\n throw new Error('[i18n] Configuration is required');\n }\n if (!config.locale || typeof config.locale !== 'string' || config.locale.trim() === '') {\n throw new Error('[i18n] Locale must be a non-empty string');\n }\n if (!config.messages) {\n throw new Error('[i18n] Messages are required');\n }\n if (typeof config.messages !== 'object' || Array.isArray(config.messages) || config.messages === null) {\n throw new Error('[i18n] Messages must be an object');\n }\n // Warn if messages is empty but allow it for graceful degradation\n const hasMessages = Object.keys(config.messages).length > 0;\n if (!hasMessages) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn('[i18n] Messages object is empty - all translations will return keys');\n }\n }\n // Validate that the current locale exists in messages, unless a fallback is provided or messages is empty\n if (hasMessages && !(config.locale in config.messages) && !config.fallbackLocale) {\n const availableLocales = Object.keys(config.messages).join(', ');\n throw new Error(`[i18n] Locale '${config.locale}' not found in messages and no fallback locale provided. Available locales: ${availableLocales}`);\n }\n // Warn if current locale doesn't exist but fallback does\n if (!(config.locale in config.messages) && config.fallbackLocale) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n const availableLocales = Object.keys(config.messages).join(', ');\n console.warn(`[i18n] Locale '${config.locale}' not found in messages, will use fallback locale '${config.fallbackLocale}'. Available locales: ${availableLocales}`);\n }\n }\n // Validate fallback locale if provided\n if (config.fallbackLocale && !(config.fallbackLocale in config.messages)) {\n const availableLocales = Object.keys(config.messages).join(', ');\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Fallback locale '${config.fallbackLocale}' not found in messages. Available locales: ${availableLocales}`);\n }\n }\n\n let currentLocale = config.locale;\n const fallbackLocale = config.fallbackLocale;\n // Deep copy messages to prevent mutations to the original config\n const messages = structuredClone(config.messages);\n const plugins = [...(config.plugins || [])];\n const listeners = new Set<(locale: LocaleCode) => void>();\n const translationCache = createCache<string>();\n let revision = 0;\n\n const notify = (): void => {\n revision++;\n listeners.forEach(listener => {\n try {\n listener(currentLocale);\n } catch (error) {\n handleError(error, 'Locale change listener');\n }\n });\n };\n\n // Helper function for consistent error handling\n const handleError = (error: unknown, context: string): void => {\n const err = error instanceof Error ? error : new Error(String(error));\n // Call user-provided error handler in production\n if (config.onError) {\n try {\n config.onError(err, context);\n } catch {\n // Silently fail if error handler itself errors\n }\n }\n // Log in development\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(`[i18n] ${context}:`, err);\n }\n };\n\n const formatters = new Map<string, (value: TranslationValue, format?: string, locale?: string) => string>();\n \n // Built-in formatters\n formatters.set('number', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const options = config.formats?.number?.[format || 'default'] || {};\n return new Intl.NumberFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('date', (value, format, locale) => {\n if (!(value instanceof Date)) return String(value);\n const options = config.formats?.date?.[format || 'default'] || {};\n return new Intl.DateTimeFormat(locale || currentLocale, options).format(value);\n });\n \n formatters.set('currency', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const parts = (format || 'currency:USD').split(':');\n const currency = parts.length > 1 ? parts[1] || 'USD' : 'USD';\n try {\n return new Intl.NumberFormat(locale || currentLocale, {\n style: 'currency',\n currency,\n }).format(value);\n } catch (error) {\n handleError(error, `Currency formatter error for currency '${currency}'`);\n return `${currency} ${value}`;\n }\n });\n \n // Register plugin formatters\n plugins.forEach(plugin => {\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) => \n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n });\n \n function getMessage(key: string, locale: LocaleCode): string | undefined {\n if (!Object.prototype.hasOwnProperty.call(messages, locale)) return undefined;\n const localeMessages = messages[locale] as Record<string, unknown> | undefined;\n if (!localeMessages || typeof localeMessages !== 'object') return undefined;\n\n // First try direct key access (for flat keys like 'user.role.admin'),\n // then nested access (for nested objects like { user: { role: { admin } } }).\n // Only own string values count: nested groups and Object.prototype members\n // ('constructor', 'toString', ...) are not translations.\n const value = Object.prototype.hasOwnProperty.call(localeMessages, key)\n ? localeMessages[key]\n : getNestedValue<unknown>(localeMessages, key);\n return typeof value === 'string' ? value : undefined;\n }\n\n function resolveMessage(\n key: string,\n params: TranslationParams | undefined,\n locale: LocaleCode\n ): { message: string; messageLocale: LocaleCode } | undefined {\n const locales = fallbackLocale && fallbackLocale !== locale ? [locale, fallbackLocale] : [locale];\n const count = params && Object.prototype.hasOwnProperty.call(params, 'count') ? params.count : undefined;\n\n for (const candidate of locales) {\n if (typeof count === 'number') {\n // Explicit zero form first (a common convention), then the CLDR category of the\n // catalog's own language, then the mandatory \"other\" form.\n const forms = new Set<string>();\n if (count === 0) forms.add('zero');\n forms.add(getPluralForm(candidate, count, config.pluralizationRules));\n forms.add('other');\n for (const form of forms) {\n const pluralMessage = getMessage(`${key}.${form}`, candidate);\n if (pluralMessage) return { message: pluralMessage, messageLocale: candidate };\n }\n }\n const message = getMessage(key, candidate);\n if (message) return { message, messageLocale: candidate };\n }\n return undefined;\n }\n\n function translate(\n key: string,\n params?: TranslationParams,\n locale: LocaleCode = currentLocale\n ): string {\n try {\n // Generate cache key with deterministic param serialization\n // Sort keys to ensure consistent caching regardless of property order\n let paramKey = '';\n if (params) {\n const paramKeys = Object.keys(params);\n if (paramKeys.length > 0) {\n try {\n // Fast path for single parameter\n if (paramKeys.length === 1) {\n const key = paramKeys[0];\n paramKey = `${key}:${JSON.stringify(params[key])}`;\n } else {\n // Sort only when multiple parameters exist\n const sortedKeys = paramKeys.sort();\n const sortedParams: Record<string, unknown> = {};\n for (const k of sortedKeys) {\n sortedParams[k] = params[k];\n }\n paramKey = JSON.stringify(sortedParams);\n }\n } catch (stringifyError) {\n // Handle circular references or other JSON.stringify errors\n // Use a simpler key based on param keys only\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn('[i18n] Failed to serialize params for caching, using fallback key');\n }\n paramKey = paramKeys.sort().join(',');\n }\n }\n }\n\n const cacheKey = `${locale}:${key}:${paramKey}`;\n const cached = translationCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const resolved = resolveMessage(key, params, locale);\n if (!resolved) {\n if (config.warnOnMissingTranslations && typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Missing translation: ${key} for locale: ${locale}`);\n }\n return key;\n }\n const { message, messageLocale } = resolved;\n\n // Apply plugins\n let result = message;\n for (const plugin of plugins) {\n if (plugin.transform) {\n try {\n const transformed = plugin.transform(key, result, params || {}, locale, messageLocale);\n // Validate plugin returns a string\n if (typeof transformed !== 'string') {\n handleError(\n new Error(`Plugin transform must return a string, got ${typeof transformed}`),\n `Plugin ${plugin.name} transform validation`\n );\n // Skip invalid transformation\n continue;\n }\n result = transformed;\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} transform`);\n }\n }\n }\n \n // Always interpolate to handle empty parameters. Plugins that emit HTML escape the\n // inserted values (otherwise a parameter could inject markup into that HTML).\n const escapers = plugins.filter(plugin => typeof plugin.escapeValue === 'function');\n result = interpolate(\n result,\n params || {},\n formatters,\n currentLocale,\n escapers.length > 0\n ? value => escapers.reduce((escaped, plugin) => plugin.escapeValue!(escaped), value)\n : undefined\n );\n \n translationCache.set(cacheKey, result);\n return result;\n } catch (error) {\n handleError(error, `Translation error for key ${key}`);\n return key;\n }\n }\n \n const t = ((key: string, params?: TranslationParams) =>\n translate(String(key), params)) as TranslationFunction<TMessages>;\n \n function setLocale(locale: LocaleCode): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n\n // Warn if locale doesn't exist in messages\n if (!messages[locale]) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(\n `[i18n] Locale '${locale}' not found in messages. Available locales: ${Object.keys(messages).join(', ')}`\n );\n }\n }\n\n if (locale !== currentLocale) {\n currentLocale = locale;\n translationCache.clear();\n notify();\n }\n }\n \n function addMessages(locale: LocaleCode, newMessages: DeepPartial<TMessages>): void {\n if (!locale || typeof locale !== 'string') {\n throw new Error('[i18n] Invalid locale provided');\n }\n \n if (!newMessages || typeof newMessages !== 'object') {\n throw new Error('[i18n] Invalid messages provided');\n }\n \n try {\n if (!messages[locale]) {\n messages[locale] = {} as TMessages;\n }\n \n // Apply beforeLoad plugins\n let processedMessages = newMessages;\n for (const plugin of plugins) {\n if (plugin.beforeLoad) {\n try {\n const result = plugin.beforeLoad(locale, processedMessages as TMessages);\n // Validate plugin returns an object\n if (!result || typeof result !== 'object' || Array.isArray(result)) {\n handleError(\n new Error(`Plugin beforeLoad must return an object, got ${typeof result}`),\n `Plugin ${plugin.name} beforeLoad validation`\n );\n // Skip invalid transformation\n continue;\n }\n processedMessages = result as DeepPartial<TMessages>;\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} beforeLoad`);\n }\n }\n }\n \n messages[locale] = deepMerge(\n messages[locale] as Record<string, unknown>,\n processedMessages as Record<string, unknown>\n ) as TMessages;\n \n // Apply afterLoad plugins\n for (const plugin of plugins) {\n if (plugin.afterLoad) {\n try {\n plugin.afterLoad(locale, messages[locale]);\n } catch (error) {\n handleError(error, `Plugin ${plugin.name} afterLoad`);\n }\n }\n }\n \n translationCache.clear();\n // Lazily loaded catalogs must re-render subscribers (e.g. React) that show the\n // active locale; other locales do not change any visible text.\n if (locale === currentLocale || locale === fallbackLocale) {\n notify();\n }\n } catch (error) {\n handleError(error, 'Error adding messages');\n throw error;\n }\n }\n \n function hasTranslation(key: TranslationKey<TMessages>, locale?: LocaleCode): boolean {\n const checkLocale = locale || currentLocale;\n const message = getMessage(String(key), checkLocale);\n return message !== undefined;\n }\n \n function addPlugin(plugin: I18nPlugin<TMessages>): void {\n // Check for duplicate plugin names\n const existingIndex = plugins.findIndex(p => p.name === plugin.name);\n if (existingIndex !== -1) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(`[i18n] Plugin '${plugin.name}' already registered. Replacing existing plugin.`);\n }\n // Remove existing plugin first\n plugins.splice(existingIndex, 1);\n }\n\n plugins.push(plugin);\n if (plugin.format) {\n formatters.set(plugin.name, (value, format, locale) =>\n plugin.format!(value, format ?? '', locale ?? currentLocale)\n );\n }\n translationCache.clear();\n }\n \n function removePlugin(pluginName: string): void {\n const index = plugins.findIndex(p => p.name === pluginName);\n if (index !== -1) {\n plugins.splice(index, 1);\n formatters.delete(pluginName);\n translationCache.clear();\n }\n }\n \n function subscribe(listener: (locale: LocaleCode) => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n \n function formatNumber(value: number, format?: string): string {\n const formatter = formatters.get('number');\n if (!formatter) {\n throw new Error('[i18n] Number formatter not available. Please add a plugin that provides number formatting.');\n }\n return formatter(value, format, currentLocale);\n }\n\n function formatDate(value: Date, format?: string): string {\n const formatter = formatters.get('date');\n if (!formatter) {\n throw new Error('[i18n] Date formatter not available. Please add a plugin that provides date formatting.');\n }\n return formatter(value, format, currentLocale);\n }\n \n function formatRelativeTime(value: Date, baseDate: Date = new Date()): string {\n // Validate that value is a valid Date\n if (!(value instanceof Date) || isNaN(value.getTime())) {\n throw new Error('[i18n] Invalid date provided to formatRelativeTime');\n }\n // Validate that baseDate is a valid Date\n if (!(baseDate instanceof Date) || isNaN(baseDate.getTime())) {\n throw new Error('[i18n] Invalid base date provided to formatRelativeTime');\n }\n\n const diffInSeconds = Math.floor((value.getTime() - baseDate.getTime()) / 1000);\n const rtf = new Intl.RelativeTimeFormat(currentLocale, { numeric: 'auto' });\n \n const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [\n ['year', 60 * 60 * 24 * 365],\n ['month', 60 * 60 * 24 * 30],\n ['week', 60 * 60 * 24 * 7],\n ['day', 60 * 60 * 24],\n ['hour', 60 * 60],\n ['minute', 60],\n ['second', 1],\n ];\n \n for (const [unit, secondsInUnit] of units) {\n if (Math.abs(diffInSeconds) >= secondsInUnit) {\n return rtf.format(Math.round(diffInSeconds / secondsInUnit), unit);\n }\n }\n \n return rtf.format(0, 'second');\n }\n \n return {\n get locale() {\n return currentLocale;\n },\n get fallbackLocale() {\n return fallbackLocale;\n },\n get messages() {\n return messages;\n },\n get revision() {\n return revision;\n },\n t,\n setLocale,\n getLocale: () => currentLocale,\n hasTranslation,\n addMessages,\n addPlugin,\n removePlugin,\n subscribe,\n formatNumber,\n formatDate,\n formatRelativeTime,\n };\n}\n","import type { I18nPlugin, TranslationParams } from '../types';\n\ntype ChoiceKind = 'plural' | 'select' | 'selectordinal';\ntype Part = string\n | { kind: 'value'; name: string; source: string }\n | { kind: 'number' }\n | { kind: ChoiceKind; name: string; source: string; choices: Map<string, Part[]>; offset: number };\n\nclass InvalidPattern extends Error {}\n\nclass MessageParser {\n private cursor = 0;\n\n constructor(private readonly source: string) {}\n\n parse(): Part[] {\n return this.message(0, false).parts;\n }\n\n private take(pattern: RegExp): string | undefined {\n pattern.lastIndex = this.cursor;\n const token = pattern.exec(this.source)?.[0];\n if (token !== undefined) this.cursor += token.length;\n return token;\n }\n\n private expect(pattern: RegExp): string {\n const token = this.take(pattern);\n if (token === undefined) throw new InvalidPattern();\n return token;\n }\n\n private space(): void {\n this.take(/\\s+/y);\n }\n\n private number(): number {\n const number = Number(this.expect(/[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?/y));\n if (!Number.isFinite(number)) throw new InvalidPattern();\n return number;\n }\n\n private quote(): string {\n let literal = '';\n this.cursor++;\n while (this.cursor < this.source.length) {\n const current = this.source.charAt(this.cursor++);\n if (current === \"'\" && !this.take(/'/y)) break;\n literal += current;\n }\n return literal;\n }\n\n private message(depth: number, pound: boolean): { parts: Part[]; closed: boolean } {\n if (depth > 64) throw new InvalidPattern();\n const parts: Part[] = [];\n let literal = '';\n function flush() {\n if (literal) parts.push(literal);\n literal = '';\n }\n while (this.cursor < this.source.length) {\n const current = this.source.charAt(this.cursor);\n if (current === '}') {\n if (depth === 0) throw new InvalidPattern();\n this.cursor++;\n flush();\n return { parts, closed: true };\n }\n if (current === '{') {\n const legacy = this.take(/\\{\\{[^{}]*\\}\\}/y);\n if (legacy !== undefined) literal += legacy;\n else {\n flush();\n parts.push(this.argument(depth));\n }\n } else if (current === \"'\" && this.take(/''/y)) {\n literal += \"'\";\n } else if (current === \"'\" && (\n ['{', '}'].includes(this.source.charAt(this.cursor + 1)) ||\n (pound && this.source.charAt(this.cursor + 1) === '#')\n )) {\n literal += this.quote();\n } else {\n this.cursor++;\n if (current === '#' && pound) {\n flush();\n parts.push({ kind: 'number' });\n } else literal += current;\n }\n }\n flush();\n return { parts, closed: false };\n }\n\n private argument(depth: number): Part {\n const start = this.cursor++;\n this.space();\n const name = this.expect(/[\\p{ID_Continue}]+/uy);\n this.space();\n if (this.take(/\\}/y)) return { kind: 'value', name, source: this.source.slice(start, this.cursor) };\n this.expect(/,/y);\n this.space();\n const kind = this.expect(/selectordinal|plural|select/y) as ChoiceKind; // The scanner accepts only these three literals.\n this.space();\n this.expect(/,/y);\n this.space();\n const offset = kind !== 'select' && this.take(/offset\\s*:\\s*/y) ? this.number() : 0;\n this.space();\n const choices = new Map<string, Part[]>();\n while (!this.take(/\\}/y)) {\n const selector = kind !== 'select' && this.take(/=/y)\n ? '=' + this.number()\n : this.expect(/[\\p{ID_Continue}]+/uy);\n this.space();\n this.expect(/\\{/y);\n const option = this.message(depth + 1, kind !== 'select');\n if (!option.closed) throw new InvalidPattern();\n if (!choices.has(selector)) choices.set(selector, option.parts);\n this.space();\n }\n if (!choices.has('other')) throw new InvalidPattern();\n return { kind, name, choices, offset, source: this.source.slice(start, this.cursor) };\n }\n}\n\nfunction language(locale: string): string {\n try {\n return Intl.getCanonicalLocales(locale.replace(/_/g, '-'))[0] ?? 'en';\n } catch {\n return 'en';\n }\n}\n\nfunction format(parts: Part[], params: TranslationParams, locale: string): string {\n const intlLocale = language(locale);\n const numberOptions = { maximumSignificantDigits: 21 };\n let cardinal: Intl.PluralRules | undefined;\n let ordinal: Intl.PluralRules | undefined;\n let numbers: Intl.NumberFormat | undefined;\n\n function render(message: Part[], pound?: number): string {\n return message.map(part => {\n if (typeof part === 'string') return part;\n if (part.kind === 'number') {\n return pound === undefined ? '#' : (numbers ??= new Intl.NumberFormat(intlLocale, numberOptions)).format(pound);\n }\n if (!Object.hasOwn(params, part.name)) return part.source;\n const value = params[part.name];\n if (part.kind === 'value') return String(value);\n if (part.kind === 'select') {\n const selection = part.choices.get(String(value)) ?? part.choices.get('other');\n return selection ? render(selection) : part.source;\n }\n if (typeof value !== 'number' || !Number.isFinite(value)) return part.source;\n const adjusted = value - part.offset;\n if (!Number.isFinite(adjusted)) return part.source;\n const exact = part.choices.get('=' + value);\n if (exact) return render(exact, adjusted);\n const rules = part.kind === 'plural'\n ? (cardinal ??= new Intl.PluralRules(intlLocale, numberOptions))\n : (ordinal ??= new Intl.PluralRules(intlLocale, { ...numberOptions, type: 'ordinal' }));\n const selection = part.choices.get(rules.select(adjusted)) ?? part.choices.get('other');\n return selection ? render(selection, adjusted) : part.source;\n }).join('');\n }\n\n return render(parts);\n}\n\nexport function createICUPlugin(): I18nPlugin {\n return {\n name: 'icu',\n transform: (_key, value, params, locale, messageLocale) => {\n if (!/[{']/.test(value)) return value;\n try {\n return format(new MessageParser(value).parse(), params, messageLocale ?? locale);\n } catch (error) {\n if (error instanceof InvalidPattern) return value;\n throw error;\n }\n },\n };\n}\n","import type { I18nPlugin } from '../types';\n\n/**\n * Escapes HTML special characters to prevent XSS attacks\n */\nfunction escapeHtml(text: string): string {\n const htmlEscapeMap: Record<string, string> = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '/': '/',\n };\n return text.replace(/[&<>\"'/]/g, (char) => htmlEscapeMap[char]);\n}\n\n/**\n * Sanitizes href attribute to prevent javascript: and data: URIs\n */\nfunction sanitizeHref(href: string): string {\n const trimmed = href.trim().toLowerCase();\n // Block javascript:, data:, vbscript:, and other dangerous protocols\n if (\n trimmed.startsWith('javascript:') ||\n trimmed.startsWith('data:') ||\n trimmed.startsWith('vbscript:') ||\n trimmed.startsWith('file:')\n ) {\n return '#';\n }\n return escapeHtml(href);\n}\n\n/**\n * Converts `**bold**`, `*italic*`, `` `code` `` and `[text](url)` to HTML and escapes the\n * rest of the message. Interpolated `{{values}}` are HTML-escaped too. Register it after\n * `icuPlugin` so ICU arguments are escaped as part of the message.\n */\nexport function createMarkdownPlugin(): I18nPlugin {\n return {\n name: 'markdown',\n escapeValue: escapeHtml,\n transform: (_key, value, _params, _locale) => {\n // Simple markdown transformations with XSS protection\n // We need to be careful not to double-escape\n let result = value;\n\n // Store placeholders for processed markdown to avoid conflicts\n const placeholders: string[] = [];\n let placeholderIndex = 0;\n\n // [text](url) -> <a href=\"url\">text</a>\n result = result.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, (_, text, href) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<a href=\"${sanitizeHref(href)}\">${escapeHtml(text)}</a>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // **bold** -> <strong>text</strong>\n result = result.replace(/\\*\\*(.*?)\\*\\*/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<strong>${escapeHtml(text)}</strong>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // *italic* -> <em>text</em>\n result = result.replace(/\\*(.*?)\\*/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<em>${escapeHtml(text)}</em>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // `code` -> <code>text</code>\n result = result.replace(/`(.*?)`/g, (_, text) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n placeholders[placeholderIndex] = `<code>${escapeHtml(text)}</code>`;\n placeholderIndex++;\n return placeholder;\n });\n\n // Escape any remaining text that wasn't part of markdown\n result = escapeHtml(result);\n\n // Restore placeholders\n for (let i = 0; i < placeholders.length; i++) {\n result = result.replace(`__MARKDOWN_PLACEHOLDER_${i}__`, placeholders[i]);\n }\n\n return result;\n },\n };\n}","import { createICUPlugin } from './plugins/icu';\nimport { createMarkdownPlugin } from './plugins/markdown';\nimport type { I18nPlugin } from './types';\n\n/**\n * Markdown plugin for basic markdown syntax transformation.\n */\nexport const markdownPlugin: I18nPlugin = createMarkdownPlugin();\n\n/**\n * ICU MessageFormat plugin for named arguments, plural forms and select branches.\n */\nexport const icuPlugin: I18nPlugin = createICUPlugin();\n"]}
|
package/package.json
CHANGED
|
@@ -1,22 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oxog/i18n",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Modern, lightweight, and framework-agnostic internationalization library",
|
|
5
5
|
"author": "Ersin Koç",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
8
8
|
"type": "git",
|
|
9
|
-
"url": "https://github.com/ersinkoc/i18n",
|
|
9
|
+
"url": "git+https://github.com/ersinkoc/i18n.git",
|
|
10
10
|
"directory": "packages/core"
|
|
11
11
|
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/ersinkoc/i18n/issues"
|
|
14
|
+
},
|
|
15
|
+
"homepage": "https://github.com/ersinkoc/i18n/tree/main/packages/core#readme",
|
|
12
16
|
"main": "./dist/index.js",
|
|
13
17
|
"module": "./dist/index.mjs",
|
|
14
18
|
"types": "./dist/index.d.ts",
|
|
15
19
|
"exports": {
|
|
16
20
|
".": {
|
|
17
|
-
"
|
|
18
|
-
|
|
19
|
-
|
|
21
|
+
"import": {
|
|
22
|
+
"types": "./dist/index.d.mts",
|
|
23
|
+
"default": "./dist/index.mjs"
|
|
24
|
+
},
|
|
25
|
+
"require": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"default": "./dist/index.js"
|
|
28
|
+
}
|
|
20
29
|
},
|
|
21
30
|
"./package.json": "./package.json"
|
|
22
31
|
},
|
|
@@ -24,10 +33,10 @@
|
|
|
24
33
|
"dist"
|
|
25
34
|
],
|
|
26
35
|
"devDependencies": {
|
|
27
|
-
"@vitest/coverage-v8": "^
|
|
36
|
+
"@vitest/coverage-v8": "^4.0.8",
|
|
28
37
|
"tsup": "^8.0.1",
|
|
29
38
|
"typescript": "^5.3.3",
|
|
30
|
-
"vitest": "^
|
|
39
|
+
"vitest": "^4.0.8"
|
|
31
40
|
},
|
|
32
41
|
"sideEffects": false,
|
|
33
42
|
"keywords": [
|
|
@@ -38,12 +47,18 @@
|
|
|
38
47
|
"typescript",
|
|
39
48
|
"type-safe"
|
|
40
49
|
],
|
|
50
|
+
"engines": {
|
|
51
|
+
"node": ">=18.0.0"
|
|
52
|
+
},
|
|
53
|
+
"publishConfig": {
|
|
54
|
+
"access": "public"
|
|
55
|
+
},
|
|
41
56
|
"scripts": {
|
|
42
|
-
"dev": "tsup --watch",
|
|
43
57
|
"build": "tsup",
|
|
58
|
+
"dev": "tsup --watch",
|
|
44
59
|
"test": "vitest run",
|
|
45
60
|
"test:watch": "vitest",
|
|
46
61
|
"test:coverage": "vitest run --coverage",
|
|
47
|
-
"typecheck": "tsc --noEmit"
|
|
62
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json"
|
|
48
63
|
}
|
|
49
64
|
}
|