@oxog/i18n 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Ersin Koç
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,69 @@
1
+ type LocaleCode = string;
2
+ type TranslationValue = string | number | boolean | Date | null | undefined;
3
+ type TranslationParams = Record<string, TranslationValue>;
4
+ type ParseKeys<T> = T extends `${infer _Start}{{${infer Param}}}${infer Rest}` ? Param extends `${infer Key}:${infer Type}` ? {
5
+ [K in Key]: Type extends 'number' ? number : Type extends 'boolean' ? boolean : Type extends 'date' ? Date : string;
6
+ } & ParseKeys<Rest> : {
7
+ [K in Param]: TranslationValue;
8
+ } & ParseKeys<Rest> : {};
9
+ type TranslationFunction<TMessages extends Messages> = <TKey extends keyof TMessages, TParams extends ParseKeys<TMessages[TKey]>>(key: TKey, ...args: keyof TParams extends never ? [] : [params: TParams]) => string;
10
+ type Messages = Record<string, string>;
11
+ type LocaleMessages<TMessages extends Messages = Messages> = Record<LocaleCode, TMessages>;
12
+ interface I18nPlugin<TMessages extends Messages = Messages> {
13
+ name: string;
14
+ transform?: (key: keyof TMessages, value: string, params: TranslationParams, locale: LocaleCode) => string;
15
+ beforeLoad?: (locale: LocaleCode, messages: TMessages) => TMessages;
16
+ afterLoad?: (locale: LocaleCode, messages: TMessages) => void;
17
+ format?: (value: TranslationValue, format: string, locale: LocaleCode) => string;
18
+ }
19
+ interface I18nConfig<TMessages extends Messages = Messages> {
20
+ locale: LocaleCode;
21
+ fallbackLocale?: LocaleCode;
22
+ messages: LocaleMessages<TMessages>;
23
+ plugins?: I18nPlugin<TMessages>[];
24
+ warnOnMissingTranslations?: boolean;
25
+ pluralizationRules?: Record<LocaleCode, (count: number) => string>;
26
+ formats?: {
27
+ number?: Record<string, Intl.NumberFormatOptions>;
28
+ date?: Record<string, Intl.DateTimeFormatOptions>;
29
+ };
30
+ }
31
+ interface I18nInstance<TMessages extends Messages = Messages> {
32
+ readonly locale: LocaleCode;
33
+ readonly fallbackLocale?: LocaleCode;
34
+ readonly messages: LocaleMessages<TMessages>;
35
+ readonly t: TranslationFunction<TMessages>;
36
+ setLocale(locale: LocaleCode): void;
37
+ getLocale(): LocaleCode;
38
+ hasTranslation(key: keyof TMessages, locale?: LocaleCode): boolean;
39
+ addMessages(locale: LocaleCode, messages: Partial<TMessages>): void;
40
+ addPlugin(plugin: I18nPlugin<TMessages>): void;
41
+ removePlugin(pluginName: string): void;
42
+ formatNumber(value: number, format?: string): string;
43
+ formatDate(value: Date, format?: string): string;
44
+ formatRelativeTime(value: Date, baseDate?: Date): string;
45
+ subscribe(listener: (locale: LocaleCode) => void): () => void;
46
+ }
47
+ type ExtractTranslationKeys<T> = T extends Messages ? keyof T : never;
48
+ type ExtractTranslationParams<TMessages extends Messages, TKey extends keyof TMessages> = TMessages[TKey] extends string ? ParseKeys<TMessages[TKey]> : never;
49
+
50
+ declare function createI18n<TMessages extends Messages = Messages>(config: I18nConfig<TMessages>): I18nInstance<TMessages>;
51
+
52
+ declare function interpolate(template: string, params: TranslationParams, formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>, locale?: string): string;
53
+ declare function deepMerge<T extends Record<string, any>>(target: T, source: Partial<T>): T;
54
+ declare function getNestedValue<T>(obj: Record<string, any>, path: string): T | undefined;
55
+ declare function createCache<T>(): {
56
+ get: (key: string) => T | undefined;
57
+ set: (key: string, value: T) => void;
58
+ clear: () => void;
59
+ };
60
+ declare const defaultPluralRules: Record<string, (count: number) => string>;
61
+ declare function getPluralForm(locale: string, count: number, customRules?: Record<string, (count: number) => string>): string;
62
+
63
+ /**
64
+ * Markdown plugin for basic markdown syntax transformation
65
+ */
66
+ declare const markdownPlugin: I18nPlugin;
67
+ declare const icuPlugin: I18nPlugin;
68
+
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 };
@@ -0,0 +1,69 @@
1
+ type LocaleCode = string;
2
+ type TranslationValue = string | number | boolean | Date | null | undefined;
3
+ type TranslationParams = Record<string, TranslationValue>;
4
+ type ParseKeys<T> = T extends `${infer _Start}{{${infer Param}}}${infer Rest}` ? Param extends `${infer Key}:${infer Type}` ? {
5
+ [K in Key]: Type extends 'number' ? number : Type extends 'boolean' ? boolean : Type extends 'date' ? Date : string;
6
+ } & ParseKeys<Rest> : {
7
+ [K in Param]: TranslationValue;
8
+ } & ParseKeys<Rest> : {};
9
+ type TranslationFunction<TMessages extends Messages> = <TKey extends keyof TMessages, TParams extends ParseKeys<TMessages[TKey]>>(key: TKey, ...args: keyof TParams extends never ? [] : [params: TParams]) => string;
10
+ type Messages = Record<string, string>;
11
+ type LocaleMessages<TMessages extends Messages = Messages> = Record<LocaleCode, TMessages>;
12
+ interface I18nPlugin<TMessages extends Messages = Messages> {
13
+ name: string;
14
+ transform?: (key: keyof TMessages, value: string, params: TranslationParams, locale: LocaleCode) => string;
15
+ beforeLoad?: (locale: LocaleCode, messages: TMessages) => TMessages;
16
+ afterLoad?: (locale: LocaleCode, messages: TMessages) => void;
17
+ format?: (value: TranslationValue, format: string, locale: LocaleCode) => string;
18
+ }
19
+ interface I18nConfig<TMessages extends Messages = Messages> {
20
+ locale: LocaleCode;
21
+ fallbackLocale?: LocaleCode;
22
+ messages: LocaleMessages<TMessages>;
23
+ plugins?: I18nPlugin<TMessages>[];
24
+ warnOnMissingTranslations?: boolean;
25
+ pluralizationRules?: Record<LocaleCode, (count: number) => string>;
26
+ formats?: {
27
+ number?: Record<string, Intl.NumberFormatOptions>;
28
+ date?: Record<string, Intl.DateTimeFormatOptions>;
29
+ };
30
+ }
31
+ interface I18nInstance<TMessages extends Messages = Messages> {
32
+ readonly locale: LocaleCode;
33
+ readonly fallbackLocale?: LocaleCode;
34
+ readonly messages: LocaleMessages<TMessages>;
35
+ readonly t: TranslationFunction<TMessages>;
36
+ setLocale(locale: LocaleCode): void;
37
+ getLocale(): LocaleCode;
38
+ hasTranslation(key: keyof TMessages, locale?: LocaleCode): boolean;
39
+ addMessages(locale: LocaleCode, messages: Partial<TMessages>): void;
40
+ addPlugin(plugin: I18nPlugin<TMessages>): void;
41
+ removePlugin(pluginName: string): void;
42
+ formatNumber(value: number, format?: string): string;
43
+ formatDate(value: Date, format?: string): string;
44
+ formatRelativeTime(value: Date, baseDate?: Date): string;
45
+ subscribe(listener: (locale: LocaleCode) => void): () => void;
46
+ }
47
+ type ExtractTranslationKeys<T> = T extends Messages ? keyof T : never;
48
+ type ExtractTranslationParams<TMessages extends Messages, TKey extends keyof TMessages> = TMessages[TKey] extends string ? ParseKeys<TMessages[TKey]> : never;
49
+
50
+ declare function createI18n<TMessages extends Messages = Messages>(config: I18nConfig<TMessages>): I18nInstance<TMessages>;
51
+
52
+ declare function interpolate(template: string, params: TranslationParams, formatters?: Map<string, (value: TranslationValue, format?: string, locale?: string) => string>, locale?: string): string;
53
+ declare function deepMerge<T extends Record<string, any>>(target: T, source: Partial<T>): T;
54
+ declare function getNestedValue<T>(obj: Record<string, any>, path: string): T | undefined;
55
+ declare function createCache<T>(): {
56
+ get: (key: string) => T | undefined;
57
+ set: (key: string, value: T) => void;
58
+ clear: () => void;
59
+ };
60
+ declare const defaultPluralRules: Record<string, (count: number) => string>;
61
+ declare function getPluralForm(locale: string, count: number, customRules?: Record<string, (count: number) => string>): string;
62
+
63
+ /**
64
+ * Markdown plugin for basic markdown syntax transformation
65
+ */
66
+ declare const markdownPlugin: I18nPlugin;
67
+ declare const icuPlugin: I18nPlugin;
68
+
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 };
package/dist/index.js ADDED
@@ -0,0 +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
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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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AC,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};"]}
package/dist/index.mjs ADDED
@@ -0,0 +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
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +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,GAAM,CAACC,CAAAA,CAAUC,CAAM,CAAA,CAAIF,CAAAA,CAAI,MAAK,CAAE,KAAA,CAAM,GAAG,CAAA,CAAE,GAAA,CAAKG,GAAcA,CAAAA,CAAE,IAAA,EAAM,CAAA,CAE5E,GAAI,EAAEF,CAAAA,IAAYL,CAAAA,CAAAA,CAChB,OAAI,OAAO,OAAA,CAAY,GAAA,EAAe,QAAQ,GAAA,EAAK,QAAA,GAAa,cAC9D,OAAA,CAAQ,IAAA,CAAK,yCAAyCK,CAAQ,CAAA,CAAE,EAE3DF,CAAAA,CAGT,IAAMK,EAAQR,CAAAA,CAAOK,CAAQ,EAE7B,GAAIC,CAAAA,EAAUL,CAAAA,EAAY,GAAA,CAAIK,CAAM,CAAA,CAClC,GAAI,CAEF,OADkBL,EAAW,GAAA,CAAIK,CAAM,EACtBE,CAAAA,CAAOJ,CAAAA,CAAI,QAAA,CAAS,GAAG,CAAA,CAAIA,CAAAA,CAAI,MAAM,GAAG,CAAA,CAAE,MAAM,CAAC,CAAA,CAAE,KAAK,GAAG,CAAA,CAAI,KAAA,CAAA,CAAWF,CAAM,CACnG,CAAA,MAASO,EAAO,CACd,OAAI,OAAO,OAAA,CA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AAAA,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};"]}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@oxog/i18n",
3
+ "version": "0.0.0",
4
+ "description": "Modern, lightweight, and framework-agnostic internationalization library",
5
+ "author": "Ersin Koç",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/ersinkoc/i18n",
10
+ "directory": "packages/core"
11
+ },
12
+ "main": "./dist/index.js",
13
+ "module": "./dist/index.mjs",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.mjs",
19
+ "require": "./dist/index.js"
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "devDependencies": {
27
+ "@vitest/coverage-v8": "^1.2.1",
28
+ "tsup": "^8.0.1",
29
+ "typescript": "^5.3.3",
30
+ "vitest": "^1.2.1"
31
+ },
32
+ "sideEffects": false,
33
+ "keywords": [
34
+ "i18n",
35
+ "internationalization",
36
+ "localization",
37
+ "translation",
38
+ "typescript",
39
+ "type-safe"
40
+ ],
41
+ "scripts": {
42
+ "dev": "tsup --watch",
43
+ "build": "tsup",
44
+ "test": "vitest run",
45
+ "test:watch": "vitest",
46
+ "test:coverage": "vitest run --coverage",
47
+ "typecheck": "tsc --noEmit"
48
+ }
49
+ }