@oxog/i18n 0.2.2 → 0.2.3

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/dist/index.d.mts CHANGED
@@ -139,6 +139,15 @@ declare const defaultPluralRules: Record<string, (count: number) => string>;
139
139
  * subtag (`pt-BR` → `pt`); otherwise `Intl.PluralRules` decides.
140
140
  */
141
141
  declare function getPluralForm(locale: string, count: number, customRules?: Record<string, (count: number) => string>): string;
142
+ /**
143
+ * Marks the braces of a value a plugin inserts into a message, so the `{{name}}`
144
+ * interpolation that runs afterwards never treats text from a parameter value as a
145
+ * placeholder. {@link releaseBraces} removes the marks once interpolation is done.
146
+ * @internal
147
+ */
148
+ declare function guardBraces(value: string): string;
149
+ /** Removes the marks {@link guardBraces} added. @internal */
150
+ declare function releaseBraces(text: string): string;
142
151
 
143
152
  /**
144
153
  * Markdown plugin for basic markdown syntax transformation.
@@ -149,4 +158,4 @@ declare const markdownPlugin: I18nPlugin;
149
158
  */
150
159
  declare const icuPlugin: I18nPlugin;
151
160
 
152
- 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 };
161
+ 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, guardBraces, icuPlugin, interpolate, markdownPlugin, releaseBraces };
package/dist/index.d.ts CHANGED
@@ -139,6 +139,15 @@ declare const defaultPluralRules: Record<string, (count: number) => string>;
139
139
  * subtag (`pt-BR` → `pt`); otherwise `Intl.PluralRules` decides.
140
140
  */
141
141
  declare function getPluralForm(locale: string, count: number, customRules?: Record<string, (count: number) => string>): string;
142
+ /**
143
+ * Marks the braces of a value a plugin inserts into a message, so the `{{name}}`
144
+ * interpolation that runs afterwards never treats text from a parameter value as a
145
+ * placeholder. {@link releaseBraces} removes the marks once interpolation is done.
146
+ * @internal
147
+ */
148
+ declare function guardBraces(value: string): string;
149
+ /** Removes the marks {@link guardBraces} added. @internal */
150
+ declare function releaseBraces(text: string): string;
142
151
 
143
152
  /**
144
153
  * Markdown plugin for basic markdown syntax transformation.
@@ -149,4 +158,4 @@ declare const markdownPlugin: I18nPlugin;
149
158
  */
150
159
  declare const icuPlugin: I18nPlugin;
151
160
 
