-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
i18nextFluent.min.js
1 lines (1 loc) · 11.6 KB
/
i18nextFluent.min.js
1
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).i18nextFluent=t()}(this,(function(){"use strict";function e(e,t,n){function r(e){return e&&e.indexOf("###")>-1?e.replace(/###/g,"."):e}function s(){return!e||"string"==typeof e}const i="string"!=typeof t?[].concat(t):t.split(".");for(;i.length>1;){if(s())return{};const t=r(i.shift());!e[t]&&n&&(e[t]=new n),e=e[t]}return s()?{}:{obj:e,k:r(i.shift())}}function t(t,n){const{obj:r,k:s}=e(t,n);if(r)return r[s]}let n=[],r=n.forEach,s=n.slice;class i{constructor(e,t){this.value=e,this.opts=t}valueOf(){return this.value}toString(){throw new Error("Subclasses of FluentType must implement toString.")}}class o extends i{valueOf(){return null}toString(){return`{${this.value||"???"}}`}}class u extends i{constructor(e,t){super(parseFloat(e),t)}toString(e){try{return e._memoizeIntlObject(Intl.NumberFormat,this.opts).format(this.value)}catch(e){return this.value}}}class a extends i{constructor(e,t){super(new Date(e),t)}toString(e){try{return e._memoizeIntlObject(Intl.DateTimeFormat,this.opts).format(this.value)}catch(e){return this.value}}}function c(e,t){return Object.assign({},e,function(e){const t={};for(const[n,r]of Object.entries(e))t[n]=r.valueOf();return t}(t))}var l=Object.freeze({__proto__:null,NUMBER:function([e],t){return e instanceof o?e:e instanceof u?new u(e.valueOf(),c(e.opts,t)):new o("NUMBER()")},DATETIME:function([e],t){return e instanceof o?e:e instanceof a?new a(e.valueOf(),c(e.opts,t)):new o("DATETIME()")}});const f=2500;function h(e,t,n){if(n===t)return!0;if(n instanceof u&&t instanceof u&&n.value===t.value)return!0;if(t instanceof u&&"string"==typeof n){if(n===e._memoizeIntlObject(Intl.PluralRules,t.opts).select(t.value))return!0}return!1}function p(e,t,n){return t[n]?g(e,t[n]):(e.errors.push(new RangeError("No default")),new o)}function d(e,t){const n=[],r={};for(const s of t)"narg"===s.type?r[s.name]=g(e,s.value):n.push(g(e,s));return[n,r]}function g(e,t){if("string"==typeof t)return e.bundle._transform(t);if(t instanceof o)return t;if(Array.isArray(t))return function(e,t){if(e.dirty.has(t))return e.errors.push(new RangeError("Cyclic reference")),new o;e.dirty.add(t);const n=[],r=e.bundle._useIsolating&&t.length>1;for(const s of t){if("string"==typeof s){n.push(e.bundle._transform(s));continue}const t=g(e,s).toString(e.bundle);r&&n.push(""),t.length>f?(e.errors.push(new RangeError(`Too many characters in placeable (${t.length}, max allowed is 2500)`)),n.push(t.slice(f))):n.push(t),r&&n.push("")}return e.dirty.delete(t),n.join("")}(e,t);switch(t.type){case"str":return t.value;case"num":return new u(t.value,{minimumFractionDigits:t.precision});case"var":return function(e,{name:t}){if(!e.args||!e.args.hasOwnProperty(t))return!1===e.insideTermReference&&e.errors.push(new ReferenceError(`Unknown variable: ${t}`)),new o(`$${t}`);const n=e.args[t];if(n instanceof i)return n;switch(typeof n){case"string":return n;case"number":return new u(n);case"object":if(n instanceof Date)return new a(n);default:return e.errors.push(new TypeError(`Unsupported variable type: ${t}, ${typeof n}`)),new o(`$${t}`)}}(e,t);case"mesg":return function(e,{name:t,attr:n}){const r=e.bundle._messages.get(t);if(!r){const n=new ReferenceError(`Unknown message: ${t}`);return e.errors.push(n),new o(t)}if(n){const s=r.attrs&&r.attrs[n];return s?g(e,s):(e.errors.push(new ReferenceError(`Unknown attribute: ${n}`)),new o(`${t}.${n}`))}return g(e,r)}(e,t);case"term":return function(e,{name:t,attr:n,args:r}){const s=`-${t}`,i=e.bundle._terms.get(s);if(!i){const t=new ReferenceError(`Unknown term: ${s}`);return e.errors.push(t),new o(s)}const[,u]=d(e,r),a={...e,args:u,insideTermReference:!0};if(n){const t=i.attrs&&i.attrs[n];return t?g(a,t):(e.errors.push(new ReferenceError(`Unknown attribute: ${n}`)),new o(`${s}.${n}`))}return g(a,i)}(e,t);case"func":return function(e,{name:t,args:n}){const r=e.bundle._functions[t]||l[t];if(!r)return e.errors.push(new ReferenceError(`Unknown function: ${t}()`)),new o(`${t}()`);if("function"!=typeof r)return e.errors.push(new TypeError(`Function ${t}() is not callable`)),new o(`${t}()`);try{return r(...d(e,n))}catch(e){return new o(`${t}()`)}}(e,t);case"select":return function(e,{selector:t,variants:n,star:r}){let s=g(e,t);if(s instanceof o){return g(e,p(e,n,r))}for(const t of n){const n=g(e,t.key);if(h(e.bundle,s,n))return g(e,t)}const i=p(e,n,r);return g(e,i)}(e,t);case void 0:return null!==t.value&&void 0!==t.value?g(e,t.value):(e.errors.push(new RangeError("No value")),new o);default:return new o}}class m extends Error{}const w=/^(-?[a-zA-Z][\w-]*) *= */gm,y=/\.([a-zA-Z][\w-]*) *= */y,v=/\*?\[/y,b=/(-?[0-9]+(?:\.([0-9]+))?)/y,x=/([a-zA-Z][\w-]*)/y,$=/([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y,E=/^[A-Z][A-Z0-9_-]*$/,_=/([^{}\n\r]+)/y,I=/([^\\"\n\r]*)/y,O=/\\([\\"])/y,j=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y,k=/^\n+/,R=/ +$/,A=/ *\r?\n/g,S=/( *)$/,F=/{\s*/y,M=/\s*}/y,T=/\[\s*/y,U=/\s*] */y,z=/\s*\(\s*/y,B=/\s*->\s*/y,Z=/\s*:\s*/y,D=/\s*,?\s*/y,N=/\s+/y;class P extends Map{static fromString(e){w.lastIndex=0;let t=new this,n=0;for(;;){let r=w.exec(e);if(null===r)break;n=w.lastIndex;try{t.set(r[1],a())}catch(e){if(e instanceof m)continue;throw e}}return t;function r(t){return t.lastIndex=n,t.test(e)}function s(t,r){if(e[n]===t)return n++,!0;if(r)throw new r(`Expected ${t}`);return!1}function i(e,t){if(r(e))return n=e.lastIndex,!0;if(t)throw new t(`Expected ${e.toString()}`);return!1}function o(t){t.lastIndex=n;let r=t.exec(e);if(null===r)throw new m(`Expected ${t.toString()}`);return n=t.lastIndex,r}function u(e){return o(e)[1]}function a(){let e=c(),t=function(){let e={};for(;r(y);){let t=u(y),n=c();if(null===n)throw new m("Expected attribute value");e[t]=n}return Object.keys(e).length>0?e:null}();if(null===t){if(null===e)throw new m("Expected message value or attributes");return e}return{value:e,attrs:t}}function c(){if(r(_))var t=u(_);if("{"===e[n]||"}"===e[n])return l(t?[t]:[],1/0);let s=C();return s?t?l([t,s],s.length):(s.value=q(s.value,k),l([s],s.length)):t?q(t,R):null}function l(t=[],s){let i=0;for(;;){if(r(_)){t.push(u(_));continue}if("{"===e[n]){if(++i>100)throw new m("Too many placeables");t.push(f());continue}if("}"===e[n])throw new m("Unbalanced closing brace");let o=C();if(!o)break;t.push(o),s=Math.min(s,o.length)}let o=t.length-1;"string"==typeof t[o]&&(t[o]=q(t[o],R));let a=[];for(let e of t)"indent"===e.type?e=e.value.slice(0,e.value.length-s):"str"===e.type&&(e=e.value),e&&a.push(e);return a}function f(){i(F,m);let e=h();if(i(M))return e;if(i(B)){let t=function(){let e,t=[],n=0;for(;r(v);){s("*")&&(e=n);let r=d(),i=c();if(null===i)throw new m("Expected variant value");t[n++]={key:r,value:i}}if(0===n)return null;if(void 0===e)throw new m("Expected default variant");return{variants:t,star:e}}();return i(M,m),{type:"select",selector:e,...t}}throw new m("Unclosed placeable")}function h(){if("{"===e[n])return f();if(r($)){let[,t,r,s=null]=o($);if("$"===t)return{type:"var",name:r};if(i(z)){let o=function(){let t=[];for(;;){switch(e[n]){case")":return n++,t;case void 0:throw new m("Unclosed argument list")}t.push(p()),i(D)}}();if("-"===t)return{type:"term",name:r,attr:s,args:o};if(E.test(r))return{type:"func",name:r,args:o};throw new m("Function names must be all upper-case")}return"-"===t?{type:"term",name:r,attr:s,args:[]}:{type:"mesg",name:r,attr:s}}return g()}function p(){let e=h();return"mesg"!==e.type?e:i(Z)?{type:"narg",name:e.name,value:g()}:e}function d(){i(T,m);let e=r(b)?P():u(x);return i(U,m),e}function g(){if(r(b))return P();if('"'===e[n])return function(){s('"',m);let t="";for(;;){if(t+=u(I),"\\"!==e[n]){if(s('"'))return{type:"str",value:t};throw new m("Unclosed string literal")}t+=W()}}();throw new m("Invalid expression")}function P(){let[,e,t=""]=o(b),n=t.length;return{type:"num",value:parseFloat(e),precision:n}}function W(){if(r(O))return u(O);if(r(j)){let[,e,t]=o(j),n=parseInt(e||t,16);return n<=55295||57344<=n?String.fromCodePoint(n):"�"}throw new m("Unknown escape sequence")}function C(){let t=n;switch(i(N),e[n]){case".":case"[":case"*":case"}":case void 0:return!1;case"{":return J(e.slice(t,n))}return" "===e[n-1]&&J(e.slice(t,n))}function q(e,t){return e.replace(t,"")}function J(e){return{type:"indent",value:e.replace(A,"\n"),length:S.exec(e)[1].length}}}}class W{constructor(e,{functions:t={},useIsolating:n=!0,transform:r=(e=>e)}={}){this.locales=Array.isArray(e)?e:[e],this._terms=new Map,this._messages=new Map,this._functions=t,this._useIsolating=n,this._transform=r,this._intls=new WeakMap}get messages(){return this._messages[Symbol.iterator]()}hasMessage(e){return this._messages.has(e)}getMessage(e){return this._messages.get(e)}addMessages(e,t){const n=P.fromString(e);return this.addResource(n,t)}addResource(e,{allowOverrides:t=!1}={}){const n=[];for(const[r,s]of e)if(r.startsWith("-")){if(!1===t&&this._terms.has(r)){n.push(`Attempt to override an existing term: "${r}"`);continue}this._terms.set(r,s)}else{if(!1===t&&this._messages.has(r)){n.push(`Attempt to override an existing message: "${r}"`);continue}this._messages.set(r,s)}return n}format(e,t,n){return"string"==typeof e?this._transform(e):null===e||null===e.value?null:"string"==typeof e.value?this._transform(e.value):function(e,t,n,r=[]){return g({bundle:e,args:t,errors:r,dirty:new WeakSet,insideTermReference:!1},n).toString(e)}(this,t,e,n)}_memoizeIntlObject(e,t){const n=this._intls.get(e)||{},r=JSON.stringify(t);return n[r]||(n[r]=new e(this.locales,t),this._intls.set(e,n)),n[r]}}function C(e,t){var n="";return n=n+e+" =",t&&t.indexOf("\n")>-1?(n+="\n ",n+=t.split("\n").join("\n ")):n=n+" "+t,n}function q(e){return!/^\s*$/.test(e)}function J(e){const[t]=e.match(/^\s*/);return t.length}class K{constructor(e,t){this.i18next=e,this.options=t,this.bundles={}}createBundle(t,n,r){const s=r?function(e,t){var n="";return Object.keys(e).forEach((function(t){var r=e[t];"string"==typeof r?(n+=C(t,r),n+="\n\n"):(r.comment&&(n+=function(e){var t="";return(t=t+"# "+e.split("\n").join("\n# "))+"\n"}(r.comment)),n+=C(t,r.val),Object.keys(r).forEach((function(e){if("comment"!==e&&"val"!==e){var t=r[e];n+=C("\n ."+e,t)}})),n+="\n\n")})),t&&t(null,n),n}(r):"",i=new W(t,this.options.fluentBundleOptions);i.addMessages(function(e){const t=e.split("\n").filter(q),n=t.map(J),r=Math.min(...n),s=new RegExp(`^\\s{${r}}`);return t.map((e=>e.replace(s,""))).join("\n")}(s)),function(t,n,r){const{obj:s,k:i}=e(t,n,Object);s[i]=r}(this.bundles,[t,n],i)}createBundleFromI18next(e,n){this.createBundle(e,n,t(this.i18next.store.data,[e,n]))}getBundle(e,n){return t(this.bundles,[e,n])}bind(){this.i18next.store.on("added",((e,t)=>{this.i18next.isInitialized&&this.createBundleFromI18next(e,t)})),this.i18next.on("initialized",(()=>{var e=this.i18next.languages||[],t=this.i18next.options.preload||[];e.filter((e=>!t.includes(e))).concat(t).forEach((e=>{this.i18next.options.ns.forEach((t=>{this.createBundleFromI18next(e,t)}))}))}))}}class L{constructor(e){this.type="i18nFormat",this.handleAsObject=!1,this.init(null,e)}init(e,t){const n=e&&e.options&&e.options.i18nFormat||{};this.options=function(e){return r.call(s.call(arguments,1),(function(t){if(t)for(var n in t)void 0===e[n]&&(e[n]=t[n])})),e}(n,t,this.options||{},{bindI18nStore:!0,fluentBundleOptions:{useIsolating:!1}}),e?(this.store=new K(e,this.options),this.options.bindI18nStore&&this.store.bind(),e.fluent=this):this.store=new K(null,this.options)}parse(e,t,n,r,s,i){const o=this.store.getBundle(n,r),u=s.indexOf(".")>-1;if(!e)return s;const a=u?e.attrs[s.split(".")[1]]:e;return o?o.format(a,t):s}getResource(e,t,n,r){let s=this.store.getBundle(e,t);const i=n.indexOf(".")>-1?n.split(".")[0]:n;if(s)return s.getMessage(i)}addLookupKeys(e,t,n,r,s){return e}}return L.type="i18nFormat",L}));