152
- 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 };
161
+ 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, guardBraces, icuPlugin, interpolate, markdownPlugin, releaseBraces };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';function S(r,n,o,t,s){if(typeof r!="string")return String(r);try{return r.replace(/\{\{([^}]+)\}\}/g,(c,g)=>{let d=l(g);return d===void 0?c:s?s(d):d})}catch(c){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Template interpolation error:",c),r}function l(c){try{let[g,d]=c.trim().split(":").map(b=>b.trim());if(!Object.prototype.hasOwnProperty.call(n,g)){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation parameter: ${g}`);return}let m=n[g];if(d&&o?.has(d))try{let b=o.get(d);if(!b)return String(m);let f=b(m,c.includes(":")?c.split(":").slice(1).join(":"):void 0,t);return typeof f!="string"?(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter '${d}' must return a string, got ${typeof f}`),String(m)):f}catch(b){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter error for ${d}:`,b),String(m)}return m==null?"":m instanceof Date?m.toLocaleDateString(t||"en-US",{year:"numeric",month:"2-digit",day:"2-digit"}):String(m)}catch(g){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Parameter interpolation error:",g);return}}}function D(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 t in n){if(t==="__proto__"||t==="constructor"||t==="prototype"){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Blocked attempt to set dangerous property: ${t}`);continue}if(!Object.prototype.hasOwnProperty.call(n,t))continue;let s=n[t];if(s!==void 0)if(typeof s=="object"&&s!==null&&!Array.isArray(s)&&!(s instanceof Date)){let l=o[t];o[t]=D(l&&typeof l=="object"?l:{},s);}else o[t]=s;}return o}catch(o){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] DeepMerge error:",o),r}}function A(r,n){if(!(!r||typeof r!="object"||!n||typeof n!="string"))try{let o=n.split("."),t=r;for(let s of o)if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,s))t=t[s];else return;return t}catch(o){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] getNestedValue error:",o);return}}function V(r){let n=new Map,o=r?.maxSize??1e3;return {get:t=>{let s=n.get(t);return s!==void 0&&(n.delete(t),n.set(t,s)),s},set:(t,s)=>{if(n.has(t))n.delete(t);else if(n.size>=o){let l=n.keys().next().value;l!==void 0&&n.delete(l);}n.set(t,s);},clear:()=>n.clear(),size:()=>n.size}}var ae={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"},R=new Map;function ee(r){let n=R.get(r);if(!n){try{let o=r.replace(/_/g,"-");n=new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(o).length>0?o:"en");}catch{n=new Intl.PluralRules("en");}R.set(r,n);}return n}function F(r,n,o){if(o){let t=r.split(/[-_]/)[0],s=Object.prototype.hasOwnProperty.call(o,r)?o[r]:Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0;if(typeof s=="function")return s(n)}return ee(r).select(n)}function re(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 n=Object.keys(r.messages).length>0;n||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Messages object is empty - all translations will return keys");let o=e=>N(e).some(i=>Object.prototype.hasOwnProperty.call(r.messages,i));if(n&&!o(r.locale)&&!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(!o(r.locale)&&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&&!o(r.fallbackLocale)){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 t=r.locale,s=r.fallbackLocale,l=structuredClone(r.messages),c=[...r.plugins||[]],g=new Set,d=V(),m=0,b=()=>{m++,g.forEach(e=>{try{e(t);}catch(i){f(i,"Locale change listener");}});},f=(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);},y=new Map;function E(e,i,a){if(!e)return;let u=h=>Object.prototype.hasOwnProperty.call(e,h)?e[h]:void 0;if(i&&u(i))return u(i);let p=(i||"").split(":").map(h=>h.trim());return p[0]===a&&p.shift(),u(p.join(":")||"default")}y.set("number",(e,i,a)=>{if(typeof e!="number")return String(e);let u=E(r.formats?.number,i,"number")||{};return new Intl.NumberFormat(a||t,u).format(e)}),y.set("date",(e,i,a)=>{if(!(e instanceof Date))return String(e);let u=E(r.formats?.date,i,"date")||{};return new Intl.DateTimeFormat(a||t,u).format(e)}),y.set("currency",(e,i,a)=>{if(typeof e!="number")return String(e);let u=(i||"currency:USD").split(":"),p=u.length>1&&u[1]||"USD";try{return new Intl.NumberFormat(a||t,{style:"currency",currency:p}).format(e)}catch(h){return f(h,`Currency formatter error for currency '${p}'`),`${p} ${e}`}}),c.forEach(e=>{e.format&&y.set(e.name,(i,a,u)=>e.format(i,a??"",u??t));});function T(e,i){if(!Object.prototype.hasOwnProperty.call(l,i))return;let a=l[i];if(!a||typeof a!="object")return;let u=Object.prototype.hasOwnProperty.call(a,e)?a[e]:A(a,e);return typeof u=="string"?u:void 0}function j(e,i,a){let u=k(a),p=i&&Object.prototype.hasOwnProperty.call(i,"count")?i.count:void 0;for(let h of u){if(typeof p=="number"){let x=new Set;p===0&&x.add("zero"),x.add(F(h,p,r.pluralizationRules)),x.add("other");for(let $ of x){let w=T(`${e}.${$}`,h);if(w)return {message:w,messageLocale:h}}}let v=T(e,h);if(v)return {message:v,messageLocale:h}}}function k(e){return [...new Set([...N(e),...s?N(s):[]])]}function I(e,i,a=t){try{let u=i?te(i):"",p=u===void 0?void 0:`${a}:${e}:${u}`,h=p===void 0?void 0:d.get(p);if(h!==void 0)return h;let v=j(e,i,a);if(!v)return r.warnOnMissingTranslations&&typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation: ${e} for locale: ${a}`),e;let{message:x,messageLocale:$}=v,w=x;for(let O of c)if(O.transform)try{let L=O.transform(e,w,i||{},a,$);if(typeof L!="string"){f(new Error(`Plugin transform must return a string, got ${typeof L}`),`Plugin ${O.name} transform validation`);continue}w=L;}catch(L){f(L,`Plugin ${O.name} transform`);}let M=c.filter(O=>typeof O.escapeValue=="function");return w=S(w,i||{},y,t,M.length>0?O=>M.reduce((L,Z)=>Z.escapeValue(L),O):void 0),p!==void 0&&d.set(p,w),w}catch(u){return f(u,`Translation error for key ${e}`),e}}let W=(e,i)=>I(String(e),i);function H(e){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");N(e).some(i=>Object.prototype.hasOwnProperty.call(l,i))||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Locale '${e}' not found in messages. Available locales: ${Object.keys(l).join(", ")}`),e!==t&&(t=e,d.clear(),b());}function U(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{l[e]||(l[e]={});let a=i;for(let u of c)if(u.beforeLoad)try{let p=u.beforeLoad(e,a);if(!p||typeof p!="object"||Array.isArray(p)){f(new Error(`Plugin beforeLoad must return an object, got ${typeof p}`),`Plugin ${u.name} beforeLoad validation`);continue}a=p;}catch(p){f(p,`Plugin ${u.name} beforeLoad`);}l[e]=D(l[e],a);for(let u of c)if(u.afterLoad)try{u.afterLoad(e,l[e]);}catch(p){f(p,`Plugin ${u.name} afterLoad`);}d.clear(),k(t).includes(e)&&b();}catch(a){throw f(a,"Error adding messages"),a}}function q(e,i,a){let u=i||t;return (a?.exact?[u]:k(u)).some(h=>T(String(e),h)!==void 0)}function J(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&&y.set(e.name,(a,u,p)=>e.format(a,u??"",p??t)),d.clear(),b();}function B(e){let i=c.findIndex(a=>a.name===e);i!==-1&&(c.splice(i,1),y.delete(e),d.clear(),b());}function G(e){return g.add(e),()=>g.delete(e)}function Q(e,i){let a=y.get("number");if(!a)throw new Error("[i18n] Number formatter not available. Please add a plugin that provides number formatting.");return a(e,i,t)}function X(e,i){let a=y.get("date");if(!a)throw new Error("[i18n] Date formatter not available. Please add a plugin that provides date formatting.");return a(e,i,t)}function Y(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),u=new Intl.RelativeTimeFormat(t,{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[h,v]of p)if(Math.abs(a)>=v)return u.format(Math.round(a/v),h);return u.format(0,"second")}return {get locale(){return t},get fallbackLocale(){return s},get messages(){return l},get revision(){return m},t:W,setLocale:H,getLocale:()=>t,hasTranslation:q,addMessages:U,addPlugin:J,removePlugin:B,subscribe:G,formatNumber:Q,formatDate:X,formatRelativeTime:Y}}function N(r){let n=[r],o=r;for(;;){let t=Math.max(o.lastIndexOf("-"),o.lastIndexOf("_"));if(t<=0)break;o=o.slice(0,t),t=Math.max(o.lastIndexOf("-"),o.lastIndexOf("_")),t>0&&o.length-t-1===1&&(o=o.slice(0,t)),n.push(o);}return n}function te(r){let n=[];for(let o of Object.keys(r).sort()){let t=r[o],s;if(typeof t=="string")s=JSON.stringify(t);else if(typeof t=="number")s=Object.is(t,-0)?"n-0":`n${t}`;else if(typeof t=="boolean"||t===null||t===void 0)s=String(t);else if(t instanceof Date)s=`d${t.getTime()}`;else return;n.push(`${JSON.stringify(o)}=${s}`);}return n.join(",")}var P=class extends Error{},C=class{constructor(n){this.source=n;}cursor=0;parse(){return this.message(0,false).parts}take(n){n.lastIndex=this.cursor;let o=n.exec(this.source)?.[0];return o!==void 0&&(this.cursor+=o.length),o}expect(n){let o=this.take(n);if(o===void 0)throw new P;return o}space(){this.take(/\s+/y);}number(){let n=Number(this.expect(/[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/y));if(!Number.isFinite(n))throw new P;return n}quote(){let n="";for(this.cursor++;this.cursor<this.source.length;){let o=this.source.charAt(this.cursor++);if(o==="'"&&!this.take(/'/y))break;n+=o;}return n}message(n,o){if(n>64)throw new P;let t=[],s="";function l(){s&&t.push(s),s="";}for(;this.cursor<this.source.length;){let c=this.source.charAt(this.cursor);if(c==="}"){if(n===0)throw new P;return this.cursor++,l(),{parts:t,closed:true}}if(c==="{"){let g=this.take(/\{\{[^{}]*\}\}/y);g!==void 0?s+=g:(l(),t.push(this.argument(n)));}else c==="'"&&this.take(/''/y)?s+="'":c==="'"&&(["{","}"].includes(this.source.charAt(this.cursor+1))||o&&this.source.charAt(this.cursor+1)==="#")?s+=this.quote():(this.cursor++,c==="#"&&o?(l(),t.push({kind:"number"})):s+=c);}return l(),{parts:t,closed:false}}argument(n){let o=this.cursor++;this.space();let t=this.expect(/[\p{ID_Continue}]+/uy);if(this.space(),this.take(/\}/y))return {kind:"value",name:t,source:this.source.slice(o,this.cursor)};this.expect(/,/y),this.space();let s=this.expect(/selectordinal|plural|select/y);this.space(),this.expect(/,/y),this.space();let l=s!=="select"&&this.take(/offset\s*:\s*/y)?this.number():0;this.space();let c=new Map;for(;!this.take(/\}/y);){let g=s!=="select"&&this.take(/=/y)?"="+this.number():this.expect(/[\p{ID_Continue}]+/uy);this.space(),this.expect(/\{/y);let d=this.message(n+1,s!=="select");if(!d.closed)throw new P;c.has(g)||c.set(g,d.parts),this.space();}if(!c.has("other"))throw new P;return {kind:s,name:t,choices:c,offset:l,source:this.source.slice(o,this.cursor)}}};function ne(r){try{return Intl.getCanonicalLocales(r.replace(/_/g,"-"))[0]??"en"}catch{return "en"}}function oe(r,n,o){let t=ne(o),s={maximumSignificantDigits:21},l,c,g;function d(m,b){return m.map(f=>{if(typeof f=="string")return f;if(f.kind==="number")return b===void 0?"#":(g??=new Intl.NumberFormat(t,s)).format(b);if(!Object.hasOwn(n,f.name))return f.source;let y=n[f.name];if(f.kind==="value")return String(y);if(f.kind==="select"){let I=f.choices.get(String(y))??f.choices.get("other");return I?d(I):f.source}if(typeof y!="number"||!Number.isFinite(y))return f.source;let E=y-f.offset;if(!Number.isFinite(E))return f.source;let T=f.choices.get("="+y);if(T)return d(T,E);let j=f.kind==="plural"?l??=new Intl.PluralRules(t,s):c??=new Intl.PluralRules(t,{...s,type:"ordinal"}),k=f.choices.get(j.select(E))??f.choices.get("other");return k?d(k,E):f.source}).join("")}return d(r)}function K(){return {name:"icu",transform:(r,n,o,t,s)=>{if(!/[{']/.test(n))return n;try{return oe(new C(n).parse(),o,s??t)}catch(l){if(l instanceof P)return n;throw l}}}}function _(r){let n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return r.replace(/[&<>"'/]/g,o=>n[o])}function se(r){let n=Array.from(r).filter(o=>o.charCodeAt(0)>32&&o.charCodeAt(0)!==127).join("").toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:")||n.startsWith("vbscript:")||n.startsWith("file:")?"#":_(r)}function ie(r,n){return r.replace(/\{\{([^}]+)\}\}/g,(o,t)=>{let s=t.split(":")[0].trim();if(!Object.prototype.hasOwnProperty.call(n,s))return o;let l=n[s];return l==null?"":String(l)})}function z(){return {name:"markdown",escapeValue:_,transform:(r,n,o,t)=>{let s=n,l=[],c=0;s=s.replace(/`(.*?)`/g,(g,d)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return l[c]=`<code>${_(d)}</code>`,c++,m}),s=s.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(g,d,m)=>{let b=`__MARKDOWN_PLACEHOLDER_${c}__`,f=se(ie(m,o||{})).replace(/[{}]/g,y=>y==="{"?"&#123;":"&#125;");return l[c]=`<a href="${f}">${_(d)}</a>`,c++,b}),s=s.replace(/\*\*(.*?)\*\*/g,(g,d)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return l[c]=`<strong>${_(d)}</strong>`,c++,m}),s=s.replace(/\*(.*?)\*/g,(g,d)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return l[c]=`<em>${_(d)}</em>`,c++,m}),s=_(s);for(let g=l.length-1;g>=0;g--)s=s.replace(`__MARKDOWN_PLACEHOLDER_${g}__`,()=>l[g]);return s}}}var me=z(),he=K();exports.createCache=V;exports.createI18n=re;exports.deepMerge=D;exports.defaultPluralRules=ae;exports.getNestedValue=A;exports.getPluralForm=F;exports.icuPlugin=he;exports.interpolate=S;exports.markdownPlugin=me;//# sourceMappingURL=index.js.map
1
+ 'use strict';function S(e,n,s,t,o){if(typeof e!="string")return String(e);try{return e.replace(/\{\{([^}]+)\}\}/g,(c,g)=>{let p=u(g);return p===void 0?c:o?o(p):p})}catch(c){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Template interpolation error:",c),e}function u(c){try{let[g,p]=c.trim().split(":").map(b=>b.trim());if(!Object.prototype.hasOwnProperty.call(n,g)){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation parameter: ${g}`);return}let m=n[g];if(p&&s?.has(p))try{let b=s.get(p);if(!b)return String(m);let f=b(m,c.includes(":")?c.split(":").slice(1).join(":"):void 0,t);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(b){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter error for ${p}:`,b),String(m)}return m==null?"":m instanceof Date?m.toLocaleDateString(t||"en-US",{year:"numeric",month:"2-digit",day:"2-digit"}):String(m)}catch(g){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Parameter interpolation error:",g);return}}}function M(e,n){if(!e||typeof e!="object")throw new Error("[i18n] Invalid target for deepMerge");if(!n||typeof n!="object")return e;try{let s={...e};for(let t in n){if(t==="__proto__"||t==="constructor"||t==="prototype"){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Blocked attempt to set dangerous property: ${t}`);continue}if(!Object.prototype.hasOwnProperty.call(n,t))continue;let o=n[t];if(o!==void 0)if(typeof o=="object"&&o!==null&&!Array.isArray(o)&&!(o instanceof Date)){let u=s[t];s[t]=M(u&&typeof u=="object"?u:{},o);}else s[t]=o;}return s}catch(s){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] DeepMerge error:",s),e}}function A(e,n){if(!(!e||typeof e!="object"||!n||typeof n!="string"))try{let s=n.split("."),t=e;for(let o of s)if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,o))t=t[o];else return;return t}catch(s){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] getNestedValue error:",s);return}}function V(e){let n=new Map,s=e?.maxSize??1e3;return {get:t=>{let o=n.get(t);return o!==void 0&&(n.delete(t),n.set(t,o)),o},set:(t,o)=>{if(n.has(t))n.delete(t);else if(n.size>=s){let u=n.keys().next().value;u!==void 0&&n.delete(u);}n.set(t,o);},clear:()=>n.clear(),size:()=>n.size}}var ue={en:e=>e===0?"zero":e===1?"one":"other",es:e=>e===0?"zero":e===1?"one":"other",fr:e=>e===0||e===1?"one":"other",de:e=>e===1?"one":"other",ja:()=>"other",ko:()=>"other",zh:()=>"other"},R=new Map;function te(e){let n=R.get(e);if(!n){try{let s=e.replace(/_/g,"-");n=new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(s).length>0?s:"en");}catch{n=new Intl.PluralRules("en");}R.set(e,n);}return n}function F(e,n,s){if(s){let t=e.split(/[-_]/)[0],o=Object.prototype.hasOwnProperty.call(s,e)?s[e]:Object.prototype.hasOwnProperty.call(s,t)?s[t]:void 0;if(typeof o=="function")return o(n)}return te(e).select(n)}function K(e){return e.replace(/\{/g,"{\uE000")}function z(e){return e.replace(/\{\uE000/g,"{")}function ne(e){if(!e)throw new Error("[i18n] Configuration is required");if(!e.locale||typeof e.locale!="string"||e.locale.trim()==="")throw new Error("[i18n] Locale must be a non-empty string");if(!e.messages)throw new Error("[i18n] Messages are required");if(typeof e.messages!="object"||Array.isArray(e.messages)||e.messages===null)throw new Error("[i18n] Messages must be an object");let n=Object.keys(e.messages).length>0;n||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Messages object is empty - all translations will return keys");let s=r=>$(r).some(i=>Object.prototype.hasOwnProperty.call(e.messages,i));if(n&&!s(e.locale)&&!e.fallbackLocale){let r=Object.keys(e.messages).join(", ");throw new Error(`[i18n] Locale '${e.locale}' not found in messages and no fallback locale provided. Available locales: ${r}`)}if(!s(e.locale)&&e.fallbackLocale&&typeof process<"u"&&process.env?.NODE_ENV!=="production"){let r=Object.keys(e.messages).join(", ");console.warn(`[i18n] Locale '${e.locale}' not found in messages, will use fallback locale '${e.fallbackLocale}'. Available locales: ${r}`);}if(e.fallbackLocale&&!s(e.fallbackLocale)){let r=Object.keys(e.messages).join(", ");typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Fallback locale '${e.fallbackLocale}' not found in messages. Available locales: ${r}`);}let t=e.locale,o=e.fallbackLocale,u=structuredClone(e.messages),c=[...e.plugins||[]],g=new Set,p=V(),m=0,b=()=>{m++,g.forEach(r=>{try{r(t);}catch(i){f(i,"Locale change listener");}});},f=(r,i)=>{let a=r instanceof Error?r:new Error(String(r));if(e.onError)try{e.onError(a,i);}catch{}typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] ${i}:`,a);},y=new Map;function L(r,i,a){if(!r)return;let l=h=>Object.prototype.hasOwnProperty.call(r,h)?r[h]:void 0;if(i&&l(i))return l(i);let d=(i||"").split(":").map(h=>h.trim());return d[0]===a&&d.shift(),l(d.join(":")||"default")}y.set("number",(r,i,a)=>{if(typeof r!="number")return String(r);let l=L(e.formats?.number,i,"number")||{};return new Intl.NumberFormat(a||t,l).format(r)}),y.set("date",(r,i,a)=>{if(!(r instanceof Date))return String(r);let l=L(e.formats?.date,i,"date")||{};return new Intl.DateTimeFormat(a||t,l).format(r)}),y.set("currency",(r,i,a)=>{if(typeof r!="number")return String(r);let l=(i||"currency:USD").split(":"),d=l.length>1&&l[1]||"USD";try{return new Intl.NumberFormat(a||t,{style:"currency",currency:d}).format(r)}catch(h){return f(h,`Currency formatter error for currency '${d}'`),`${d} ${r}`}}),c.forEach(r=>{r.format&&y.set(r.name,(i,a,l)=>r.format(i,a??"",l??t));});function x(r,i){if(!Object.prototype.hasOwnProperty.call(u,i))return;let a=u[i];if(!a||typeof a!="object")return;let l=Object.prototype.hasOwnProperty.call(a,r)?a[r]:A(a,r);return typeof l=="string"?l:void 0}function D(r,i,a){let l=k(a),d=i&&Object.prototype.hasOwnProperty.call(i,"count")?i.count:void 0;for(let h of l){if(typeof d=="number"){let E=new Set;d===0&&E.add("zero"),E.add(F(h,d,e.pluralizationRules)),E.add("other");for(let I of E){let w=x(`${r}.${I}`,h);if(w)return {message:w,messageLocale:h}}}let P=x(r,h);if(P)return {message:P,messageLocale:h}}}function k(r){return [...new Set([...$(r),...o?$(o):[]])]}function j(r,i,a=t){try{let l=i?se(i):"",d=l===void 0?void 0:`${a}:${r}:${l}`,h=d===void 0?void 0:p.get(d);if(h!==void 0)return h;let P=D(r,i,a);if(!P)return e.warnOnMissingTranslations&&typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation: ${r} for locale: ${a}`),r;let{message:E,messageLocale:I}=P,w=E;for(let O of c)if(O.transform)try{let _=O.transform(r,w,i||{},a,I);if(typeof _!="string"){f(new Error(`Plugin transform must return a string, got ${typeof _}`),`Plugin ${O.name} transform validation`);continue}w=_;}catch(_){f(_,`Plugin ${O.name} transform`);}let N=c.filter(O=>typeof O.escapeValue=="function");return w=S(w,i||{},y,t,N.length>0?O=>N.reduce((_,re)=>re.escapeValue(_),O):void 0),w=z(w),d!==void 0&&p.set(d,w),w}catch(l){return f(l,`Translation error for key ${r}`),r}}let H=(r,i)=>j(String(r),i);function q(r){if(!r||typeof r!="string")throw new Error("[i18n] Invalid locale provided");$(r).some(i=>Object.prototype.hasOwnProperty.call(u,i))||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Locale '${r}' not found in messages. Available locales: ${Object.keys(u).join(", ")}`),r!==t&&(t=r,p.clear(),b());}function B(r,i){if(!r||typeof r!="string")throw new Error("[i18n] Invalid locale provided");if(!i||typeof i!="object")throw new Error("[i18n] Invalid messages provided");try{u[r]||(u[r]={});let a=i;for(let l of c)if(l.beforeLoad)try{let d=l.beforeLoad(r,a);if(!d||typeof d!="object"||Array.isArray(d)){f(new Error(`Plugin beforeLoad must return an object, got ${typeof d}`),`Plugin ${l.name} beforeLoad validation`);continue}a=d;}catch(d){f(d,`Plugin ${l.name} beforeLoad`);}u[r]=M(u[r],a);for(let l of c)if(l.afterLoad)try{l.afterLoad(r,u[r]);}catch(d){f(d,`Plugin ${l.name} afterLoad`);}p.clear(),k(t).includes(r)&&b();}catch(a){throw f(a,"Error adding messages"),a}}function J(r,i,a){let l=i||t;return (a?.exact?[l]:k(l)).some(h=>x(String(r),h)!==void 0)}function G(r){let i=c.findIndex(a=>a.name===r.name);i!==-1&&(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Plugin '${r.name}' already registered. Replacing existing plugin.`),c.splice(i,1)),c.push(r),r.format&&y.set(r.name,(a,l,d)=>r.format(a,l??"",d??t)),p.clear(),b();}function Q(r){let i=c.findIndex(a=>a.name===r);i!==-1&&(c.splice(i,1),y.delete(r),p.clear(),b());}function X(r){return g.add(r),()=>g.delete(r)}function Y(r,i){let a=y.get("number");if(!a)throw new Error("[i18n] Number formatter not available. Please add a plugin that provides number formatting.");return a(r,i,t)}function Z(r,i){let a=y.get("date");if(!a)throw new Error("[i18n] Date formatter not available. Please add a plugin that provides date formatting.");return a(r,i,t)}function ee(r,i=new Date){if(!(r instanceof Date)||isNaN(r.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.trunc((r.getTime()-i.getTime())/1e3),l=new Intl.RelativeTimeFormat(t,{numeric:"auto"}),d=[["year",60*60*24*365],["month",60*60*24*30,12],["week",60*60*24*7],["day",60*60*24,7],["hour",60*60,24],["minute",60,60],["second",1]],h=a<0?-1:1;for(let P=0;P<d.length;P++){let[E,I,w]=d[P];if(Math.abs(a)>=I){let N=Math.round(Math.abs(a)/I);return w!==void 0&&N>=w?l.format(h,d[P-1][0]):l.format(h*N,E)}}return l.format(0,"second")}return {get locale(){return t},get fallbackLocale(){return o},get messages(){return u},get revision(){return m},t:H,setLocale:q,getLocale:()=>t,hasTranslation:J,addMessages:B,addPlugin:G,removePlugin:Q,subscribe:X,formatNumber:Y,formatDate:Z,formatRelativeTime:ee}}function $(e){let n=[e],s=e;for(;;){let t=Math.max(s.lastIndexOf("-"),s.lastIndexOf("_"));if(t<=0)break;s=s.slice(0,t),t=Math.max(s.lastIndexOf("-"),s.lastIndexOf("_")),t>0&&s.length-t-1===1&&(s=s.slice(0,t)),n.push(s);}return n}function se(e){let n=[];for(let s of Object.keys(e).sort()){let t=e[s],o;if(typeof t=="string")o=JSON.stringify(t);else if(typeof t=="number")o=Object.is(t,-0)?"n-0":`n${t}`;else if(typeof t=="boolean"||t===null||t===void 0)o=String(t);else if(t instanceof Date)o=`d${t.getTime()}`;else return;n.push(`${JSON.stringify(s)}=${o}`);}return n.join(",")}var v=class extends Error{},C=class{constructor(n){this.source=n;}cursor=0;parse(){return this.message(0,false).parts}take(n){n.lastIndex=this.cursor;let s=n.exec(this.source)?.[0];return s!==void 0&&(this.cursor+=s.length),s}expect(n){let s=this.take(n);if(s===void 0)throw new v;return s}space(){this.take(/\s+/y);}number(){let n=Number(this.expect(/[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/y));if(!Number.isFinite(n))throw new v;return n}quote(){let n="";for(this.cursor++;this.cursor<this.source.length;){let s=this.source.charAt(this.cursor++);if(s==="'"&&!this.take(/'/y))break;n+=s;}return n}message(n,s){if(n>64)throw new v;let t=[],o="";function u(){o&&t.push(o),o="";}for(;this.cursor<this.source.length;){let c=this.source.charAt(this.cursor);if(c==="}"){if(n===0)throw new v;return this.cursor++,u(),{parts:t,closed:true}}if(c==="{"){let g=this.take(/\{\{[^{}]*\}\}/y);g!==void 0?o+=g:(u(),t.push(this.argument(n)));}else c==="'"&&this.take(/''/y)?o+="'":c==="'"&&(["{","}"].includes(this.source.charAt(this.cursor+1))||s&&this.source.charAt(this.cursor+1)==="#")?o+=this.quote():(this.cursor++,c==="#"&&s?(u(),t.push({kind:"number"})):o+=c);}return u(),{parts:t,closed:false}}argument(n){let s=this.cursor++;this.space();let t=this.expect(/[\p{ID_Continue}]+/uy);if(this.space(),this.take(/\}/y))return {kind:"value",name:t,source:this.source.slice(s,this.cursor)};this.expect(/,/y),this.space();let o=this.expect(/selectordinal|plural|select/y);this.space(),this.expect(/,/y),this.space();let u=o!=="select"&&this.take(/offset\s*:\s*/y)?this.number():0;this.space();let c=new Map;for(;!this.take(/\}/y);){let g=o!=="select"&&this.take(/=/y)?"="+this.number():this.expect(/[\p{ID_Continue}]+/uy);this.space(),this.expect(/\{/y);let p=this.message(n+1,o!=="select");if(!p.closed)throw new v;c.has(g)||c.set(g,p.parts),this.space();}if(!c.has("other"))throw new v;return {kind:o,name:t,choices:c,offset:u,source:this.source.slice(s,this.cursor)}}};function oe(e){try{return Intl.getCanonicalLocales(e.replace(/_/g,"-"))[0]??"en"}catch{return "en"}}function ie(e,n,s){let t=oe(s),o={maximumSignificantDigits:21},u,c,g;function p(m,b){return m.map(f=>{if(typeof f=="string")return f;if(f.kind==="number")return b===void 0?"#":(g??=new Intl.NumberFormat(t,o)).format(b);if(!Object.hasOwn(n,f.name))return f.source;let y=n[f.name];if(f.kind==="value")return K(String(y));if(f.kind==="select"){let j=f.choices.get(String(y))??f.choices.get("other");return j?p(j):f.source}if(typeof y!="number"||!Number.isFinite(y))return f.source;let L=y-f.offset;if(!Number.isFinite(L))return f.source;let x=f.choices.get("="+y);if(x)return p(x,L);let D=f.kind==="plural"?u??=new Intl.PluralRules(t,o):c??=new Intl.PluralRules(t,{...o,type:"ordinal"}),k=f.choices.get(D.select(L))??f.choices.get("other");return k?p(k,L):f.source}).join("")}return p(e)}function U(){return {name:"icu",transform:(e,n,s,t,o)=>{if(!/[{']/.test(n))return n;try{return ie(new C(n).parse(),s,o??t)}catch(u){if(u instanceof v)return n;throw u}}}}function T(e){let n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return e.replace(/[&<>"'/]/g,s=>n[s])}function ae(e){let n=Array.from(e).filter(s=>s.charCodeAt(0)>32&&s.charCodeAt(0)!==127).join("").toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:")||n.startsWith("vbscript:")||n.startsWith("file:")?"#":T(e)}function ce(e,n){return e.replace(/\{\{([^}]+)\}\}/g,(s,t)=>{let o=t.split(":")[0].trim();if(!Object.prototype.hasOwnProperty.call(n,o))return s;let u=n[o];return u==null?"":String(u)})}function W(){return {name:"markdown",escapeValue:T,transform:(e,n,s,t)=>{let o=n,u=[],c=0;o=o.replace(/`(.*?)`/g,(g,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return u[c]=`<code>${T(p)}</code>`,c++,m}),o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(g,p,m)=>{let b=`__MARKDOWN_PLACEHOLDER_${c}__`,f=ae(ce(m,s||{})).replace(/[{}]/g,y=>y==="{"?"&#123;":"&#125;");return u[c]=`<a href="${f}">${T(p)}</a>`,c++,b}),o=o.replace(/\*\*(.*?)\*\*/g,(g,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return u[c]=`<strong>${T(p)}</strong>`,c++,m}),o=o.replace(/\*(.*?)\*/g,(g,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return u[c]=`<em>${T(p)}</em>`,c++,m}),o=T(o);for(let g=u.length-1;g>=0;g--)o=o.replace(`__MARKDOWN_PLACEHOLDER_${g}__`,()=>u[g]);return o}}}var be=W(),we=U();exports.createCache=V;exports.createI18n=ne;exports.deepMerge=M;exports.defaultPluralRules=ue;exports.getNestedValue=A;exports.getPluralForm=F;exports.guardBraces=K;exports.icuPlugin=we;exports.interpolate=S;exports.markdownPlugin=be;exports.releaseBraces=z;//# 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/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","hasCatalog","localeChain","candidate","availableLocales","currentLocale","fallbackLocale","messages","plugins","listeners","translationCache","revision","notify","listener","handleError","context","err","namedFormat","table","type","own","name","parts","part","currency","plugin","getMessage","localeMessages","resolveMessage","locales","lookupChain","forms","form","pluralMessage","message","translate","paramsCacheKey","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","chain","cut","encoded","InvalidPattern","MessageParser","pattern","token","number","literal","depth","pound","flush","legacy","start","kind","offset","choices","selector","option","intlLocale","numberOptions","cardinal","ordinal","numbers","render","selection","adjusted","exact","createICUPlugin","_key","escapeHtml","text","htmlEscapeMap","char","sanitizeHref","href","trimmed","resolveHrefParams","placeholder","createMarkdownPlugin","_locale","placeholders","placeholderIndex","_","url","brace","i","markdownPlugin","icuPlugin"],"mappings":"aAMO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EACAC,CAAAA,CACQ,CACR,GAAI,OAAOJ,CAAAA,EAAa,QAAA,CACtB,OAAO,MAAA,CAAOA,CAAQ,EAGxB,GAAI,CACF,OAAOA,CAAAA,CAAS,OAAA,CAAQ,kBAAA,CAAoB,CAACK,CAAAA,CAAOC,CAAAA,GAAQ,CAC1D,IAAMC,CAAAA,CAAcC,EAAmBF,CAAG,CAAA,CAC1C,OAAIC,CAAAA,GAAgB,KAAA,CAAA,CAAkBF,CAAAA,CAC/BD,CAAAA,CAASA,CAAAA,CAAOG,CAAW,EAAIA,CACxC,CAAC,CACH,CAAA,MAASE,CAAAA,CAAO,CACd,OAAI,OAAO,OAAA,CAAY,GAAA,EAAe,OAAA,CAAQ,GAAA,EAAK,WAAa,YAAA,EAC9D,OAAA,CAAQ,MAAM,sCAAA,CAAwCA,CAAK,EAEtDT,CACT,CAEA,SAASQ,CAAAA,CAAmBF,CAAAA,CAAiC,CAC3D,GAAI,CACF,GAAM,CAACI,CAAAA,CAAUC,CAAM,EAAIL,CAAAA,CACxB,IAAA,EAAK,CACL,KAAA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I,EAASA,CAAAA,CAAO,OAAA,CAAQ,gBAAA,CAAkB,CAACsI,CAAAA,CAAGZ,CAAAA,GAAS,CACrD,IAAMO,CAAAA,CAAc,0BAA0BI,CAAgB,CAAA,EAAA,CAAA,CAC9D,OAAAD,CAAAA,CAAaC,CAAgB,CAAA,CAAI,CAAA,QAAA,EAAWZ,CAAAA,CAAWC,CAAI,CAAC,CAAA,SAAA,CAAA,CAC5DW,CAAAA,EAAAA,CACOJ,CACT,CAAC,CAAA,CAGDjI,CAAAA,CAASA,EAAO,OAAA,CAAQ,YAAA,CAAc,CAACsI,CAAAA,CAAGZ,CAAAA,GAAS,CACjD,IAAMO,CAAAA,CAAc,CAAA,uBAAA,EAA0BI,CAAgB,CAAA,EAAA,CAAA,CAC9D,OAAAD,EAAaC,CAAgB,CAAA,CAAI,CAAA,IAAA,EAAOZ,CAAAA,CAAWC,CAAI,CAAC,QACxDW,CAAAA,EAAAA,CACOJ,CACT,CAAC,CAAA,CAGDjI,CAAAA,CAASyH,EAAWzH,CAAM,CAAA,CAK1B,IAAA,IAASyI,CAAAA,CAAIL,CAAAA,CAAa,MAAA,CAAS,EAAGK,CAAAA,EAAK,CAAA,CAAGA,IAC5CzI,CAAAA,CAASA,CAAAA,CAAO,QAAQ,CAAA,uBAAA,EAA0ByI,CAAC,CAAA,EAAA,CAAA,CAAM,IAAML,CAAAA,CAAaK,CAAC,CAAC,CAAA,CAGhF,OAAOzI,CACT,CACF,CACF,KClHa0I,EAAAA,CAA6BR,CAAAA,EAAqB,CAKlDS,EAAAA,CAAwBpB,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\n .trim()\n .split(':')\n .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(\n value,\n key.includes(':') ? key.split(':').slice(1).join(':') : undefined,\n locale\n );\n // Validate formatter returns a string\n if (typeof formatted !== 'string') {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(\n `[i18n] Formatter '${format}' must return a string, got ${typeof formatted}`\n );\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>(target: T, source: Partial<T>): 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 (key === '__proto__' || key === 'constructor' || key === 'prototype') {\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>(obj: Record<string, unknown>, path: string): 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 (\n current &&\n typeof current === 'object' &&\n Object.prototype.hasOwnProperty.call(current, key)\n ) {\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(\n Intl.PluralRules.supportedLocalesOf(tag).length > 0 ? tag : 'en'\n );\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 { createCache, deepMerge, getNestedValue, getPluralForm, interpolate } 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 (\n typeof config.messages !== 'object' ||\n Array.isArray(config.messages) ||\n config.messages === null\n ) {\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 const hasCatalog = (locale: LocaleCode): boolean =>\n localeChain(locale).some(candidate =>\n Object.prototype.hasOwnProperty.call(config.messages, candidate)\n );\n // Validate that the current locale (or a base language: en-US → en) exists in messages,\n // unless a fallback is provided or messages is empty\n if (hasMessages && !hasCatalog(config.locale) && !config.fallbackLocale) {\n const availableLocales = Object.keys(config.messages).join(', ');\n throw new Error(\n `[i18n] Locale '${config.locale}' not found in messages and no fallback locale provided. Available locales: ${availableLocales}`\n );\n }\n // Warn if current locale doesn't exist but fallback does\n if (!hasCatalog(config.locale) && config.fallbackLocale) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n const availableLocales = Object.keys(config.messages).join(', ');\n console.warn(\n `[i18n] Locale '${config.locale}' not found in messages, will use fallback locale '${config.fallbackLocale}'. Available locales: ${availableLocales}`\n );\n }\n }\n // Validate fallback locale if provided\n if (config.fallbackLocale && !hasCatalog(config.fallbackLocale)) {\n const availableLocales = Object.keys(config.messages).join(', ');\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(\n `[i18n] Fallback locale '${config.fallbackLocale}' not found in messages. Available locales: ${availableLocales}`\n );\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<\n string,\n (value: TranslationValue, format?: string, locale?: string) => string\n >();\n\n // Options of a named format. `formatNumber(v, 'percent')` passes the name; placeholders pass\n // the formatter too (`{{v:number}}` → 'number' → `default`, `{{v:number:percent}}` →\n // 'number:percent' → `percent`). A format literally named like that still wins.\n function namedFormat<T extends object>(\n table: Record<string, T> | undefined,\n format: string | undefined,\n type: string\n ): T | undefined {\n if (!table) return undefined;\n const own = (name: string) =>\n Object.prototype.hasOwnProperty.call(table, name) ? table[name] : undefined;\n if (format && own(format)) return own(format);\n const parts = (format || '').split(':').map(part => part.trim());\n if (parts[0] === type) parts.shift();\n return own(parts.join(':') || 'default');\n }\n\n // Built-in formatters\n formatters.set('number', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const options = namedFormat(config.formats?.number, format, 'number') || {};\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 = namedFormat(config.formats?.date, format, 'date') || {};\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 // BCP 47 lookup: the locale, its base languages (zh-Hant-TW → zh-Hant → zh), then the\n // fallback locale and its base languages.\n const locales = lookupChain(locale);\n const count =\n 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 lookupChain(locale: LocaleCode): LocaleCode[] {\n return [\n ...new Set([...localeChain(locale), ...(fallbackLocale ? localeChain(fallbackLocale) : [])]),\n ];\n }\n\n function translate(\n key: string,\n params?: TranslationParams,\n locale: LocaleCode = currentLocale\n ): string {\n try {\n // Params that cannot be encoded unambiguously are not cached.\n const paramKey = params ? paramsCacheKey(params) : '';\n const cacheKey = paramKey === undefined ? undefined : `${locale}:${key}:${paramKey}`;\n const cached = cacheKey === undefined ? undefined : translationCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const resolved = resolveMessage(key, params, locale);\n if (!resolved) {\n if (\n config.warnOnMissingTranslations &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'production'\n ) {\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 if (cacheKey !== undefined) 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 neither the locale nor its base language exists in messages\n if (\n !localeChain(locale).some(candidate =>\n Object.prototype.hasOwnProperty.call(messages, candidate)\n )\n ) {\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 (lookupChain(currentLocale).includes(locale)) {\n notify();\n }\n } catch (error) {\n handleError(error, 'Error adding messages');\n throw error;\n }\n }\n\n function hasTranslation(\n key: TranslationKey<TMessages>,\n locale?: LocaleCode,\n options?: { exact?: boolean }\n ): boolean {\n const checkLocale = locale || currentLocale;\n // Same lookup as t(): the locale, its base languages, then the fallback locale chain.\n // `exact: true` checks only the given (or active) locale's own catalog.\n const locales = options?.exact ? [checkLocale] : lookupChain(checkLocale);\n return locales.some(candidate => getMessage(String(key), candidate) !== 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(\n `[i18n] Plugin '${plugin.name}' already registered. Replacing existing plugin.`\n );\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 // Plugins change the visible text; UI bindings re-render on notifications.\n notify();\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 notify();\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(\n '[i18n] Number formatter not available. Please add a plugin that provides number formatting.'\n );\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(\n '[i18n] Date formatter not available. Please add a plugin that provides date formatting.'\n );\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\n/**\n * `locale` followed by its truncations (RFC 4647 lookup): `zh-Hant-TW` → `zh-Hant` → `zh`.\n * A trailing single-letter subtag (extension or private-use singleton) is dropped too.\n */\nfunction localeChain(locale: LocaleCode): LocaleCode[] {\n const chain = [locale];\n let current = locale;\n for (;;) {\n let cut = Math.max(current.lastIndexOf('-'), current.lastIndexOf('_'));\n if (cut <= 0) break;\n current = current.slice(0, cut);\n cut = Math.max(current.lastIndexOf('-'), current.lastIndexOf('_'));\n if (cut > 0 && current.length - cut - 1 === 1) current = current.slice(0, cut);\n chain.push(current);\n }\n return chain;\n}\n\n/**\n * Cache key for translation params: every value that renders differently gets a different key\n * (`NaN`, `Infinity`, `-0` and `null` all serialize to the same JSON). Returns undefined for\n * values without a faithful encoding (objects, bigint, ...), which are then not cached.\n */\nfunction paramsCacheKey(params: TranslationParams): string | undefined {\n const parts: string[] = [];\n for (const name of Object.keys(params).sort()) {\n const value: unknown = params[name];\n let encoded: string;\n if (typeof value === 'string') encoded = JSON.stringify(value);\n else if (typeof value === 'number') encoded = Object.is(value, -0) ? 'n-0' : `n${value}`;\n else if (typeof value === 'boolean' || value === null || value === undefined)\n encoded = String(value);\n else if (value instanceof Date) encoded = `d${value.getTime()}`;\n else return undefined;\n parts.push(`${JSON.stringify(name)}=${encoded}`);\n }\n return parts.join(',');\n}\n","import type { I18nPlugin, TranslationParams } from '../types';\n\ntype ChoiceKind = 'plural' | 'select' | 'selectordinal';\ntype Part =\n | string\n | { kind: 'value'; name: string; source: string }\n | { kind: 'number' }\n | {\n kind: ChoiceKind;\n name: string;\n source: string;\n choices: Map<string, Part[]>;\n offset: number;\n };\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 (\n 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))\n 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 =\n 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\n .map(part => {\n if (typeof part === 'string') return part;\n if (part.kind === 'number') {\n return pound === undefined\n ? '#'\n : (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 =\n 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 })\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, TranslationParams } 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 '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '/': '&#x2F;',\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 // Browsers ignore leading controls/spaces and tabs/newlines anywhere in a URL\n // (\"java\\tscript:\" is \"javascript:\"), so remove them before checking the scheme.\n const trimmed = Array.from(href)\n .filter(char => char.charCodeAt(0) > 0x20 && char.charCodeAt(0) !== 0x7f)\n .join('')\n .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 * Inserts `{{name}}` parameters into a link URL so the complete URL is checked. The raw value\n * is used (no formatter); placeholders without a parameter are kept.\n */\nfunction resolveHrefParams(href: string, params: TranslationParams): string {\n return href.replace(/\\{\\{([^}]+)\\}\\}/g, (match, placeholder: string) => {\n const name = placeholder.split(':')[0].trim();\n if (!Object.prototype.hasOwnProperty.call(params, name)) return match;\n const value = params[name];\n return value === null || value === undefined ? '' : String(value);\n });\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 // `code` -> <code>text</code>. Code spans go first: their content is literal (no\n // emphasis or links inside), and bold/italic/link text may contain them.\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 // [text](url) -> <a href=\"url\">text</a>\n result = result.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, (_, text, href) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n // Parameters are inserted before the scheme check (a `{{url}}` parameter could be a\n // javascript: URL); braces are encoded so interpolation cannot change the URL later.\n const url = sanitizeHref(resolveHrefParams(href, params || {})).replace(/[{}]/g, brace =>\n brace === '{' ? '&#123;' : '&#125;'\n );\n placeholders[placeholderIndex] = `<a href=\"${url}\">${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 // Escape any remaining text that wasn't part of markdown\n result = escapeHtml(result);\n\n // Restore placeholders, newest first: an outer construct (`**[a](b)**`) holds the\n // placeholders created before it. A replacer function keeps `$&`, `$'` and `$$` in the\n // text literal (a replacement string would expand them).\n for (let i = placeholders.length - 1; i >= 0; i--) {\n result = result.replace(`__MARKDOWN_PLACEHOLDER_${i}__`, () => placeholders[i]);\n }\n\n return result;\n },\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"]}
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","guardBraces","releaseBraces","text","createI18n","config","hasMessages","hasCatalog","localeChain","candidate","availableLocales","currentLocale","fallbackLocale","messages","plugins","listeners","translationCache","revision","notify","listener","handleError","context","err","namedFormat","table","type","own","name","parts","part","currency","plugin","getMessage","localeMessages","resolveMessage","locales","lookupChain","forms","form","pluralMessage","message","translate","paramsCacheKey","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","sign","i","unit","secondsInUnit","perNextUnit","amount","chain","cut","encoded","InvalidPattern","MessageParser","pattern","token","number","literal","depth","pound","flush","legacy","start","kind","offset","choices","selector","option","intlLocale","numberOptions","cardinal","ordinal","numbers","render","selection","adjusted","exact","createICUPlugin","_key","escapeHtml","htmlEscapeMap","char","sanitizeHref","href","trimmed","resolveHrefParams","placeholder","createMarkdownPlugin","_locale","placeholders","placeholderIndex","_","url","brace","markdownPlugin","icuPlugin"],"mappings":"aAMO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EACAC,CAAAA,CACQ,CACR,GAAI,OAAOJ,CAAAA,EAAa,QAAA,CACtB,OAAO,MAAA,CAAOA,CAAQ,EAGxB,GAAI,CACF,OAAOA,CAAAA,CAAS,OAAA,CAAQ,kBAAA,CAAoB,CAACK,CAAAA,CAAOC,CAAAA,GAAQ,CAC1D,IAAMC,CAAAA,CAAcC,EAAmBF,CAAG,CAAA,CAC1C,OAAIC,CAAAA,GAAgB,KAAA,CAAA,CAAkBF,CAAAA,CAC/BD,CAAAA,CAASA,CAAAA,CAAOG,CAAW,EAAIA,CACxC,CAAC,CACH,CAAA,MAASE,CAAAA,CAAO,CACd,OAAI,OAAO,OAAA,CAAY,GAAA,EAAe,OAAA,CAAQ,GAAA,EAAK,QAAA,GAAa,cAC9D,OAAA,CAAQ,KAAA,CAAM,uCAAwCA,CAAK,CAAA,CAEtDT,CACT,CAEA,SAASQ,CAAAA,CAAmBF,CAAAA,CAAiC,CAC3D,GAAI,CACF,GAAM,CAACI,CAAAA,CAAUC,CAAM,CAAA,CAAIL,CAAAA,CACxB,MAAK,CACL,KAAA,CAAM,GAAG,CAAA,CACT,GAAA,CAAKM,CAAAA,EAAcA,EAAE,IAAA,EAAM,EAE9B,GAAI,CAAC,OAAO,SAAA,CAAU,cAAA,CAAe,IAAA,CAAKX,CAAAA,CAAQS,CAAQ,CAAA,CAAG,CACvD,OAAO,OAAA,CAAY,GAAA,EAAe,OAAA,CAAQ,GAAA,EAAK,QAAA,GAAa,cAC9D,OAAA,CAAQ,IAAA,CAAK,CAAA,sCAAA,EAAyCA,CAAQ,CAAA,CAAE,CAAA,CAElE,MACF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AAA,CAAc,CAAC4I,CAAAA,CAAGpH,CAAAA,GAAS,CACjD,IAAM+G,CAAAA,CAAc,0BAA0BI,CAAgB,CAAA,EAAA,CAAA,CAC9D,OAAAD,CAAAA,CAAaC,CAAgB,CAAA,CAAI,CAAA,IAAA,EAAOX,CAAAA,CAAWxG,CAAI,CAAC,CAAA,KAAA,CAAA,CACxDmH,CAAAA,EAAAA,CACOJ,CACT,CAAC,CAAA,CAGDvI,CAAAA,CAASgI,EAAWhI,CAAM,CAAA,CAK1B,IAAA,IAAS6F,CAAAA,CAAI6C,CAAAA,CAAa,MAAA,CAAS,EAAG7C,CAAAA,EAAK,CAAA,CAAGA,IAC5C7F,CAAAA,CAASA,CAAAA,CAAO,QAAQ,CAAA,uBAAA,EAA0B6F,CAAC,CAAA,EAAA,CAAA,CAAM,IAAM6C,CAAAA,CAAa7C,CAAC,CAAC,CAAA,CAGhF,OAAO7F,CACT,CACF,CACF,KClHa+I,EAAAA,CAA6BP,CAAAA,EAAqB,CAKlDQ,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\n .trim()\n .split(':')\n .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(\n value,\n key.includes(':') ? key.split(':').slice(1).join(':') : undefined,\n locale\n );\n // Validate formatter returns a string\n if (typeof formatted !== 'string') {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(\n `[i18n] Formatter '${format}' must return a string, got ${typeof formatted}`\n );\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>(target: T, source: Partial<T>): 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 (key === '__proto__' || key === 'constructor' || key === 'prototype') {\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>(obj: Record<string, unknown>, path: string): 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 (\n current &&\n typeof current === 'object' &&\n Object.prototype.hasOwnProperty.call(current, key)\n ) {\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(\n Intl.PluralRules.supportedLocalesOf(tag).length > 0 ? tag : 'en'\n );\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\n/**\n * Marks the braces of a value a plugin inserts into a message, so the `{{name}}`\n * interpolation that runs afterwards never treats text from a parameter value as a\n * placeholder. {@link releaseBraces} removes the marks once interpolation is done.\n * @internal\n */\nexport function guardBraces(value: string): string {\n return value.replace(/\\{/g, '{\\uE000');\n}\n\n/** Removes the marks {@link guardBraces} added. @internal */\nexport function releaseBraces(text: string): string {\n return text.replace(/\\{\\uE000/g, '{');\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 releaseBraces,\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 (\n typeof config.messages !== 'object' ||\n Array.isArray(config.messages) ||\n config.messages === null\n ) {\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 const hasCatalog = (locale: LocaleCode): boolean =>\n localeChain(locale).some(candidate =>\n Object.prototype.hasOwnProperty.call(config.messages, candidate)\n );\n // Validate that the current locale (or a base language: en-US → en) exists in messages,\n // unless a fallback is provided or messages is empty\n if (hasMessages && !hasCatalog(config.locale) && !config.fallbackLocale) {\n const availableLocales = Object.keys(config.messages).join(', ');\n throw new Error(\n `[i18n] Locale '${config.locale}' not found in messages and no fallback locale provided. Available locales: ${availableLocales}`\n );\n }\n // Warn if current locale doesn't exist but fallback does\n if (!hasCatalog(config.locale) && config.fallbackLocale) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n const availableLocales = Object.keys(config.messages).join(', ');\n console.warn(\n `[i18n] Locale '${config.locale}' not found in messages, will use fallback locale '${config.fallbackLocale}'. Available locales: ${availableLocales}`\n );\n }\n }\n // Validate fallback locale if provided\n if (config.fallbackLocale && !hasCatalog(config.fallbackLocale)) {\n const availableLocales = Object.keys(config.messages).join(', ');\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(\n `[i18n] Fallback locale '${config.fallbackLocale}' not found in messages. Available locales: ${availableLocales}`\n );\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<\n string,\n (value: TranslationValue, format?: string, locale?: string) => string\n >();\n\n // Options of a named format. `formatNumber(v, 'percent')` passes the name; placeholders pass\n // the formatter too (`{{v:number}}` → 'number' → `default`, `{{v:number:percent}}` →\n // 'number:percent' → `percent`). A format literally named like that still wins.\n function namedFormat<T extends object>(\n table: Record<string, T> | undefined,\n format: string | undefined,\n type: string\n ): T | undefined {\n if (!table) return undefined;\n const own = (name: string) =>\n Object.prototype.hasOwnProperty.call(table, name) ? table[name] : undefined;\n if (format && own(format)) return own(format);\n const parts = (format || '').split(':').map(part => part.trim());\n if (parts[0] === type) parts.shift();\n return own(parts.join(':') || 'default');\n }\n\n // Built-in formatters\n formatters.set('number', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const options = namedFormat(config.formats?.number, format, 'number') || {};\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 = namedFormat(config.formats?.date, format, 'date') || {};\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 // BCP 47 lookup: the locale, its base languages (zh-Hant-TW → zh-Hant → zh), then the\n // fallback locale and its base languages.\n const locales = lookupChain(locale);\n const count =\n 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 lookupChain(locale: LocaleCode): LocaleCode[] {\n return [\n ...new Set([...localeChain(locale), ...(fallbackLocale ? localeChain(fallbackLocale) : [])]),\n ];\n }\n\n function translate(\n key: string,\n params?: TranslationParams,\n locale: LocaleCode = currentLocale\n ): string {\n try {\n // Params that cannot be encoded unambiguously are not cached.\n const paramKey = params ? paramsCacheKey(params) : '';\n const cacheKey = paramKey === undefined ? undefined : `${locale}:${key}:${paramKey}`;\n const cached = cacheKey === undefined ? undefined : translationCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const resolved = resolveMessage(key, params, locale);\n if (!resolved) {\n if (\n config.warnOnMissingTranslations &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'production'\n ) {\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 result = releaseBraces(result);\n\n if (cacheKey !== undefined) 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 neither the locale nor its base language exists in messages\n if (\n !localeChain(locale).some(candidate =>\n Object.prototype.hasOwnProperty.call(messages, candidate)\n )\n ) {\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 (lookupChain(currentLocale).includes(locale)) {\n notify();\n }\n } catch (error) {\n handleError(error, 'Error adding messages');\n throw error;\n }\n }\n\n function hasTranslation(\n key: TranslationKey<TMessages>,\n locale?: LocaleCode,\n options?: { exact?: boolean }\n ): boolean {\n const checkLocale = locale || currentLocale;\n // Same lookup as t(): the locale, its base languages, then the fallback locale chain.\n // `exact: true` checks only the given (or active) locale's own catalog.\n const locales = options?.exact ? [checkLocale] : lookupChain(checkLocale);\n return locales.some(candidate => getMessage(String(key), candidate) !== 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(\n `[i18n] Plugin '${plugin.name}' already registered. Replacing existing plugin.`\n );\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 // Plugins change the visible text; UI bindings re-render on notifications.\n notify();\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 notify();\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(\n '[i18n] Number formatter not available. Please add a plugin that provides number formatting.'\n );\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(\n '[i18n] Date formatter not available. Please add a plugin that provides date formatting.'\n );\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 // Truncate and round the magnitude so a date d before the base reads like one d after it.\n const diffInSeconds = Math.trunc((value.getTime() - baseDate.getTime()) / 1000);\n const rtf = new Intl.RelativeTimeFormat(currentLocale, { numeric: 'auto' });\n\n // [unit, seconds in it, how many of it make the next larger unit (weeks do not add up to a month)]\n const units: Array<[Intl.RelativeTimeFormatUnit, number, number?]> = [\n ['year', 60 * 60 * 24 * 365],\n ['month', 60 * 60 * 24 * 30, 12],\n ['week', 60 * 60 * 24 * 7],\n ['day', 60 * 60 * 24, 7],\n ['hour', 60 * 60, 24],\n ['minute', 60, 60],\n ['second', 1],\n ];\n\n const sign = diffInSeconds < 0 ? -1 : 1;\n for (let i = 0; i < units.length; i++) {\n const [unit, secondsInUnit, perNextUnit] = units[i]!;\n if (Math.abs(diffInSeconds) >= secondsInUnit) {\n const amount = Math.round(Math.abs(diffInSeconds) / secondsInUnit);\n // Rounding up to a whole larger unit reads as that unit: \"in 1 hour\", not \"in 60 minutes\".\n if (perNextUnit !== undefined && amount >= perNextUnit) {\n return rtf.format(sign, units[i - 1]![0]);\n }\n return rtf.format(sign * amount, 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\n/**\n * `locale` followed by its truncations (RFC 4647 lookup): `zh-Hant-TW` → `zh-Hant` → `zh`.\n * A trailing single-letter subtag (extension or private-use singleton) is dropped too.\n */\nfunction localeChain(locale: LocaleCode): LocaleCode[] {\n const chain = [locale];\n let current = locale;\n for (;;) {\n let cut = Math.max(current.lastIndexOf('-'), current.lastIndexOf('_'));\n if (cut <= 0) break;\n current = current.slice(0, cut);\n cut = Math.max(current.lastIndexOf('-'), current.lastIndexOf('_'));\n if (cut > 0 && current.length - cut - 1 === 1) current = current.slice(0, cut);\n chain.push(current);\n }\n return chain;\n}\n\n/**\n * Cache key for translation params: every value that renders differently gets a different key\n * (`NaN`, `Infinity`, `-0` and `null` all serialize to the same JSON). Returns undefined for\n * values without a faithful encoding (objects, bigint, ...), which are then not cached.\n */\nfunction paramsCacheKey(params: TranslationParams): string | undefined {\n const parts: string[] = [];\n for (const name of Object.keys(params).sort()) {\n const value: unknown = params[name];\n let encoded: string;\n if (typeof value === 'string') encoded = JSON.stringify(value);\n else if (typeof value === 'number') encoded = Object.is(value, -0) ? 'n-0' : `n${value}`;\n else if (typeof value === 'boolean' || value === null || value === undefined)\n encoded = String(value);\n else if (value instanceof Date) encoded = `d${value.getTime()}`;\n else return undefined;\n parts.push(`${JSON.stringify(name)}=${encoded}`);\n }\n return parts.join(',');\n}\n","import type { I18nPlugin, TranslationParams } from '../types';\nimport { guardBraces } from '../utils';\n\ntype ChoiceKind = 'plural' | 'select' | 'selectordinal';\ntype Part =\n | string\n | { kind: 'value'; name: string; source: string }\n | { kind: 'number' }\n | {\n kind: ChoiceKind;\n name: string;\n source: string;\n choices: Map<string, Part[]>;\n offset: number;\n };\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 (\n 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))\n 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 =\n 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\n .map(part => {\n if (typeof part === 'string') return part;\n if (part.kind === 'number') {\n return pound === undefined\n ? '#'\n : (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 // Guarded: interpolation must not read placeholders inside a parameter value\n if (part.kind === 'value') return guardBraces(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 =\n 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 })\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, TranslationParams } 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 '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '/': '&#x2F;',\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 // Browsers ignore leading controls/spaces and tabs/newlines anywhere in a URL\n // (\"java\\tscript:\" is \"javascript:\"), so remove them before checking the scheme.\n const trimmed = Array.from(href)\n .filter(char => char.charCodeAt(0) > 0x20 && char.charCodeAt(0) !== 0x7f)\n .join('')\n .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 * Inserts `{{name}}` parameters into a link URL so the complete URL is checked. The raw value\n * is used (no formatter); placeholders without a parameter are kept.\n */\nfunction resolveHrefParams(href: string, params: TranslationParams): string {\n return href.replace(/\\{\\{([^}]+)\\}\\}/g, (match, placeholder: string) => {\n const name = placeholder.split(':')[0].trim();\n if (!Object.prototype.hasOwnProperty.call(params, name)) return match;\n const value = params[name];\n return value === null || value === undefined ? '' : String(value);\n });\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 // `code` -> <code>text</code>. Code spans go first: their content is literal (no\n // emphasis or links inside), and bold/italic/link text may contain them.\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 // [text](url) -> <a href=\"url\">text</a>\n result = result.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, (_, text, href) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n // Parameters are inserted before the scheme check (a `{{url}}` parameter could be a\n // javascript: URL); braces are encoded so interpolation cannot change the URL later.\n const url = sanitizeHref(resolveHrefParams(href, params || {})).replace(/[{}]/g, brace =>\n brace === '{' ? '&#123;' : '&#125;'\n );\n placeholders[placeholderIndex] = `<a href=\"${url}\">${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 // Escape any remaining text that wasn't part of markdown\n result = escapeHtml(result);\n\n // Restore placeholders, newest first: an outer construct (`**[a](b)**`) holds the\n // placeholders created before it. A replacer function keeps `$&`, `$'` and `$$` in the\n // text literal (a replacement string would expand them).\n for (let i = placeholders.length - 1; i >= 0; i--) {\n result = result.replace(`__MARKDOWN_PLACEHOLDER_${i}__`, () => placeholders[i]);\n }\n\n return result;\n },\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 S(r,n,o,t,s){if(typeof r!="string")return String(r);try{return r.replace(/\{\{([^}]+)\}\}/g,(c,g)=>{let d=l(g);return d===void 0?c:s?s(d):d})}catch(c){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Template interpolation error:",c),r}function l(c){try{let[g,d]=c.trim().split(":").map(b=>b.trim());if(!Object.prototype.hasOwnProperty.call(n,g)){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation parameter: ${g}`);return}let m=n[g];if(d&&o?.has(d))try{let b=o.get(d);if(!b)return String(m);let f=b(m,c.includes(":")?c.split(":").slice(1).join(":"):void 0,t);return typeof f!="string"?(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter '${d}' must return a string, got ${typeof f}`),String(m)):f}catch(b){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter error for ${d}:`,b),String(m)}return m==null?"":m instanceof Date?m.toLocaleDateString(t||"en-US",{year:"numeric",month:"2-digit",day:"2-digit"}):String(m)}catch(g){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Parameter interpolation error:",g);return}}}function D(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 t in n){if(t==="__proto__"||t==="constructor"||t==="prototype"){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Blocked attempt to set dangerous property: ${t}`);continue}if(!Object.prototype.hasOwnProperty.call(n,t))continue;let s=n[t];if(s!==void 0)if(typeof s=="object"&&s!==null&&!Array.isArray(s)&&!(s instanceof Date)){let l=o[t];o[t]=D(l&&typeof l=="object"?l:{},s);}else o[t]=s;}return o}catch(o){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] DeepMerge error:",o),r}}function A(r,n){if(!(!r||typeof r!="object"||!n||typeof n!="string"))try{let o=n.split("."),t=r;for(let s of o)if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,s))t=t[s];else return;return t}catch(o){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] getNestedValue error:",o);return}}function V(r){let n=new Map,o=r?.maxSize??1e3;return {get:t=>{let s=n.get(t);return s!==void 0&&(n.delete(t),n.set(t,s)),s},set:(t,s)=>{if(n.has(t))n.delete(t);else if(n.size>=o){let l=n.keys().next().value;l!==void 0&&n.delete(l);}n.set(t,s);},clear:()=>n.clear(),size:()=>n.size}}var ae={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"},R=new Map;function ee(r){let n=R.get(r);if(!n){try{let o=r.replace(/_/g,"-");n=new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(o).length>0?o:"en");}catch{n=new Intl.PluralRules("en");}R.set(r,n);}return n}function F(r,n,o){if(o){let t=r.split(/[-_]/)[0],s=Object.prototype.hasOwnProperty.call(o,r)?o[r]:Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0;if(typeof s=="function")return s(n)}return ee(r).select(n)}function re(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 n=Object.keys(r.messages).length>0;n||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Messages object is empty - all translations will return keys");let o=e=>N(e).some(i=>Object.prototype.hasOwnProperty.call(r.messages,i));if(n&&!o(r.locale)&&!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(!o(r.locale)&&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&&!o(r.fallbackLocale)){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 t=r.locale,s=r.fallbackLocale,l=structuredClone(r.messages),c=[...r.plugins||[]],g=new Set,d=V(),m=0,b=()=>{m++,g.forEach(e=>{try{e(t);}catch(i){f(i,"Locale change listener");}});},f=(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);},y=new Map;function E(e,i,a){if(!e)return;let u=h=>Object.prototype.hasOwnProperty.call(e,h)?e[h]:void 0;if(i&&u(i))return u(i);let p=(i||"").split(":").map(h=>h.trim());return p[0]===a&&p.shift(),u(p.join(":")||"default")}y.set("number",(e,i,a)=>{if(typeof e!="number")return String(e);let u=E(r.formats?.number,i,"number")||{};return new Intl.NumberFormat(a||t,u).format(e)}),y.set("date",(e,i,a)=>{if(!(e instanceof Date))return String(e);let u=E(r.formats?.date,i,"date")||{};return new Intl.DateTimeFormat(a||t,u).format(e)}),y.set("currency",(e,i,a)=>{if(typeof e!="number")return String(e);let u=(i||"currency:USD").split(":"),p=u.length>1&&u[1]||"USD";try{return new Intl.NumberFormat(a||t,{style:"currency",currency:p}).format(e)}catch(h){return f(h,`Currency formatter error for currency '${p}'`),`${p} ${e}`}}),c.forEach(e=>{e.format&&y.set(e.name,(i,a,u)=>e.format(i,a??"",u??t));});function T(e,i){if(!Object.prototype.hasOwnProperty.call(l,i))return;let a=l[i];if(!a||typeof a!="object")return;let u=Object.prototype.hasOwnProperty.call(a,e)?a[e]:A(a,e);return typeof u=="string"?u:void 0}function j(e,i,a){let u=k(a),p=i&&Object.prototype.hasOwnProperty.call(i,"count")?i.count:void 0;for(let h of u){if(typeof p=="number"){let x=new Set;p===0&&x.add("zero"),x.add(F(h,p,r.pluralizationRules)),x.add("other");for(let $ of x){let w=T(`${e}.${$}`,h);if(w)return {message:w,messageLocale:h}}}let v=T(e,h);if(v)return {message:v,messageLocale:h}}}function k(e){return [...new Set([...N(e),...s?N(s):[]])]}function I(e,i,a=t){try{let u=i?te(i):"",p=u===void 0?void 0:`${a}:${e}:${u}`,h=p===void 0?void 0:d.get(p);if(h!==void 0)return h;let v=j(e,i,a);if(!v)return r.warnOnMissingTranslations&&typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation: ${e} for locale: ${a}`),e;let{message:x,messageLocale:$}=v,w=x;for(let O of c)if(O.transform)try{let L=O.transform(e,w,i||{},a,$);if(typeof L!="string"){f(new Error(`Plugin transform must return a string, got ${typeof L}`),`Plugin ${O.name} transform validation`);continue}w=L;}catch(L){f(L,`Plugin ${O.name} transform`);}let M=c.filter(O=>typeof O.escapeValue=="function");return w=S(w,i||{},y,t,M.length>0?O=>M.reduce((L,Z)=>Z.escapeValue(L),O):void 0),p!==void 0&&d.set(p,w),w}catch(u){return f(u,`Translation error for key ${e}`),e}}let W=(e,i)=>I(String(e),i);function H(e){if(!e||typeof e!="string")throw new Error("[i18n] Invalid locale provided");N(e).some(i=>Object.prototype.hasOwnProperty.call(l,i))||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Locale '${e}' not found in messages. Available locales: ${Object.keys(l).join(", ")}`),e!==t&&(t=e,d.clear(),b());}function U(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{l[e]||(l[e]={});let a=i;for(let u of c)if(u.beforeLoad)try{let p=u.beforeLoad(e,a);if(!p||typeof p!="object"||Array.isArray(p)){f(new Error(`Plugin beforeLoad must return an object, got ${typeof p}`),`Plugin ${u.name} beforeLoad validation`);continue}a=p;}catch(p){f(p,`Plugin ${u.name} beforeLoad`);}l[e]=D(l[e],a);for(let u of c)if(u.afterLoad)try{u.afterLoad(e,l[e]);}catch(p){f(p,`Plugin ${u.name} afterLoad`);}d.clear(),k(t).includes(e)&&b();}catch(a){throw f(a,"Error adding messages"),a}}function q(e,i,a){let u=i||t;return (a?.exact?[u]:k(u)).some(h=>T(String(e),h)!==void 0)}function J(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&&y.set(e.name,(a,u,p)=>e.format(a,u??"",p??t)),d.clear(),b();}function B(e){let i=c.findIndex(a=>a.name===e);i!==-1&&(c.splice(i,1),y.delete(e),d.clear(),b());}function G(e){return g.add(e),()=>g.delete(e)}function Q(e,i){let a=y.get("number");if(!a)throw new Error("[i18n] Number formatter not available. Please add a plugin that provides number formatting.");return a(e,i,t)}function X(e,i){let a=y.get("date");if(!a)throw new Error("[i18n] Date formatter not available. Please add a plugin that provides date formatting.");return a(e,i,t)}function Y(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),u=new Intl.RelativeTimeFormat(t,{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[h,v]of p)if(Math.abs(a)>=v)return u.format(Math.round(a/v),h);return u.format(0,"second")}return {get locale(){return t},get fallbackLocale(){return s},get messages(){return l},get revision(){return m},t:W,setLocale:H,getLocale:()=>t,hasTranslation:q,addMessages:U,addPlugin:J,removePlugin:B,subscribe:G,formatNumber:Q,formatDate:X,formatRelativeTime:Y}}function N(r){let n=[r],o=r;for(;;){let t=Math.max(o.lastIndexOf("-"),o.lastIndexOf("_"));if(t<=0)break;o=o.slice(0,t),t=Math.max(o.lastIndexOf("-"),o.lastIndexOf("_")),t>0&&o.length-t-1===1&&(o=o.slice(0,t)),n.push(o);}return n}function te(r){let n=[];for(let o of Object.keys(r).sort()){let t=r[o],s;if(typeof t=="string")s=JSON.stringify(t);else if(typeof t=="number")s=Object.is(t,-0)?"n-0":`n${t}`;else if(typeof t=="boolean"||t===null||t===void 0)s=String(t);else if(t instanceof Date)s=`d${t.getTime()}`;else return;n.push(`${JSON.stringify(o)}=${s}`);}return n.join(",")}var P=class extends Error{},C=class{constructor(n){this.source=n;}cursor=0;parse(){return this.message(0,false).parts}take(n){n.lastIndex=this.cursor;let o=n.exec(this.source)?.[0];return o!==void 0&&(this.cursor+=o.length),o}expect(n){let o=this.take(n);if(o===void 0)throw new P;return o}space(){this.take(/\s+/y);}number(){let n=Number(this.expect(/[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/y));if(!Number.isFinite(n))throw new P;return n}quote(){let n="";for(this.cursor++;this.cursor<this.source.length;){let o=this.source.charAt(this.cursor++);if(o==="'"&&!this.take(/'/y))break;n+=o;}return n}message(n,o){if(n>64)throw new P;let t=[],s="";function l(){s&&t.push(s),s="";}for(;this.cursor<this.source.length;){let c=this.source.charAt(this.cursor);if(c==="}"){if(n===0)throw new P;return this.cursor++,l(),{parts:t,closed:true}}if(c==="{"){let g=this.take(/\{\{[^{}]*\}\}/y);g!==void 0?s+=g:(l(),t.push(this.argument(n)));}else c==="'"&&this.take(/''/y)?s+="'":c==="'"&&(["{","}"].includes(this.source.charAt(this.cursor+1))||o&&this.source.charAt(this.cursor+1)==="#")?s+=this.quote():(this.cursor++,c==="#"&&o?(l(),t.push({kind:"number"})):s+=c);}return l(),{parts:t,closed:false}}argument(n){let o=this.cursor++;this.space();let t=this.expect(/[\p{ID_Continue}]+/uy);if(this.space(),this.take(/\}/y))return {kind:"value",name:t,source:this.source.slice(o,this.cursor)};this.expect(/,/y),this.space();let s=this.expect(/selectordinal|plural|select/y);this.space(),this.expect(/,/y),this.space();let l=s!=="select"&&this.take(/offset\s*:\s*/y)?this.number():0;this.space();let c=new Map;for(;!this.take(/\}/y);){let g=s!=="select"&&this.take(/=/y)?"="+this.number():this.expect(/[\p{ID_Continue}]+/uy);this.space(),this.expect(/\{/y);let d=this.message(n+1,s!=="select");if(!d.closed)throw new P;c.has(g)||c.set(g,d.parts),this.space();}if(!c.has("other"))throw new P;return {kind:s,name:t,choices:c,offset:l,source:this.source.slice(o,this.cursor)}}};function ne(r){try{return Intl.getCanonicalLocales(r.replace(/_/g,"-"))[0]??"en"}catch{return "en"}}function oe(r,n,o){let t=ne(o),s={maximumSignificantDigits:21},l,c,g;function d(m,b){return m.map(f=>{if(typeof f=="string")return f;if(f.kind==="number")return b===void 0?"#":(g??=new Intl.NumberFormat(t,s)).format(b);if(!Object.hasOwn(n,f.name))return f.source;let y=n[f.name];if(f.kind==="value")return String(y);if(f.kind==="select"){let I=f.choices.get(String(y))??f.choices.get("other");return I?d(I):f.source}if(typeof y!="number"||!Number.isFinite(y))return f.source;let E=y-f.offset;if(!Number.isFinite(E))return f.source;let T=f.choices.get("="+y);if(T)return d(T,E);let j=f.kind==="plural"?l??=new Intl.PluralRules(t,s):c??=new Intl.PluralRules(t,{...s,type:"ordinal"}),k=f.choices.get(j.select(E))??f.choices.get("other");return k?d(k,E):f.source}).join("")}return d(r)}function K(){return {name:"icu",transform:(r,n,o,t,s)=>{if(!/[{']/.test(n))return n;try{return oe(new C(n).parse(),o,s??t)}catch(l){if(l instanceof P)return n;throw l}}}}function _(r){let n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return r.replace(/[&<>"'/]/g,o=>n[o])}function se(r){let n=Array.from(r).filter(o=>o.charCodeAt(0)>32&&o.charCodeAt(0)!==127).join("").toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:")||n.startsWith("vbscript:")||n.startsWith("file:")?"#":_(r)}function ie(r,n){return r.replace(/\{\{([^}]+)\}\}/g,(o,t)=>{let s=t.split(":")[0].trim();if(!Object.prototype.hasOwnProperty.call(n,s))return o;let l=n[s];return l==null?"":String(l)})}function z(){return {name:"markdown",escapeValue:_,transform:(r,n,o,t)=>{let s=n,l=[],c=0;s=s.replace(/`(.*?)`/g,(g,d)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return l[c]=`<code>${_(d)}</code>`,c++,m}),s=s.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(g,d,m)=>{let b=`__MARKDOWN_PLACEHOLDER_${c}__`,f=se(ie(m,o||{})).replace(/[{}]/g,y=>y==="{"?"&#123;":"&#125;");return l[c]=`<a href="${f}">${_(d)}</a>`,c++,b}),s=s.replace(/\*\*(.*?)\*\*/g,(g,d)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return l[c]=`<strong>${_(d)}</strong>`,c++,m}),s=s.replace(/\*(.*?)\*/g,(g,d)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return l[c]=`<em>${_(d)}</em>`,c++,m}),s=_(s);for(let g=l.length-1;g>=0;g--)s=s.replace(`__MARKDOWN_PLACEHOLDER_${g}__`,()=>l[g]);return s}}}var me=z(),he=K();export{V as createCache,re as createI18n,D as deepMerge,ae as defaultPluralRules,A as getNestedValue,F as getPluralForm,he as icuPlugin,S as interpolate,me as markdownPlugin};//# sourceMappingURL=index.mjs.map
1
+ function S(e,n,s,t,o){if(typeof e!="string")return String(e);try{return e.replace(/\{\{([^}]+)\}\}/g,(c,g)=>{let p=u(g);return p===void 0?c:o?o(p):p})}catch(c){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Template interpolation error:",c),e}function u(c){try{let[g,p]=c.trim().split(":").map(b=>b.trim());if(!Object.prototype.hasOwnProperty.call(n,g)){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation parameter: ${g}`);return}let m=n[g];if(p&&s?.has(p))try{let b=s.get(p);if(!b)return String(m);let f=b(m,c.includes(":")?c.split(":").slice(1).join(":"):void 0,t);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(b){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] Formatter error for ${p}:`,b),String(m)}return m==null?"":m instanceof Date?m.toLocaleDateString(t||"en-US",{year:"numeric",month:"2-digit",day:"2-digit"}):String(m)}catch(g){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] Parameter interpolation error:",g);return}}}function M(e,n){if(!e||typeof e!="object")throw new Error("[i18n] Invalid target for deepMerge");if(!n||typeof n!="object")return e;try{let s={...e};for(let t in n){if(t==="__proto__"||t==="constructor"||t==="prototype"){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Blocked attempt to set dangerous property: ${t}`);continue}if(!Object.prototype.hasOwnProperty.call(n,t))continue;let o=n[t];if(o!==void 0)if(typeof o=="object"&&o!==null&&!Array.isArray(o)&&!(o instanceof Date)){let u=s[t];s[t]=M(u&&typeof u=="object"?u:{},o);}else s[t]=o;}return s}catch(s){return typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] DeepMerge error:",s),e}}function A(e,n){if(!(!e||typeof e!="object"||!n||typeof n!="string"))try{let s=n.split("."),t=e;for(let o of s)if(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,o))t=t[o];else return;return t}catch(s){typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error("[i18n] getNestedValue error:",s);return}}function V(e){let n=new Map,s=e?.maxSize??1e3;return {get:t=>{let o=n.get(t);return o!==void 0&&(n.delete(t),n.set(t,o)),o},set:(t,o)=>{if(n.has(t))n.delete(t);else if(n.size>=s){let u=n.keys().next().value;u!==void 0&&n.delete(u);}n.set(t,o);},clear:()=>n.clear(),size:()=>n.size}}var ue={en:e=>e===0?"zero":e===1?"one":"other",es:e=>e===0?"zero":e===1?"one":"other",fr:e=>e===0||e===1?"one":"other",de:e=>e===1?"one":"other",ja:()=>"other",ko:()=>"other",zh:()=>"other"},R=new Map;function te(e){let n=R.get(e);if(!n){try{let s=e.replace(/_/g,"-");n=new Intl.PluralRules(Intl.PluralRules.supportedLocalesOf(s).length>0?s:"en");}catch{n=new Intl.PluralRules("en");}R.set(e,n);}return n}function F(e,n,s){if(s){let t=e.split(/[-_]/)[0],o=Object.prototype.hasOwnProperty.call(s,e)?s[e]:Object.prototype.hasOwnProperty.call(s,t)?s[t]:void 0;if(typeof o=="function")return o(n)}return te(e).select(n)}function K(e){return e.replace(/\{/g,"{\uE000")}function z(e){return e.replace(/\{\uE000/g,"{")}function ne(e){if(!e)throw new Error("[i18n] Configuration is required");if(!e.locale||typeof e.locale!="string"||e.locale.trim()==="")throw new Error("[i18n] Locale must be a non-empty string");if(!e.messages)throw new Error("[i18n] Messages are required");if(typeof e.messages!="object"||Array.isArray(e.messages)||e.messages===null)throw new Error("[i18n] Messages must be an object");let n=Object.keys(e.messages).length>0;n||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn("[i18n] Messages object is empty - all translations will return keys");let s=r=>$(r).some(i=>Object.prototype.hasOwnProperty.call(e.messages,i));if(n&&!s(e.locale)&&!e.fallbackLocale){let r=Object.keys(e.messages).join(", ");throw new Error(`[i18n] Locale '${e.locale}' not found in messages and no fallback locale provided. Available locales: ${r}`)}if(!s(e.locale)&&e.fallbackLocale&&typeof process<"u"&&process.env?.NODE_ENV!=="production"){let r=Object.keys(e.messages).join(", ");console.warn(`[i18n] Locale '${e.locale}' not found in messages, will use fallback locale '${e.fallbackLocale}'. Available locales: ${r}`);}if(e.fallbackLocale&&!s(e.fallbackLocale)){let r=Object.keys(e.messages).join(", ");typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Fallback locale '${e.fallbackLocale}' not found in messages. Available locales: ${r}`);}let t=e.locale,o=e.fallbackLocale,u=structuredClone(e.messages),c=[...e.plugins||[]],g=new Set,p=V(),m=0,b=()=>{m++,g.forEach(r=>{try{r(t);}catch(i){f(i,"Locale change listener");}});},f=(r,i)=>{let a=r instanceof Error?r:new Error(String(r));if(e.onError)try{e.onError(a,i);}catch{}typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.error(`[i18n] ${i}:`,a);},y=new Map;function L(r,i,a){if(!r)return;let l=h=>Object.prototype.hasOwnProperty.call(r,h)?r[h]:void 0;if(i&&l(i))return l(i);let d=(i||"").split(":").map(h=>h.trim());return d[0]===a&&d.shift(),l(d.join(":")||"default")}y.set("number",(r,i,a)=>{if(typeof r!="number")return String(r);let l=L(e.formats?.number,i,"number")||{};return new Intl.NumberFormat(a||t,l).format(r)}),y.set("date",(r,i,a)=>{if(!(r instanceof Date))return String(r);let l=L(e.formats?.date,i,"date")||{};return new Intl.DateTimeFormat(a||t,l).format(r)}),y.set("currency",(r,i,a)=>{if(typeof r!="number")return String(r);let l=(i||"currency:USD").split(":"),d=l.length>1&&l[1]||"USD";try{return new Intl.NumberFormat(a||t,{style:"currency",currency:d}).format(r)}catch(h){return f(h,`Currency formatter error for currency '${d}'`),`${d} ${r}`}}),c.forEach(r=>{r.format&&y.set(r.name,(i,a,l)=>r.format(i,a??"",l??t));});function x(r,i){if(!Object.prototype.hasOwnProperty.call(u,i))return;let a=u[i];if(!a||typeof a!="object")return;let l=Object.prototype.hasOwnProperty.call(a,r)?a[r]:A(a,r);return typeof l=="string"?l:void 0}function D(r,i,a){let l=k(a),d=i&&Object.prototype.hasOwnProperty.call(i,"count")?i.count:void 0;for(let h of l){if(typeof d=="number"){let E=new Set;d===0&&E.add("zero"),E.add(F(h,d,e.pluralizationRules)),E.add("other");for(let I of E){let w=x(`${r}.${I}`,h);if(w)return {message:w,messageLocale:h}}}let P=x(r,h);if(P)return {message:P,messageLocale:h}}}function k(r){return [...new Set([...$(r),...o?$(o):[]])]}function j(r,i,a=t){try{let l=i?se(i):"",d=l===void 0?void 0:`${a}:${r}:${l}`,h=d===void 0?void 0:p.get(d);if(h!==void 0)return h;let P=D(r,i,a);if(!P)return e.warnOnMissingTranslations&&typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Missing translation: ${r} for locale: ${a}`),r;let{message:E,messageLocale:I}=P,w=E;for(let O of c)if(O.transform)try{let _=O.transform(r,w,i||{},a,I);if(typeof _!="string"){f(new Error(`Plugin transform must return a string, got ${typeof _}`),`Plugin ${O.name} transform validation`);continue}w=_;}catch(_){f(_,`Plugin ${O.name} transform`);}let N=c.filter(O=>typeof O.escapeValue=="function");return w=S(w,i||{},y,t,N.length>0?O=>N.reduce((_,re)=>re.escapeValue(_),O):void 0),w=z(w),d!==void 0&&p.set(d,w),w}catch(l){return f(l,`Translation error for key ${r}`),r}}let H=(r,i)=>j(String(r),i);function q(r){if(!r||typeof r!="string")throw new Error("[i18n] Invalid locale provided");$(r).some(i=>Object.prototype.hasOwnProperty.call(u,i))||typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Locale '${r}' not found in messages. Available locales: ${Object.keys(u).join(", ")}`),r!==t&&(t=r,p.clear(),b());}function B(r,i){if(!r||typeof r!="string")throw new Error("[i18n] Invalid locale provided");if(!i||typeof i!="object")throw new Error("[i18n] Invalid messages provided");try{u[r]||(u[r]={});let a=i;for(let l of c)if(l.beforeLoad)try{let d=l.beforeLoad(r,a);if(!d||typeof d!="object"||Array.isArray(d)){f(new Error(`Plugin beforeLoad must return an object, got ${typeof d}`),`Plugin ${l.name} beforeLoad validation`);continue}a=d;}catch(d){f(d,`Plugin ${l.name} beforeLoad`);}u[r]=M(u[r],a);for(let l of c)if(l.afterLoad)try{l.afterLoad(r,u[r]);}catch(d){f(d,`Plugin ${l.name} afterLoad`);}p.clear(),k(t).includes(r)&&b();}catch(a){throw f(a,"Error adding messages"),a}}function J(r,i,a){let l=i||t;return (a?.exact?[l]:k(l)).some(h=>x(String(r),h)!==void 0)}function G(r){let i=c.findIndex(a=>a.name===r.name);i!==-1&&(typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[i18n] Plugin '${r.name}' already registered. Replacing existing plugin.`),c.splice(i,1)),c.push(r),r.format&&y.set(r.name,(a,l,d)=>r.format(a,l??"",d??t)),p.clear(),b();}function Q(r){let i=c.findIndex(a=>a.name===r);i!==-1&&(c.splice(i,1),y.delete(r),p.clear(),b());}function X(r){return g.add(r),()=>g.delete(r)}function Y(r,i){let a=y.get("number");if(!a)throw new Error("[i18n] Number formatter not available. Please add a plugin that provides number formatting.");return a(r,i,t)}function Z(r,i){let a=y.get("date");if(!a)throw new Error("[i18n] Date formatter not available. Please add a plugin that provides date formatting.");return a(r,i,t)}function ee(r,i=new Date){if(!(r instanceof Date)||isNaN(r.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.trunc((r.getTime()-i.getTime())/1e3),l=new Intl.RelativeTimeFormat(t,{numeric:"auto"}),d=[["year",60*60*24*365],["month",60*60*24*30,12],["week",60*60*24*7],["day",60*60*24,7],["hour",60*60,24],["minute",60,60],["second",1]],h=a<0?-1:1;for(let P=0;P<d.length;P++){let[E,I,w]=d[P];if(Math.abs(a)>=I){let N=Math.round(Math.abs(a)/I);return w!==void 0&&N>=w?l.format(h,d[P-1][0]):l.format(h*N,E)}}return l.format(0,"second")}return {get locale(){return t},get fallbackLocale(){return o},get messages(){return u},get revision(){return m},t:H,setLocale:q,getLocale:()=>t,hasTranslation:J,addMessages:B,addPlugin:G,removePlugin:Q,subscribe:X,formatNumber:Y,formatDate:Z,formatRelativeTime:ee}}function $(e){let n=[e],s=e;for(;;){let t=Math.max(s.lastIndexOf("-"),s.lastIndexOf("_"));if(t<=0)break;s=s.slice(0,t),t=Math.max(s.lastIndexOf("-"),s.lastIndexOf("_")),t>0&&s.length-t-1===1&&(s=s.slice(0,t)),n.push(s);}return n}function se(e){let n=[];for(let s of Object.keys(e).sort()){let t=e[s],o;if(typeof t=="string")o=JSON.stringify(t);else if(typeof t=="number")o=Object.is(t,-0)?"n-0":`n${t}`;else if(typeof t=="boolean"||t===null||t===void 0)o=String(t);else if(t instanceof Date)o=`d${t.getTime()}`;else return;n.push(`${JSON.stringify(s)}=${o}`);}return n.join(",")}var v=class extends Error{},C=class{constructor(n){this.source=n;}cursor=0;parse(){return this.message(0,false).parts}take(n){n.lastIndex=this.cursor;let s=n.exec(this.source)?.[0];return s!==void 0&&(this.cursor+=s.length),s}expect(n){let s=this.take(n);if(s===void 0)throw new v;return s}space(){this.take(/\s+/y);}number(){let n=Number(this.expect(/[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/y));if(!Number.isFinite(n))throw new v;return n}quote(){let n="";for(this.cursor++;this.cursor<this.source.length;){let s=this.source.charAt(this.cursor++);if(s==="'"&&!this.take(/'/y))break;n+=s;}return n}message(n,s){if(n>64)throw new v;let t=[],o="";function u(){o&&t.push(o),o="";}for(;this.cursor<this.source.length;){let c=this.source.charAt(this.cursor);if(c==="}"){if(n===0)throw new v;return this.cursor++,u(),{parts:t,closed:true}}if(c==="{"){let g=this.take(/\{\{[^{}]*\}\}/y);g!==void 0?o+=g:(u(),t.push(this.argument(n)));}else c==="'"&&this.take(/''/y)?o+="'":c==="'"&&(["{","}"].includes(this.source.charAt(this.cursor+1))||s&&this.source.charAt(this.cursor+1)==="#")?o+=this.quote():(this.cursor++,c==="#"&&s?(u(),t.push({kind:"number"})):o+=c);}return u(),{parts:t,closed:false}}argument(n){let s=this.cursor++;this.space();let t=this.expect(/[\p{ID_Continue}]+/uy);if(this.space(),this.take(/\}/y))return {kind:"value",name:t,source:this.source.slice(s,this.cursor)};this.expect(/,/y),this.space();let o=this.expect(/selectordinal|plural|select/y);this.space(),this.expect(/,/y),this.space();let u=o!=="select"&&this.take(/offset\s*:\s*/y)?this.number():0;this.space();let c=new Map;for(;!this.take(/\}/y);){let g=o!=="select"&&this.take(/=/y)?"="+this.number():this.expect(/[\p{ID_Continue}]+/uy);this.space(),this.expect(/\{/y);let p=this.message(n+1,o!=="select");if(!p.closed)throw new v;c.has(g)||c.set(g,p.parts),this.space();}if(!c.has("other"))throw new v;return {kind:o,name:t,choices:c,offset:u,source:this.source.slice(s,this.cursor)}}};function oe(e){try{return Intl.getCanonicalLocales(e.replace(/_/g,"-"))[0]??"en"}catch{return "en"}}function ie(e,n,s){let t=oe(s),o={maximumSignificantDigits:21},u,c,g;function p(m,b){return m.map(f=>{if(typeof f=="string")return f;if(f.kind==="number")return b===void 0?"#":(g??=new Intl.NumberFormat(t,o)).format(b);if(!Object.hasOwn(n,f.name))return f.source;let y=n[f.name];if(f.kind==="value")return K(String(y));if(f.kind==="select"){let j=f.choices.get(String(y))??f.choices.get("other");return j?p(j):f.source}if(typeof y!="number"||!Number.isFinite(y))return f.source;let L=y-f.offset;if(!Number.isFinite(L))return f.source;let x=f.choices.get("="+y);if(x)return p(x,L);let D=f.kind==="plural"?u??=new Intl.PluralRules(t,o):c??=new Intl.PluralRules(t,{...o,type:"ordinal"}),k=f.choices.get(D.select(L))??f.choices.get("other");return k?p(k,L):f.source}).join("")}return p(e)}function U(){return {name:"icu",transform:(e,n,s,t,o)=>{if(!/[{']/.test(n))return n;try{return ie(new C(n).parse(),s,o??t)}catch(u){if(u instanceof v)return n;throw u}}}}function T(e){let n={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return e.replace(/[&<>"'/]/g,s=>n[s])}function ae(e){let n=Array.from(e).filter(s=>s.charCodeAt(0)>32&&s.charCodeAt(0)!==127).join("").toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:")||n.startsWith("vbscript:")||n.startsWith("file:")?"#":T(e)}function ce(e,n){return e.replace(/\{\{([^}]+)\}\}/g,(s,t)=>{let o=t.split(":")[0].trim();if(!Object.prototype.hasOwnProperty.call(n,o))return s;let u=n[o];return u==null?"":String(u)})}function W(){return {name:"markdown",escapeValue:T,transform:(e,n,s,t)=>{let o=n,u=[],c=0;o=o.replace(/`(.*?)`/g,(g,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return u[c]=`<code>${T(p)}</code>`,c++,m}),o=o.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(g,p,m)=>{let b=`__MARKDOWN_PLACEHOLDER_${c}__`,f=ae(ce(m,s||{})).replace(/[{}]/g,y=>y==="{"?"&#123;":"&#125;");return u[c]=`<a href="${f}">${T(p)}</a>`,c++,b}),o=o.replace(/\*\*(.*?)\*\*/g,(g,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return u[c]=`<strong>${T(p)}</strong>`,c++,m}),o=o.replace(/\*(.*?)\*/g,(g,p)=>{let m=`__MARKDOWN_PLACEHOLDER_${c}__`;return u[c]=`<em>${T(p)}</em>`,c++,m}),o=T(o);for(let g=u.length-1;g>=0;g--)o=o.replace(`__MARKDOWN_PLACEHOLDER_${g}__`,()=>u[g]);return o}}}var be=W(),we=U();export{V as createCache,ne as createI18n,M as deepMerge,ue as defaultPluralRules,A as getNestedValue,F as getPluralForm,K as guardBraces,we as icuPlugin,S as interpolate,be as markdownPlugin,z as releaseBraces};//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
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","hasCatalog","localeChain","candidate","availableLocales","currentLocale","fallbackLocale","messages","plugins","listeners","translationCache","revision","notify","listener","handleError","context","err","namedFormat","table","type","own","name","parts","part","currency","plugin","getMessage","localeMessages","resolveMessage","locales","lookupChain","forms","form","pluralMessage","message","translate","paramsCacheKey","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","chain","cut","encoded","InvalidPattern","MessageParser","pattern","token","number","literal","depth","pound","flush","legacy","start","kind","offset","choices","selector","option","intlLocale","numberOptions","cardinal","ordinal","numbers","render","selection","adjusted","exact","createICUPlugin","_key","escapeHtml","text","htmlEscapeMap","char","sanitizeHref","href","trimmed","resolveHrefParams","placeholder","createMarkdownPlugin","_locale","placeholders","placeholderIndex","_","url","brace","i","markdownPlugin","icuPlugin"],"mappings":"AAMO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EACAC,CAAAA,CACQ,CACR,GAAI,OAAOJ,CAAAA,EAAa,QAAA,CACtB,OAAO,MAAA,CAAOA,CAAQ,EAGxB,GAAI,CACF,OAAOA,CAAAA,CAAS,OAAA,CAAQ,kBAAA,CAAoB,CAACK,CAAAA,CAAOC,CAAAA,GAAQ,CAC1D,IAAMC,CAAAA,CAAcC,EAAmBF,CAAG,CAAA,CAC1C,OAAIC,CAAAA,GAAgB,KAAA,CAAA,CAAkBF,CAAAA,CAC/BD,CAAAA,CAASA,CAAAA,CAAOG,CAAW,EAAIA,CACxC,CAAC,CACH,CAAA,MAASE,CAAAA,CAAO,CACd,OAAI,OAAO,OAAA,CAAY,GAAA,EAAe,OAAA,CAAQ,GAAA,EAAK,WAAa,YAAA,EAC9D,OAAA,CAAQ,MAAM,sCAAA,CAAwCA,CAAK,EAEtDT,CACT,CAEA,SAASQ,CAAAA,CAAmBF,CAAAA,CAAiC,CAC3D,GAAI,CACF,GAAM,CAACI,CAAAA,CAAUC,CAAM,EAAIL,CAAAA,CACxB,IAAA,EAAK,CACL,KAAA,CAAM,GAAG,CAAA,CACT,IAAKM,CAAAA,EAAcA,CAAAA,CAAE,MAAM,CAAA,CAE9B,GAAI,CAAC,MAAA,CAAO,SAAA,CAAU,cAAA,CAAe,IAAA,CAAKX,CAAAA,CAAQS,CAAQ,CAAA,CAAG,CACvD,OAAO,OAAA,CAAY,GAAA,EAAe,OAAA,CAAQ,KAAK,QAAA,GAAa,YAAA,EAC9D,OAAA,CAAQ,IAAA,CAAK,CAAA,sCAAA,EAAyCA,CAAQ,EAAE,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,CAAAA,CAASA,EAAO,OAAA,CAAQ,YAAA,CAAc,CAACsI,CAAAA,CAAGZ,CAAAA,GAAS,CACjD,IAAMO,CAAAA,CAAc,CAAA,uBAAA,EAA0BI,CAAgB,CAAA,EAAA,CAAA,CAC9D,OAAAD,EAAaC,CAAgB,CAAA,CAAI,CAAA,IAAA,EAAOZ,CAAAA,CAAWC,CAAI,CAAC,QACxDW,CAAAA,EAAAA,CACOJ,CACT,CAAC,CAAA,CAGDjI,CAAAA,CAASyH,EAAWzH,CAAM,CAAA,CAK1B,IAAA,IAASyI,CAAAA,CAAIL,CAAAA,CAAa,MAAA,CAAS,EAAGK,CAAAA,EAAK,CAAA,CAAGA,IAC5CzI,CAAAA,CAASA,CAAAA,CAAO,QAAQ,CAAA,uBAAA,EAA0ByI,CAAC,CAAA,EAAA,CAAA,CAAM,IAAML,CAAAA,CAAaK,CAAC,CAAC,CAAA,CAGhF,OAAOzI,CACT,CACF,CACF,KClHa0I,EAAAA,CAA6BR,CAAAA,EAAqB,CAKlDS,EAAAA,CAAwBpB,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\n .trim()\n .split(':')\n .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(\n value,\n key.includes(':') ? key.split(':').slice(1).join(':') : undefined,\n locale\n );\n // Validate formatter returns a string\n if (typeof formatted !== 'string') {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(\n `[i18n] Formatter '${format}' must return a string, got ${typeof formatted}`\n );\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>(target: T, source: Partial<T>): 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 (key === '__proto__' || key === 'constructor' || key === 'prototype') {\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>(obj: Record<string, unknown>, path: string): 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 (\n current &&\n typeof current === 'object' &&\n Object.prototype.hasOwnProperty.call(current, key)\n ) {\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(\n Intl.PluralRules.supportedLocalesOf(tag).length > 0 ? tag : 'en'\n );\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 { createCache, deepMerge, getNestedValue, getPluralForm, interpolate } 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 (\n typeof config.messages !== 'object' ||\n Array.isArray(config.messages) ||\n config.messages === null\n ) {\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 const hasCatalog = (locale: LocaleCode): boolean =>\n localeChain(locale).some(candidate =>\n Object.prototype.hasOwnProperty.call(config.messages, candidate)\n );\n // Validate that the current locale (or a base language: en-US → en) exists in messages,\n // unless a fallback is provided or messages is empty\n if (hasMessages && !hasCatalog(config.locale) && !config.fallbackLocale) {\n const availableLocales = Object.keys(config.messages).join(', ');\n throw new Error(\n `[i18n] Locale '${config.locale}' not found in messages and no fallback locale provided. Available locales: ${availableLocales}`\n );\n }\n // Warn if current locale doesn't exist but fallback does\n if (!hasCatalog(config.locale) && config.fallbackLocale) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n const availableLocales = Object.keys(config.messages).join(', ');\n console.warn(\n `[i18n] Locale '${config.locale}' not found in messages, will use fallback locale '${config.fallbackLocale}'. Available locales: ${availableLocales}`\n );\n }\n }\n // Validate fallback locale if provided\n if (config.fallbackLocale && !hasCatalog(config.fallbackLocale)) {\n const availableLocales = Object.keys(config.messages).join(', ');\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(\n `[i18n] Fallback locale '${config.fallbackLocale}' not found in messages. Available locales: ${availableLocales}`\n );\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<\n string,\n (value: TranslationValue, format?: string, locale?: string) => string\n >();\n\n // Options of a named format. `formatNumber(v, 'percent')` passes the name; placeholders pass\n // the formatter too (`{{v:number}}` → 'number' → `default`, `{{v:number:percent}}` →\n // 'number:percent' → `percent`). A format literally named like that still wins.\n function namedFormat<T extends object>(\n table: Record<string, T> | undefined,\n format: string | undefined,\n type: string\n ): T | undefined {\n if (!table) return undefined;\n const own = (name: string) =>\n Object.prototype.hasOwnProperty.call(table, name) ? table[name] : undefined;\n if (format && own(format)) return own(format);\n const parts = (format || '').split(':').map(part => part.trim());\n if (parts[0] === type) parts.shift();\n return own(parts.join(':') || 'default');\n }\n\n // Built-in formatters\n formatters.set('number', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const options = namedFormat(config.formats?.number, format, 'number') || {};\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 = namedFormat(config.formats?.date, format, 'date') || {};\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 // BCP 47 lookup: the locale, its base languages (zh-Hant-TW → zh-Hant → zh), then the\n // fallback locale and its base languages.\n const locales = lookupChain(locale);\n const count =\n 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 lookupChain(locale: LocaleCode): LocaleCode[] {\n return [\n ...new Set([...localeChain(locale), ...(fallbackLocale ? localeChain(fallbackLocale) : [])]),\n ];\n }\n\n function translate(\n key: string,\n params?: TranslationParams,\n locale: LocaleCode = currentLocale\n ): string {\n try {\n // Params that cannot be encoded unambiguously are not cached.\n const paramKey = params ? paramsCacheKey(params) : '';\n const cacheKey = paramKey === undefined ? undefined : `${locale}:${key}:${paramKey}`;\n const cached = cacheKey === undefined ? undefined : translationCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const resolved = resolveMessage(key, params, locale);\n if (!resolved) {\n if (\n config.warnOnMissingTranslations &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'production'\n ) {\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 if (cacheKey !== undefined) 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 neither the locale nor its base language exists in messages\n if (\n !localeChain(locale).some(candidate =>\n Object.prototype.hasOwnProperty.call(messages, candidate)\n )\n ) {\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 (lookupChain(currentLocale).includes(locale)) {\n notify();\n }\n } catch (error) {\n handleError(error, 'Error adding messages');\n throw error;\n }\n }\n\n function hasTranslation(\n key: TranslationKey<TMessages>,\n locale?: LocaleCode,\n options?: { exact?: boolean }\n ): boolean {\n const checkLocale = locale || currentLocale;\n // Same lookup as t(): the locale, its base languages, then the fallback locale chain.\n // `exact: true` checks only the given (or active) locale's own catalog.\n const locales = options?.exact ? [checkLocale] : lookupChain(checkLocale);\n return locales.some(candidate => getMessage(String(key), candidate) !== 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(\n `[i18n] Plugin '${plugin.name}' already registered. Replacing existing plugin.`\n );\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 // Plugins change the visible text; UI bindings re-render on notifications.\n notify();\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 notify();\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(\n '[i18n] Number formatter not available. Please add a plugin that provides number formatting.'\n );\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(\n '[i18n] Date formatter not available. Please add a plugin that provides date formatting.'\n );\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\n/**\n * `locale` followed by its truncations (RFC 4647 lookup): `zh-Hant-TW` → `zh-Hant` → `zh`.\n * A trailing single-letter subtag (extension or private-use singleton) is dropped too.\n */\nfunction localeChain(locale: LocaleCode): LocaleCode[] {\n const chain = [locale];\n let current = locale;\n for (;;) {\n let cut = Math.max(current.lastIndexOf('-'), current.lastIndexOf('_'));\n if (cut <= 0) break;\n current = current.slice(0, cut);\n cut = Math.max(current.lastIndexOf('-'), current.lastIndexOf('_'));\n if (cut > 0 && current.length - cut - 1 === 1) current = current.slice(0, cut);\n chain.push(current);\n }\n return chain;\n}\n\n/**\n * Cache key for translation params: every value that renders differently gets a different key\n * (`NaN`, `Infinity`, `-0` and `null` all serialize to the same JSON). Returns undefined for\n * values without a faithful encoding (objects, bigint, ...), which are then not cached.\n */\nfunction paramsCacheKey(params: TranslationParams): string | undefined {\n const parts: string[] = [];\n for (const name of Object.keys(params).sort()) {\n const value: unknown = params[name];\n let encoded: string;\n if (typeof value === 'string') encoded = JSON.stringify(value);\n else if (typeof value === 'number') encoded = Object.is(value, -0) ? 'n-0' : `n${value}`;\n else if (typeof value === 'boolean' || value === null || value === undefined)\n encoded = String(value);\n else if (value instanceof Date) encoded = `d${value.getTime()}`;\n else return undefined;\n parts.push(`${JSON.stringify(name)}=${encoded}`);\n }\n return parts.join(',');\n}\n","import type { I18nPlugin, TranslationParams } from '../types';\n\ntype ChoiceKind = 'plural' | 'select' | 'selectordinal';\ntype Part =\n | string\n | { kind: 'value'; name: string; source: string }\n | { kind: 'number' }\n | {\n kind: ChoiceKind;\n name: string;\n source: string;\n choices: Map<string, Part[]>;\n offset: number;\n };\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 (\n 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))\n 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 =\n 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\n .map(part => {\n if (typeof part === 'string') return part;\n if (part.kind === 'number') {\n return pound === undefined\n ? '#'\n : (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 =\n 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 })\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, TranslationParams } 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 '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '/': '&#x2F;',\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 // Browsers ignore leading controls/spaces and tabs/newlines anywhere in a URL\n // (\"java\\tscript:\" is \"javascript:\"), so remove them before checking the scheme.\n const trimmed = Array.from(href)\n .filter(char => char.charCodeAt(0) > 0x20 && char.charCodeAt(0) !== 0x7f)\n .join('')\n .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 * Inserts `{{name}}` parameters into a link URL so the complete URL is checked. The raw value\n * is used (no formatter); placeholders without a parameter are kept.\n */\nfunction resolveHrefParams(href: string, params: TranslationParams): string {\n return href.replace(/\\{\\{([^}]+)\\}\\}/g, (match, placeholder: string) => {\n const name = placeholder.split(':')[0].trim();\n if (!Object.prototype.hasOwnProperty.call(params, name)) return match;\n const value = params[name];\n return value === null || value === undefined ? '' : String(value);\n });\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 // `code` -> <code>text</code>. Code spans go first: their content is literal (no\n // emphasis or links inside), and bold/italic/link text may contain them.\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 // [text](url) -> <a href=\"url\">text</a>\n result = result.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, (_, text, href) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n // Parameters are inserted before the scheme check (a `{{url}}` parameter could be a\n // javascript: URL); braces are encoded so interpolation cannot change the URL later.\n const url = sanitizeHref(resolveHrefParams(href, params || {})).replace(/[{}]/g, brace =>\n brace === '{' ? '&#123;' : '&#125;'\n );\n placeholders[placeholderIndex] = `<a href=\"${url}\">${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 // Escape any remaining text that wasn't part of markdown\n result = escapeHtml(result);\n\n // Restore placeholders, newest first: an outer construct (`**[a](b)**`) holds the\n // placeholders created before it. A replacer function keeps `$&`, `$'` and `$$` in the\n // text literal (a replacement string would expand them).\n for (let i = placeholders.length - 1; i >= 0; i--) {\n result = result.replace(`__MARKDOWN_PLACEHOLDER_${i}__`, () => placeholders[i]);\n }\n\n return result;\n },\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"]}
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","guardBraces","releaseBraces","text","createI18n","config","hasMessages","hasCatalog","localeChain","candidate","availableLocales","currentLocale","fallbackLocale","messages","plugins","listeners","translationCache","revision","notify","listener","handleError","context","err","namedFormat","table","type","own","name","parts","part","currency","plugin","getMessage","localeMessages","resolveMessage","locales","lookupChain","forms","form","pluralMessage","message","translate","paramsCacheKey","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","sign","i","unit","secondsInUnit","perNextUnit","amount","chain","cut","encoded","InvalidPattern","MessageParser","pattern","token","number","literal","depth","pound","flush","legacy","start","kind","offset","choices","selector","option","intlLocale","numberOptions","cardinal","ordinal","numbers","render","selection","adjusted","exact","createICUPlugin","_key","escapeHtml","htmlEscapeMap","char","sanitizeHref","href","trimmed","resolveHrefParams","placeholder","createMarkdownPlugin","_locale","placeholders","placeholderIndex","_","url","brace","markdownPlugin","icuPlugin"],"mappings":"AAMO,SAASA,CAAAA,CACdC,EACAC,CAAAA,CACAC,CAAAA,CACAC,EACAC,CAAAA,CACQ,CACR,GAAI,OAAOJ,CAAAA,EAAa,QAAA,CACtB,OAAO,MAAA,CA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A,CAK1B,IAAA,IAAS6F,CAAAA,CAAI6C,CAAAA,CAAa,MAAA,CAAS,EAAG7C,CAAAA,EAAK,CAAA,CAAGA,IAC5C7F,CAAAA,CAASA,CAAAA,CAAO,QAAQ,CAAA,uBAAA,EAA0B6F,CAAC,CAAA,EAAA,CAAA,CAAM,IAAM6C,CAAAA,CAAa7C,CAAC,CAAC,CAAA,CAGhF,OAAO7F,CACT,CACF,CACF,KClHa+I,EAAAA,CAA6BP,CAAAA,EAAqB,CAKlDQ,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\n .trim()\n .split(':')\n .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(\n value,\n key.includes(':') ? key.split(':').slice(1).join(':') : undefined,\n locale\n );\n // Validate formatter returns a string\n if (typeof formatted !== 'string') {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.error(\n `[i18n] Formatter '${format}' must return a string, got ${typeof formatted}`\n );\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>(target: T, source: Partial<T>): 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 (key === '__proto__' || key === 'constructor' || key === 'prototype') {\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>(obj: Record<string, unknown>, path: string): 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 (\n current &&\n typeof current === 'object' &&\n Object.prototype.hasOwnProperty.call(current, key)\n ) {\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(\n Intl.PluralRules.supportedLocalesOf(tag).length > 0 ? tag : 'en'\n );\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\n/**\n * Marks the braces of a value a plugin inserts into a message, so the `{{name}}`\n * interpolation that runs afterwards never treats text from a parameter value as a\n * placeholder. {@link releaseBraces} removes the marks once interpolation is done.\n * @internal\n */\nexport function guardBraces(value: string): string {\n return value.replace(/\\{/g, '{\\uE000');\n}\n\n/** Removes the marks {@link guardBraces} added. @internal */\nexport function releaseBraces(text: string): string {\n return text.replace(/\\{\\uE000/g, '{');\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 releaseBraces,\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 (\n typeof config.messages !== 'object' ||\n Array.isArray(config.messages) ||\n config.messages === null\n ) {\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 const hasCatalog = (locale: LocaleCode): boolean =>\n localeChain(locale).some(candidate =>\n Object.prototype.hasOwnProperty.call(config.messages, candidate)\n );\n // Validate that the current locale (or a base language: en-US → en) exists in messages,\n // unless a fallback is provided or messages is empty\n if (hasMessages && !hasCatalog(config.locale) && !config.fallbackLocale) {\n const availableLocales = Object.keys(config.messages).join(', ');\n throw new Error(\n `[i18n] Locale '${config.locale}' not found in messages and no fallback locale provided. Available locales: ${availableLocales}`\n );\n }\n // Warn if current locale doesn't exist but fallback does\n if (!hasCatalog(config.locale) && config.fallbackLocale) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n const availableLocales = Object.keys(config.messages).join(', ');\n console.warn(\n `[i18n] Locale '${config.locale}' not found in messages, will use fallback locale '${config.fallbackLocale}'. Available locales: ${availableLocales}`\n );\n }\n }\n // Validate fallback locale if provided\n if (config.fallbackLocale && !hasCatalog(config.fallbackLocale)) {\n const availableLocales = Object.keys(config.messages).join(', ');\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(\n `[i18n] Fallback locale '${config.fallbackLocale}' not found in messages. Available locales: ${availableLocales}`\n );\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<\n string,\n (value: TranslationValue, format?: string, locale?: string) => string\n >();\n\n // Options of a named format. `formatNumber(v, 'percent')` passes the name; placeholders pass\n // the formatter too (`{{v:number}}` → 'number' → `default`, `{{v:number:percent}}` →\n // 'number:percent' → `percent`). A format literally named like that still wins.\n function namedFormat<T extends object>(\n table: Record<string, T> | undefined,\n format: string | undefined,\n type: string\n ): T | undefined {\n if (!table) return undefined;\n const own = (name: string) =>\n Object.prototype.hasOwnProperty.call(table, name) ? table[name] : undefined;\n if (format && own(format)) return own(format);\n const parts = (format || '').split(':').map(part => part.trim());\n if (parts[0] === type) parts.shift();\n return own(parts.join(':') || 'default');\n }\n\n // Built-in formatters\n formatters.set('number', (value, format, locale) => {\n if (typeof value !== 'number') return String(value);\n const options = namedFormat(config.formats?.number, format, 'number') || {};\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 = namedFormat(config.formats?.date, format, 'date') || {};\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 // BCP 47 lookup: the locale, its base languages (zh-Hant-TW → zh-Hant → zh), then the\n // fallback locale and its base languages.\n const locales = lookupChain(locale);\n const count =\n 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 lookupChain(locale: LocaleCode): LocaleCode[] {\n return [\n ...new Set([...localeChain(locale), ...(fallbackLocale ? localeChain(fallbackLocale) : [])]),\n ];\n }\n\n function translate(\n key: string,\n params?: TranslationParams,\n locale: LocaleCode = currentLocale\n ): string {\n try {\n // Params that cannot be encoded unambiguously are not cached.\n const paramKey = params ? paramsCacheKey(params) : '';\n const cacheKey = paramKey === undefined ? undefined : `${locale}:${key}:${paramKey}`;\n const cached = cacheKey === undefined ? undefined : translationCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const resolved = resolveMessage(key, params, locale);\n if (!resolved) {\n if (\n config.warnOnMissingTranslations &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'production'\n ) {\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 result = releaseBraces(result);\n\n if (cacheKey !== undefined) 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 neither the locale nor its base language exists in messages\n if (\n !localeChain(locale).some(candidate =>\n Object.prototype.hasOwnProperty.call(messages, candidate)\n )\n ) {\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 (lookupChain(currentLocale).includes(locale)) {\n notify();\n }\n } catch (error) {\n handleError(error, 'Error adding messages');\n throw error;\n }\n }\n\n function hasTranslation(\n key: TranslationKey<TMessages>,\n locale?: LocaleCode,\n options?: { exact?: boolean }\n ): boolean {\n const checkLocale = locale || currentLocale;\n // Same lookup as t(): the locale, its base languages, then the fallback locale chain.\n // `exact: true` checks only the given (or active) locale's own catalog.\n const locales = options?.exact ? [checkLocale] : lookupChain(checkLocale);\n return locales.some(candidate => getMessage(String(key), candidate) !== 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(\n `[i18n] Plugin '${plugin.name}' already registered. Replacing existing plugin.`\n );\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 // Plugins change the visible text; UI bindings re-render on notifications.\n notify();\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 notify();\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(\n '[i18n] Number formatter not available. Please add a plugin that provides number formatting.'\n );\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(\n '[i18n] Date formatter not available. Please add a plugin that provides date formatting.'\n );\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 // Truncate and round the magnitude so a date d before the base reads like one d after it.\n const diffInSeconds = Math.trunc((value.getTime() - baseDate.getTime()) / 1000);\n const rtf = new Intl.RelativeTimeFormat(currentLocale, { numeric: 'auto' });\n\n // [unit, seconds in it, how many of it make the next larger unit (weeks do not add up to a month)]\n const units: Array<[Intl.RelativeTimeFormatUnit, number, number?]> = [\n ['year', 60 * 60 * 24 * 365],\n ['month', 60 * 60 * 24 * 30, 12],\n ['week', 60 * 60 * 24 * 7],\n ['day', 60 * 60 * 24, 7],\n ['hour', 60 * 60, 24],\n ['minute', 60, 60],\n ['second', 1],\n ];\n\n const sign = diffInSeconds < 0 ? -1 : 1;\n for (let i = 0; i < units.length; i++) {\n const [unit, secondsInUnit, perNextUnit] = units[i]!;\n if (Math.abs(diffInSeconds) >= secondsInUnit) {\n const amount = Math.round(Math.abs(diffInSeconds) / secondsInUnit);\n // Rounding up to a whole larger unit reads as that unit: \"in 1 hour\", not \"in 60 minutes\".\n if (perNextUnit !== undefined && amount >= perNextUnit) {\n return rtf.format(sign, units[i - 1]![0]);\n }\n return rtf.format(sign * amount, 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\n/**\n * `locale` followed by its truncations (RFC 4647 lookup): `zh-Hant-TW` → `zh-Hant` → `zh`.\n * A trailing single-letter subtag (extension or private-use singleton) is dropped too.\n */\nfunction localeChain(locale: LocaleCode): LocaleCode[] {\n const chain = [locale];\n let current = locale;\n for (;;) {\n let cut = Math.max(current.lastIndexOf('-'), current.lastIndexOf('_'));\n if (cut <= 0) break;\n current = current.slice(0, cut);\n cut = Math.max(current.lastIndexOf('-'), current.lastIndexOf('_'));\n if (cut > 0 && current.length - cut - 1 === 1) current = current.slice(0, cut);\n chain.push(current);\n }\n return chain;\n}\n\n/**\n * Cache key for translation params: every value that renders differently gets a different key\n * (`NaN`, `Infinity`, `-0` and `null` all serialize to the same JSON). Returns undefined for\n * values without a faithful encoding (objects, bigint, ...), which are then not cached.\n */\nfunction paramsCacheKey(params: TranslationParams): string | undefined {\n const parts: string[] = [];\n for (const name of Object.keys(params).sort()) {\n const value: unknown = params[name];\n let encoded: string;\n if (typeof value === 'string') encoded = JSON.stringify(value);\n else if (typeof value === 'number') encoded = Object.is(value, -0) ? 'n-0' : `n${value}`;\n else if (typeof value === 'boolean' || value === null || value === undefined)\n encoded = String(value);\n else if (value instanceof Date) encoded = `d${value.getTime()}`;\n else return undefined;\n parts.push(`${JSON.stringify(name)}=${encoded}`);\n }\n return parts.join(',');\n}\n","import type { I18nPlugin, TranslationParams } from '../types';\nimport { guardBraces } from '../utils';\n\ntype ChoiceKind = 'plural' | 'select' | 'selectordinal';\ntype Part =\n | string\n | { kind: 'value'; name: string; source: string }\n | { kind: 'number' }\n | {\n kind: ChoiceKind;\n name: string;\n source: string;\n choices: Map<string, Part[]>;\n offset: number;\n };\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 (\n 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))\n 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 =\n 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\n .map(part => {\n if (typeof part === 'string') return part;\n if (part.kind === 'number') {\n return pound === undefined\n ? '#'\n : (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 // Guarded: interpolation must not read placeholders inside a parameter value\n if (part.kind === 'value') return guardBraces(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 =\n 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 })\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, TranslationParams } 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 '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '/': '&#x2F;',\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 // Browsers ignore leading controls/spaces and tabs/newlines anywhere in a URL\n // (\"java\\tscript:\" is \"javascript:\"), so remove them before checking the scheme.\n const trimmed = Array.from(href)\n .filter(char => char.charCodeAt(0) > 0x20 && char.charCodeAt(0) !== 0x7f)\n .join('')\n .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 * Inserts `{{name}}` parameters into a link URL so the complete URL is checked. The raw value\n * is used (no formatter); placeholders without a parameter are kept.\n */\nfunction resolveHrefParams(href: string, params: TranslationParams): string {\n return href.replace(/\\{\\{([^}]+)\\}\\}/g, (match, placeholder: string) => {\n const name = placeholder.split(':')[0].trim();\n if (!Object.prototype.hasOwnProperty.call(params, name)) return match;\n const value = params[name];\n return value === null || value === undefined ? '' : String(value);\n });\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 // `code` -> <code>text</code>. Code spans go first: their content is literal (no\n // emphasis or links inside), and bold/italic/link text may contain them.\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 // [text](url) -> <a href=\"url\">text</a>\n result = result.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, (_, text, href) => {\n const placeholder = `__MARKDOWN_PLACEHOLDER_${placeholderIndex}__`;\n // Parameters are inserted before the scheme check (a `{{url}}` parameter could be a\n // javascript: URL); braces are encoded so interpolation cannot change the URL later.\n const url = sanitizeHref(resolveHrefParams(href, params || {})).replace(/[{}]/g, brace =>\n brace === '{' ? '&#123;' : '&#125;'\n );\n placeholders[placeholderIndex] = `<a href=\"${url}\">${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 // Escape any remaining text that wasn't part of markdown\n result = escapeHtml(result);\n\n // Restore placeholders, newest first: an outer construct (`**[a](b)**`) holds the\n // placeholders created before it. A replacer function keeps `$&`, `$'` and `$$` in the\n // text literal (a replacement string would expand them).\n for (let i = placeholders.length - 1; i >= 0; i--) {\n result = result.replace(`__MARKDOWN_PLACEHOLDER_${i}__`, () => placeholders[i]);\n }\n\n return result;\n },\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,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxog/i18n",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "Modern, lightweight, and framework-agnostic internationalization library",
5
5
  "author": "Ersin Koç",
6
6
  "license": "MIT",