@lionrapid/core 0.6.6 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/browser/auto-init.d.ts +6 -0
- package/dist/browser/auto-init.d.ts.map +1 -1
- package/dist/browser/auto-init.js +36 -6
- package/dist/browser/auto-init.js.map +1 -1
- package/dist/browser/language-switcher.d.ts +12 -0
- package/dist/browser/language-switcher.d.ts.map +1 -1
- package/dist/browser/language-switcher.js +58 -0
- package/dist/browser/language-switcher.js.map +1 -1
- package/dist/browser/lionrapid.auto.dev.js +163 -14
- package/dist/browser/lionrapid.auto.dev.js.map +3 -3
- package/dist/browser/lionrapid.auto.js +163 -14
- package/dist/browser/lionrapid.auto.js.map +3 -3
- package/dist/browser/lionrapid.auto.min.js +5 -5
- package/dist/browser/lionrapid.auto.min.js.map +4 -4
- package/dist/browser/lionrapid.esm.js +103 -10
- package/dist/browser/lionrapid.esm.js.map +2 -2
- package/dist/browser/lionrapid.esm.min.js +4 -4
- package/dist/browser/lionrapid.esm.min.js.map +3 -3
- package/dist/browser/lionrapid.iife.dev.js +103 -10
- package/dist/browser/lionrapid.iife.dev.js.map +2 -2
- package/dist/browser/lionrapid.iife.js +103 -10
- package/dist/browser/lionrapid.iife.js.map +2 -2
- package/dist/browser/lionrapid.iife.min.js +4 -4
- package/dist/browser/lionrapid.iife.min.js.map +3 -3
- package/dist/browser/lionrapid.umd.js +103 -10
- package/dist/browser/lionrapid.umd.js.map +2 -2
- package/dist/browser/lionrapid.umd.min.js +4 -4
- package/dist/browser/lionrapid.umd.min.js.map +3 -3
- package/dist/browser/storage/cache-storage-repository.d.ts +9 -0
- package/dist/browser/storage/cache-storage-repository.d.ts.map +1 -1
- package/dist/browser/storage/cache-storage-repository.js +14 -10
- package/dist/browser/storage/cache-storage-repository.js.map +1 -1
- package/dist/browser/storage/scope.d.ts +12 -0
- package/dist/browser/storage/scope.d.ts.map +1 -0
- package/dist/browser/storage/scope.js +15 -0
- package/dist/browser/storage/scope.js.map +1 -0
- package/dist/builder.d.ts.map +1 -1
- package/dist/builder.js +9 -0
- package/dist/builder.js.map +1 -1
- package/dist/handlers/async-storage-handler.d.ts +9 -0
- package/dist/handlers/async-storage-handler.d.ts.map +1 -1
- package/dist/handlers/async-storage-handler.js +42 -0
- package/dist/handlers/async-storage-handler.js.map +1 -1
- package/dist/handlers/handler-chain.d.ts +2 -0
- package/dist/handlers/handler-chain.d.ts.map +1 -1
- package/dist/handlers/handler-chain.js +29 -0
- package/dist/handlers/handler-chain.js.map +1 -1
- package/dist/handlers/sync-storage-handler.d.ts +4 -0
- package/dist/handlers/sync-storage-handler.d.ts.map +1 -1
- package/dist/handlers/sync-storage-handler.js +35 -0
- package/dist/handlers/sync-storage-handler.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/interfaces/handler.interface.d.ts +4 -0
- package/dist/interfaces/handler.interface.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var __lionrapidAutoExports=(()=>{var
|
|
1
|
+
"use strict";var __lionrapidAutoExports=(()=>{var ie=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var mt=Object.prototype.hasOwnProperty;var ht=(a,e,t)=>e in a?ie(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var ft=(a,e)=>{for(var t in e)ie(a,t,{get:e[t],enumerable:!0})},yt=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gt(e))!mt.call(a,r)&&r!==t&&ie(a,r,{get:()=>e[r],enumerable:!(n=pt(e,r))||n.enumerable});return a};var bt=a=>yt(ie({},"__esModule",{value:!0}),a);var d=(a,e,t)=>ht(a,typeof e!="symbol"?e+"":e,t);var Rn={};ft(Rn,{AttributeExtractor:()=>Q,AutoTranslator:()=>Z,BlockExtractor:()=>X,CacheStorageRepository:()=>j,DOMObserver:()=>Y,ExcludeFilter:()=>K,LanguageSwitcher:()=>q,LionRapidBuilder:()=>W,LionRapidCore:()=>V,LocalStorageRepository:()=>te,MemoryRepository:()=>O,NetworkRepository:()=>J,autoInit:()=>De,generateAutoKey:()=>$,md5:()=>M,parseBlockElement:()=>H,parseConfig:()=>Ue});function P(a,e){let t=(a&65535)+(e&65535);return(a>>16)+(e>>16)+(t>>16)<<16|t&65535}function vt(a,e){return a<<e|a>>>32-e}function oe(a,e,t,n,r,s){return P(vt(P(P(e,a),P(n,s)),r),t)}function E(a,e,t,n,r,s,i){return oe(e&t|~e&n,a,e,r,s,i)}function C(a,e,t,n,r,s,i){return oe(e&n|t&~n,a,e,r,s,i)}function R(a,e,t,n,r,s,i){return oe(e^t^n,a,e,r,s,i)}function S(a,e,t,n,r,s,i){return oe(t^(e|~n),a,e,r,s,i)}function wt(a,e){a[e>>5]|=128<<e%32,a[(e+64>>>9<<4)+14]=e;let t=1732584193,n=-271733879,r=-1732584194,s=271733878;for(let i=0;i<a.length;i+=16){let o=t,l=n,u=r,p=s;t=E(t,n,r,s,a[i],7,-680876936),s=E(s,t,n,r,a[i+1],12,-389564586),r=E(r,s,t,n,a[i+2],17,606105819),n=E(n,r,s,t,a[i+3],22,-1044525330),t=E(t,n,r,s,a[i+4],7,-176418897),s=E(s,t,n,r,a[i+5],12,1200080426),r=E(r,s,t,n,a[i+6],17,-1473231341),n=E(n,r,s,t,a[i+7],22,-45705983),t=E(t,n,r,s,a[i+8],7,1770035416),s=E(s,t,n,r,a[i+9],12,-1958414417),r=E(r,s,t,n,a[i+10],17,-42063),n=E(n,r,s,t,a[i+11],22,-1990404162),t=E(t,n,r,s,a[i+12],7,1804603682),s=E(s,t,n,r,a[i+13],12,-40341101),r=E(r,s,t,n,a[i+14],17,-1502002290),n=E(n,r,s,t,a[i+15],22,1236535329),t=C(t,n,r,s,a[i+1],5,-165796510),s=C(s,t,n,r,a[i+6],9,-1069501632),r=C(r,s,t,n,a[i+11],14,643717713),n=C(n,r,s,t,a[i],20,-373897302),t=C(t,n,r,s,a[i+5],5,-701558691),s=C(s,t,n,r,a[i+10],9,38016083),r=C(r,s,t,n,a[i+15],14,-660478335),n=C(n,r,s,t,a[i+4],20,-405537848),t=C(t,n,r,s,a[i+9],5,568446438),s=C(s,t,n,r,a[i+14],9,-1019803690),r=C(r,s,t,n,a[i+3],14,-187363961),n=C(n,r,s,t,a[i+8],20,1163531501),t=C(t,n,r,s,a[i+13],5,-1444681467),s=C(s,t,n,r,a[i+2],9,-51403784),r=C(r,s,t,n,a[i+7],14,1735328473),n=C(n,r,s,t,a[i+12],20,-1926607734),t=R(t,n,r,s,a[i+5],4,-378558),s=R(s,t,n,r,a[i+8],11,-2022574463),r=R(r,s,t,n,a[i+11],16,1839030562),n=R(n,r,s,t,a[i+14],23,-35309556),t=R(t,n,r,s,a[i+1],4,-1530992060),s=R(s,t,n,r,a[i+4],11,1272893353),r=R(r,s,t,n,a[i+7],16,-155497632),n=R(n,r,s,t,a[i+10],23,-1094730640),t=R(t,n,r,s,a[i+13],4,681279174),s=R(s,t,n,r,a[i+0],11,-358537222),r=R(r,s,t,n,a[i+3],16,-722521979),n=R(n,r,s,t,a[i+6],23,76029189),t=R(t,n,r,s,a[i+9],4,-640364487),s=R(s,t,n,r,a[i+12],11,-421815835),r=R(r,s,t,n,a[i+15],16,530742520),n=R(n,r,s,t,a[i+2],23,-995338651),t=S(t,n,r,s,a[i],6,-198630844),s=S(s,t,n,r,a[i+7],10,1126891415),r=S(r,s,t,n,a[i+14],15,-1416354905),n=S(n,r,s,t,a[i+5],21,-57434055),t=S(t,n,r,s,a[i+12],6,1700485571),s=S(s,t,n,r,a[i+3],10,-1894986606),r=S(r,s,t,n,a[i+10],15,-1051523),n=S(n,r,s,t,a[i+1],21,-2054922799),t=S(t,n,r,s,a[i+8],6,1873313359),s=S(s,t,n,r,a[i+15],10,-30611744),r=S(r,s,t,n,a[i+6],15,-1560198380),n=S(n,r,s,t,a[i+13],21,1309151649),t=S(t,n,r,s,a[i+4],6,-145523070),s=S(s,t,n,r,a[i+11],10,-1120210379),r=S(r,s,t,n,a[i+2],15,718787259),n=S(n,r,s,t,a[i+9],21,-343485551),t=P(t,o),n=P(n,l),r=P(r,u),s=P(s,p)}return[t,n,r,s]}function Et(a){let e="0123456789abcdef",t="";for(let n=0;n<a.length*4;n++)t+=e.charAt(a[n>>2]>>n%4*8+4&15)+e.charAt(a[n>>2]>>n%4*8&15);return t}function Ct(a){if(typeof TextEncoder<"u")return new TextEncoder().encode(a);let e=[];for(let t=0;t<a.length;t++){let n=a.charCodeAt(t);if(n<128)e.push(n);else if(n<2048)e.push(192|n>>6,128|n&63);else if(n>=55296&&n<56320&&t+1<a.length){let r=a.charCodeAt(++t),s=65536+(n-55296<<10)+(r-56320);e.push(240|s>>18,128|s>>12&63,128|s>>6&63,128|s&63)}else e.push(224|n>>12,128|n>>6&63,128|n&63)}return new Uint8Array(e)}function Rt(a){let e=[];for(let t=0;t<a.length;t++)e[t>>2]|=a[t]<<t%4*8;return e}function M(a){let e=Ct(a);return Et(wt(Rt(e),e.length*8))}function $(a){let e=a.trim();return"auto_"+M(e).substring(0,12)}var St=200,_e=90;function xt(a){return`${a.length} chars, md5:${M(a.trim()).slice(0,12)}`}function Tt(a){return a.length<=St?JSON.stringify(a):JSON.stringify(`${a.slice(0,_e)}\u2026${a.slice(-_e)}`)}var Be=200,kt=500,Nt=2,Lt=120;function le(a,e){return a.length<=e?a:`${a.slice(0,e)}\u2026 (${a.length} chars)`}function Te(a){return JSON.stringify(a).slice(1,-1)}function ce(a){if(a instanceof Error){let e=a.name||"Error";return le(Te(`${e}: ${a.message}`),Be)}return le(Te(String(a)),Be)}function ke(a){if(a instanceof Error){let t=String(a.message??"").split(`
|
|
2
2
|
`).length,n=(a.stack??"").split(`
|
|
3
|
-
`).slice(t).map(r=>r.trim()).filter(r=>r.startsWith("at ")).slice(0,
|
|
4
|
-
`);for(let n=3;n<t.length;n++){let r=t[n];if(r&&!r.includes("logger.ts")&&!r.includes("Logger"))return this.parseStackLine(r)}}catch{}return null}parseStackLine(e){let t=e.match(/at\s+(.+?)\s+\((.+):(\d+):(\d+)\)/);return t?{functionName:t[1],fileName:this.extractFileName(t[2]),lineNumber:parseInt(t[3],10)}:(t=e.match(/at\s+(.+):(\d+):(\d+)/),t?{fileName:this.extractFileName(t[1]),lineNumber:parseInt(t[2],10)}:null)}extractFileName(e){let t=e.split("/");return t[t.length-1]||e}colorize(e,t){return this.config.useColors?`${v[t]}${e}${v.RESET}`:e}getColors(){return v}createPackageLogger(e,t){return new a({...this.config,packageName:e,packageEmoji:t||"\u{1F4E6}"})}getLogLevelFromEnv(){switch(ze.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":return 2;case"ERROR":return 3;case"NONE":return 4;default:return 2}}shouldEnableLogging(){return ze!=="NONE"}shouldUseColors(){return Fe?!1:typeof window<"u"?!0:(typeof process<"u",$e)}},M=()=>{},Ge=()=>()=>{},l=Ve?{configure:M,debug:M,info:M,warn:(a,e)=>{console.warn(`\u{1F981} LionRapid Core \u26A0\uFE0F ${a}`,e||"")},error:(a,e)=>{console.error(`\u{1F981} LionRapid Core \u274C ${a}`,e||"")},time:Ge,colorize:a=>a,getColors:()=>v,createPackageLogger:(a,e)=>({configure:M,debug:M,info:M,warn:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${a}`;console.warn(`${r} \u26A0\uFE0F ${t}`,n||"")},error:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${a}`;console.error(`${r} \u274C ${t}`,n||"")},time:Ge,colorize:t=>t,getColors:()=>v,createPackageLogger:M})}:new Ae({packageName:"LionRapid Core",packageEmoji:"\u{1F981}"});var We=/^[a-z]{2,3}(?:-[a-z0-9]{2,4})*$/i,Nt=new Set(["ar","fa","he","ur","yi"]);function $t(a){return a.split("-")[0].toLowerCase()}function Ie(a){let e=a.trim();if(!e)return e;let[t,...n]=e.split("-"),r=[t.toLowerCase()];for(let s of n)s.length===4?r.push(s[0].toUpperCase()+s.slice(1).toLowerCase()):s.length===2?r.push(s.toUpperCase()):r.push(s.toLowerCase());return r.join("-")}var At=Object.freeze({ara:"ar",ben:"bn",bul:"bg",ces:"cs",cmn:"zh",dan:"da",deu:"de",ell:"el",eng:"en",est:"et",fas:"fa",fin:"fi",fra:"fr",heb:"he",hin:"hi",hrv:"hr",hun:"hu",ind:"id",isl:"is",ita:"it",jpn:"ja",kor:"ko",lav:"lv",lit:"lt",msa:"ms",nld:"nl",nor:"no",pol:"pl",por:"pt",ron:"ro",rus:"ru",slk:"sk",slv:"sl",spa:"es",srp:"sr",swe:"sv",tha:"th",tur:"tr",ukr:"uk",urd:"ur",vie:"vi",yid:"yi",zho:"zh"});function It(a){let e=a.trim().toLowerCase();if(!e)return[];let t=e.split("-"),n=[];for(;t.length>0;){let r=t.join("-");n.includes(r)||n.push(r);let s=At[r];s&&!n.includes(s)&&n.push(s),t.pop()}return n}function de(a,e,t){if(e.length===0)return t;let n=e.map(r=>({raw:r,lower:Ie(r).toLowerCase()}));for(let r of a)if(r)for(let s of It(r)){let i=n.find(o=>o.lower===s);if(i)return i.raw}return t}function pe(a){return Nt.has($t(a))?"rtl":"ltr"}var ge=class{constructor(){d(this,"eventListeners",new Map);d(this,"debugMode",typeof process<"u"&&!1)}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}off(e,t){let n=this.eventListeners.get(e);n&&n.delete(t)}emit(e,t){let n=this.eventListeners.get(e);n&&n.forEach(r=>{try{r(t)}catch(s){console.error(`Error in event listener for ${String(e)}:`,s)}})}hasListeners(e){return this.eventListeners.has(e)&&this.eventListeners.get(e).size>0}clearEvents(){this.eventListeners.clear()}createContext(e,t,n){return{requestId:e,timestamp:performance.now(),trace:t,...n}}emitEvent(e,t,n,r){this.emit(e,{context:this.createContext(n,r),payload:t})}translation(e,t){let n=["translation"],r=t?[...n,t]:n;return{request:()=>{this.emit("translation:request",{context:this.createContext(e.id,[...n,"request"]),payload:{key:e.cleanKey}})},success:s=>{this.emit("translation:success",{context:this.createContext(e.id,[...r,"success"]),payload:{key:e.cleanKey,value:s}})},fallback:s=>{this.emit("translation:fallback",{context:this.createContext(e.id,[...n,"fallback"]),payload:{key:e.cleanKey,value:s}})},missing:(s,i,o)=>{this.emit("translation:missing",{context:this.createContext(e.id,[...n,"missing"]),payload:{key:e.cleanKey,fallbackValue:s,locale:i,namespace:o}})},notFound:(s,i,o)=>{this.emit("translation:not-found",{context:this.createContext(e.id,[...n,"not-found"]),payload:{key:e.cleanKey,fallbackValue:s,locale:i,namespace:o,status:404}})},locked:(s,i,o)=>{this.emit("translation:locked",{context:this.createContext(e.id,[...n,"locked"]),payload:{key:e.cleanKey,fallbackValue:s,locale:i,namespace:o,status:423}})}}}repo(e,t){let n=["repo",t];return{getStart:()=>{typeof e!="string"&&this.emit("repo:get:start",{context:this.createContext(e.id,[...n,"get","start"]),payload:{key:e.cleanKey,source:t}})},getSuccess:r=>{typeof e!="string"&&this.emit("repo:get:success",{context:this.createContext(e.id,[...n,"get","success"]),payload:{key:e.cleanKey,value:r,source:t}})},getMiss:()=>{typeof e!="string"&&this.emit("repo:get:miss",{context:this.createContext(e.id,[...n,"get","miss"]),payload:{key:e.cleanKey,source:t}})},setStart:r=>{typeof e!="string"&&this.emit("repo:set:start",{context:this.createContext(e.id,[...n,"set","start"]),payload:{key:e.cleanKey,value:r,source:t}})},setSuccess:r=>{let s=typeof e=="string"?"system":e.id,i=typeof e=="string"?e:e.cleanKey;this.emit("repo:set:success",{context:this.createContext(s,[...n,"set","success"]),payload:{key:i,value:r,source:t}})},error:r=>{typeof e!="string"&&this.emit("repo:error",{context:this.createContext(e.id,[...n,"error"]),payload:{key:e.cleanKey,source:t,error:r}})}}}network(e,t){let n=typeof e=="string"?e:e.cleanKey,r=typeof e=="string"?"network":e.id,s=["network",t||"request"];return{start:()=>{this.emit("network:request:start",{context:this.createContext(r,[...s,"start"]),payload:{key:n}})},success:i=>{this.emit("network:request:success",{context:this.createContext(r,[...s,"success"]),payload:{key:n,value:i,method:t||"GET"}})},error:(i,o)=>{this.emit("network:request:error",{context:this.createContext(r,[...s,"error"]),payload:{key:n,method:t||"GET",error:i,...o&&{status:o}}})},retry:(i,o,c)=>{this.emit("network:retry",{context:this.createContext(r,[...s,"retry"]),payload:{key:n,attempt:i,delayMs:o,...c&&{reason:c}}})}}}builder(){let e=["builder"],t=`build-${Date.now()}`;return{use:n=>{this.emit("builder:use",{context:this.createContext(t,[...e,"use"]),payload:{type:n}})},buildStart:(n,r)=>{this.emit("builder:build:start",{context:this.createContext(t,[...e,"build","start"]),payload:{locale:n,namespace:r}})},buildDone:(n,r)=>{this.emit("builder:build:done",{context:this.createContext(t,[...e,"build","done"]),payload:{repositories:n,plugins:r}})}}}language(e,t){let n=`lang-change-${Date.now()}`,r=["language","change"];return{start:()=>{this.emit("language:change:start",{context:this.createContext(n,[...r,"start"]),payload:{oldLocale:e,newLocale:t}})},complete:()=>{this.emit("language:change:success",{context:this.createContext(n,[...r,"complete"]),payload:{oldLocale:e,newLocale:t,dir:pe(t)}})},error:s=>{this.emit("language:change:error",{context:this.createContext(n,[...r,"error"]),payload:{oldLocale:e,newLocale:t,error:s}})}}}cache(e,t,n){return this.debugMode?{start:()=>{l.debug(`\u{1F9F9} Cache ${e} starting: ${t}`)},complete:()=>{l.debug(`\u2705 Cache ${e} complete: ${n?.clearedCount||0} entries`)}}:{start:()=>{},complete:()=>{}}}};var me=class{constructor(e){d(this,"asyncHandlers",[]);d(this,"syncHandlers",[]);d(this,"bus");this.bus=e}addSyncHandler(e){e.enabled&&(this.syncHandlers.push(e),this.sortHandlersIfNeeded(this.syncHandlers),l.debug(`Sync handler added: ${e.name}`))}handleSync(e){for(let t of this.syncHandlers)try{let n=t.lookup(e);if(n!==null&&n.value)return l.debug(`Sync hit: ${t.name} (${n.duration}ms)`),n}catch(n){l.warn(`Sync lookup failed in ${t.name}:`,n),this.bus.repo(e,t.name).error(n);continue}return null}saveToMemoryHandlers(e,t,n){let r=this.syncHandlers;r.length!==0&&(l.debug(`Saving to ${r.length} memory handlers`),r.forEach(s=>{try{s.save(e,t),l.debug(`Saved to memory: ${s.name}`)}catch(i){l.warn(`Failed to save to memory ${s.name}:`,i),this.bus.repo(e,s.name).error(i)}}))}saveNamespaceToMemoryHandlers(e,t){let n=this.syncHandlers.filter(r=>r.type==="memory"&&r.saveNamespace);n.length!==0&&(l.debug(`Saving namespace to ${n.length} memory handlers`),n.forEach(r=>{try{r.saveNamespace(e,t),l.debug(`Namespace saved to memory: ${r.name}`,{locale:t.locale,namespace:t.namespace})}catch(s){l.warn(`Failed to save namespace to memory ${r.name}:`,s),this.bus.repo(`${t.locale}:${t.namespace}`,r.name).error(s)}}))}addAsyncHandler(e){e.enabled&&(this.asyncHandlers.push(e),this.sortHandlersIfNeeded(this.asyncHandlers),l.debug(`Async handler added: ${e.name}`))}async handleAsync(e){for(let t of this.asyncHandlers)try{l.debug(`Trying handler: ${t.name}`);let n=await t.lookup(e);if(n.value&&n.status===200)return l.debug(`Async hit: ${t.name} (${n.duration}ms)`),n.namespaceLoaded?(l.debug(`Saving loaded namespace: ${n.namespaceLoaded.locale}:${n.namespaceLoaded.namespace}`),await this.saveNamespaceToHandlers(n.namespaceLoaded.data,{locale:n.namespaceLoaded.locale,namespace:n.namespaceLoaded.namespace}),n):(await this.saveToStorageHandlers(e,n,t),this.saveToMemoryHandlers(e,n,t),n);l.debug(`Handler ${t.name} returned fallback (status: ${n.status})`)}catch(n){l.warn(`Handler ${t.name} failed:`,n),this.bus.repo(e,t.name).error(n);continue}return l.debug(`No async handlers found translation for ${e.cleanKey}`),null}async saveToStorageHandlers(e,t,n){let r=this.asyncHandlers.indexOf(n),s=this.asyncHandlers.slice(0,r).filter(o=>o.type==="storage");if(s.length===0)return;l.debug(`Saving to ${s.length} storage handlers`);let i=s.map(async o=>{try{await o.save(e,t),l.debug(`Saved to storage: ${o.name}`)}catch(c){l.warn(`Failed to save to storage ${o.name}:`,c),this.bus.repo(e,o.name).error(c)}});await Promise.allSettled(i)}async saveNamespaceToStorageHandlers(e,t){let n=this.asyncHandlers.filter(s=>s.type==="storage"&&s.saveNamespace);if(n.length===0)return;l.debug(`Saving namespace to ${n.length} storage handlers`);let r=n.map(async s=>{try{await s.saveNamespace(e,t),l.debug(`Namespace saved to storage: ${s.name}`,{locale:t.locale,namespace:t.namespace})}catch(i){l.warn(`Failed to save namespace to storage ${s.name}:`,i),this.bus.repo(`${t.locale}:${t.namespace}`,s.name).error(i)}});await Promise.allSettled(r)}async saveNamespaceToHandlers(e,t){this.saveNamespaceToMemoryHandlers(e,t),await this.saveNamespaceToStorageHandlers(e,t)}getSyncHandlers(){return[...this.syncHandlers]}getAsyncHandlers(){return[...this.asyncHandlers]}getChainInfo(){return{length:this.syncHandlers.length+this.asyncHandlers.length,handlers:[...this.syncHandlers.map(e=>({name:e.name,priority:e.priority,type:e.type,enabled:e.enabled})),...this.asyncHandlers.map(e=>({name:e.name,priority:e.priority,type:e.type,enabled:e.enabled}))]}}isCached(e){return this.syncHandlers.some(t=>t.isCached?.(e)===!0)||this.asyncHandlers.some(t=>t.isCached?.(e)===!0)}getEntries(){let e={},t=[...this.syncHandlers,...this.asyncHandlers];for(let n of t)n.getEntries&&(e[n.name]=n.getEntries());return e}async destroy(){let t=[...this.syncHandlers,...this.asyncHandlers].map(async n=>{try{await n.destroy?.(),l.debug(`Handler destroyed: ${n.name}`)}catch(r){l.warn(`Failed to destroy handler: ${n.name}`,r)}});await Promise.allSettled(t),this.syncHandlers=[],this.asyncHandlers=[]}sortHandlersIfNeeded(e){e.some(n=>n.priority>0)&&e.sort((n,r)=>{let s=n.priority||Number.MAX_SAFE_INTEGER,i=r.priority||Number.MAX_SAFE_INTEGER;return s-i})}async loadNamespace(e,t){for(let n of this.asyncHandlers)if(n.type==="network")try{l.debug(`Trying to load namespace: ${e}:${t} from ${n.name}`);let r=await n.loadNamespace?.(e,t);if(r&&r.data&&r.status===200)return l.debug(`Loaded namespace: ${e}:${t} from ${n.name}`),await this.saveNamespaceToStorageHandlers(r.data,{namespace:t,locale:e}),this.saveNamespaceToMemoryHandlers(r.data,{namespace:t,locale:e}),r.data}catch(r){l.warn(`Failed to load namespace: ${e}:${t} from ${n.name}`,r),this.bus.repo(`${e}:${t}`,n.name).error(r);continue}return l.debug(`No handlers found namespace: ${e}:${t}`),null}clearCache(){let e=[...this.syncHandlers,...this.asyncHandlers];for(let t of e)try{t.destroy?.(),l.debug(`Cache cleared for handler: ${t.name}`)}catch(n){l.warn(`Failed to clear cache for handler: ${t.name}`,n)}l.debug("Cache cleared for all handlers")}clearNamespace(e,t){for(let n of this.syncHandlers)try{n.clearNamespace?.(e,t)}catch(r){l.warn(`Failed to clear namespace for handler: ${n.name}`,r)}l.debug(`Cleared namespace: ${e}:${t}`)}setCache(e,t,n){for(let r of this.syncHandlers)if(r.type==="memory"&&r.setCache)try{r.setCache(e,t,n)}catch(s){l.warn(`Failed to set cache in handler: ${r.name}`,s)}l.debug(`Cache set: ${e}`)}getNamespaceData(e){for(let t of this.syncHandlers)if(t.type==="memory")try{let n=t.getEntries?.();if(n&&n[e]){let r=n[e];return typeof r=="string"?JSON.parse(r):r}}catch(n){l.debug(`Error getting namespace data from ${t.name}:`,n)}return null}};function Je(a){let e=a.indexOf(":");if(e>0&&e<a.length-1){let t=a.substring(0,e),n=a.substring(e+1);return{originalKey:a,namespace:t,cleanKey:n,hasExplicitNamespace:!0}}return{originalKey:a,cleanKey:a,hasExplicitNamespace:!1}}function Xe(a,e,t){let n=a.hasExplicitNamespace?a.namespace:t;return{locale:e,namespace:n}}function P(a,e){if(!(!a||!e)){if(!e.includes(".")&&!e.includes("["))return a[e];try{let t=Pt(e),n=a;for(let r of t){if(n==null){l.debug(`\u{1F50D} Nested key resolution stopped at null/undefined for: ${e}`);return}if(typeof r=="number"){if(!Array.isArray(n)){l.debug(`\u{1F50D} Expected array for index ${r} in path: ${e}`);return}n=n[r]}else{if(typeof n!="object"){l.debug(`\u{1F50D} Expected object for key '${r}' in path: ${e}`);return}n=n[r]}}return l.debug(`\u{1F50D} Nested key resolved: ${e} \u2192 ${typeof n=="object"?"[Object]":n}`),n}catch(t){l.debug(`\u{1F50D} Nested key resolution error for '${e}':`,t);return}}}function Pt(a){let e=[],t="",n=!1;for(let r=0;r<a.length;r++){let s=a[r];if(s==="."&&!n)t&&(e.push(t),t="");else if(s==="[")t&&(e.push(t),t=""),n=!0;else if(s==="]"&&n){if(t){let i=parseInt(t,10);isNaN(i)?e.push(t):e.push(i),t=""}n=!1}else t+=s}return t&&e.push(t),e}function he(a,e,t){let n=[a];return e&&n.push(e),n.push(t),n.join(":")}function S(a,e){return`@${a}:${e}`}function D(a,e="",t,n){let r={};for(let[s,i]of Object.entries(a)){let o=e?`${e}.${s}`:s,c=he(t,n,o);typeof i=="object"&&i!==null&&"text"in i&&"styles"in i?r[c]=JSON.stringify(i):typeof i=="object"&&i!==null?Object.assign(r,D(i,o,t,n)):r[c]=JSON.stringify({text:String(i),styles:{}})}return r}function se(a,e,t,n,r){let s=performance.now(),{defaultValue:i,params:o}=Ot(t,n),c=Je(a),u=Xe(c,e,r),p=he(u.locale,u.namespace,c.cleanKey),m=u.namespace?S(u.locale,u.namespace):void 0;return{id:`${p}-${s}`,originalKey:a,originalParams:t,originalDefaultValue:n,cleanKey:c.cleanKey,hasExplicitNamespace:c.hasExplicitNamespace,parsedParams:o,parsedDefaultValue:i,locale:e,namespace:u.namespace,individualCacheKey:p,namespaceCacheKey:m,startTime:s}}function Ot(a,e){let t,n;return typeof a=="object"&&typeof e=="object"&&(typeof process>"u"||!1)&&console.warn("[LionRapid] Warning: Both secondParam and thirdParam are objects. Expected pattern: t(key, params, defaultValue) or t(key, defaultValue, params). Second object will be ignored as it cannot be a defaultValue."),typeof a=="string"?(t=a,typeof e=="object"&&(n=e)):typeof a=="object"&&(n=a,typeof e=="string"&&(t=e)),{defaultValue:t,params:n}}var fe=class{constructor(e,t){d(this,"name");d(this,"version","1.0.0");d(this,"priority");d(this,"type","memory");d(this,"enabled");d(this,"ttlMap",new Map);d(this,"ttl");d(this,"repository");d(this,"bus");this.bus=e,this.repository=t,this.name=t.name;let n=t.getConfig();this.enabled=n.enabled??!0,this.priority=n.priority??0,this.ttl=n.options?.ttl??1800*1e3}getSourceType(){return"memory"}lookup(e){let t=Date.now();l.debug(`Sync lookup: ${e.cleanKey}`);let n=this.bus.repo(e,this.name);n.getStart();let r=this.tryDirectLookup(e);if(r!==null)return l.debug(`Cache hit: ${e.cleanKey}`),n.getSuccess(r.text),this.createResult(r,"memory",200,t,!0);if(e.cleanKey.includes(".")&&e.namespace){let s=this.tryNamespaceLookup(e);if(s!==null)return l.debug(`Namespace hit: ${e.cleanKey}`),n.getSuccess(s.text),this.createResult(s,"memory",200,t,!0)}return l.debug(`Cache miss: ${e.cleanKey}`),n.getMiss(),this.createResult({text:e.parsedDefaultValue||e.cleanKey,styles:{}},"fallback",404,t)}save(e,t){if(!t.value)return;let n=this.bus.repo(e,this.name),r={text:t.value,styles:t.styles||{}};this.setWithTTL(e.individualCacheKey,JSON.stringify(r)),l.debug(`Saved to cache: ${e.cleanKey}`),n.setSuccess(t.value)}saveNamespace(e,t){if(!t.namespace)return;let n=this.bus.repo(t.locale+":"+t.namespace,this.name),r=S(t.locale,t.namespace);this.setWithTTL(r,JSON.stringify(e));let s=D(e,"",t.locale,t.namespace);for(let[i,o]of Object.entries(s))this.setWithTTL(i,o);n.setSuccess(JSON.stringify(e))}tryDirectLookup(e){if(this.checkAndExpireTTL(e.individualCacheKey))return null;let t=this.repository.get(e.individualCacheKey);if(!t)return null;this.refreshTTL(e.individualCacheKey);try{let n=JSON.parse(t);return typeof n=="object"&&"text"in n?{text:String(n.text),styles:n.styles||{}}:{text:t,styles:{}}}catch{return{text:t,styles:{}}}}tryNamespaceLookup(e){if(!e.namespace)return null;let t=S(e.locale,e.namespace);if(this.checkAndExpireTTL(t))return null;let n=this.repository.get(t);if(!n)return null;this.refreshTTL(t);try{let r=JSON.parse(n),s=P(r,e.cleanKey);if(s!=null){let i;return typeof s=="object"&&s!==null&&"text"in s?i={text:String(s.text),styles:s.styles||{}}:i={text:String(s),styles:{}},this.setWithTTL(e.individualCacheKey,JSON.stringify(i)),l.debug(`Cached from namespace: ${e.cleanKey}`),i}}catch(r){l.debug(`Invalid JSON in namespace cache: ${t}`,r),this.repository.remove(t),this.ttlMap.delete(t)}return null}createResult(e,t,n,r,s){return{value:e.text,styles:e.styles,source:t,status:n,duration:Date.now()-r,...s!==void 0&&{cached:s}}}checkAndExpireTTL(e){let t=this.ttlMap.get(e);return t&&Date.now()-t>this.ttl?(this.repository.remove(e),this.ttlMap.delete(e),l.debug(`TTL expired: ${e}`),!0):!1}setWithTTL(e,t){this.repository.set(e,t),this.ttlMap.set(e,Date.now())}refreshTTL(e){this.ttlMap.set(e,Date.now())}getTTLInfo(){let e={},t=Date.now();for(let[n,r]of this.ttlMap.entries()){let s=t-r,i=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:i}}return e}getEntries(){if(this.repository.getEntries!==void 0)return this.repository.getEntries()}clearNamespace(e,t){let n=S(e,t),r=`${e}:${t}:`;this.repository.remove(n),this.ttlMap.delete(n);let s=this.repository.getEntries?.();if(s)for(let i of Object.keys(s))i.startsWith(r)&&(this.repository.remove(i),this.ttlMap.delete(i));l.debug(`Cleared namespace: ${e}:${t}`)}destroy(){this.repository.clear(),this.ttlMap.clear()}setCache(e,t,n){let r={text:t,styles:n||{}};this.setWithTTL(e,JSON.stringify(r)),l.debug(`Direct cache set: ${e}`)}};var ye=class{constructor(e,t){d(this,"name");d(this,"version","1.0.0");d(this,"priority");d(this,"type","storage");d(this,"enabled");d(this,"ttlMap",new Map);d(this,"ttl");d(this,"repository");d(this,"bus");this.bus=e,this.repository=t,this.name=t.name;let n=t.getConfig();this.enabled=n.enabled??!0,this.priority=n.priority??0,this.ttl=n.options?.ttl??1800*1e3}getSourceType(){return"memory"}async lookup(e){let t=Date.now();l.debug(`Async lookup: ${e.cleanKey}`);let n=this.bus.repo(e,this.name),r=await this.tryDirectLookup(e);if(r!==null)return l.debug(`Cache hit: ${e.cleanKey}`),n.getSuccess(r.text),this.createResult(r,"storage",200,t,!0);if(e.cleanKey.includes(".")&&e.namespace){let s=await this.tryNamespaceLookup(e);if(s!==null)return l.debug(`Namespace hit: ${e.cleanKey}`),n.getSuccess(s.text),this.createResult(s,"storage",200,t,!0)}return l.debug(`Cache miss: ${e.cleanKey}`),n.getMiss(),this.createResult({text:e.parsedDefaultValue||e.cleanKey,styles:{}},"fallback",404,t)}async save(e,t){if(!t.value)return;let n=this.bus.repo(e,this.name),r={text:t.value,styles:t.styles||{}};await this.setWithTTL(e.individualCacheKey,JSON.stringify(r)),l.debug(`Saved to cache: ${e.cleanKey}`),n.setSuccess(t.value)}async saveNamespace(e,t){if(!t.namespace)return;let n=this.bus.repo(t.locale+":"+t.namespace,this.name),r=Object.keys(e).length;l.debug(`Saving namespace: ${t.locale}:${t.namespace} (${r} keys)`);let s=S(t.locale,t.namespace);await this.setWithTTL(s,JSON.stringify(e));let i=D(e,"",t.locale,t.namespace),o=0;for(let[c,u]of Object.entries(i))await this.setWithTTL(c,u),o++;l.debug(`Saved: ${o} keys + namespace blob`),n.setSuccess(JSON.stringify(e))}async tryDirectLookup(e){if(await this.checkAndExpireTTL(e.individualCacheKey))return null;let t=await this.repository.get(e.individualCacheKey);if(!t)return null;this.refreshTTL(e.individualCacheKey);try{let n=JSON.parse(t);return typeof n=="object"&&"text"in n?{text:String(n.text),styles:n.styles||{}}:{text:t,styles:{}}}catch{return{text:t,styles:{}}}}async tryNamespaceLookup(e){if(!e.namespace)return null;let t=S(e.locale,e.namespace);if(await this.checkAndExpireTTL(t))return null;let n=await this.repository.get(t);if(!n)return null;this.refreshTTL(t);try{let r=JSON.parse(n),s=P(r,e.cleanKey);if(s!=null){let i;return typeof s=="object"&&s!==null&&"text"in s?i={text:String(s.text),styles:s.styles||{}}:i={text:String(s),styles:{}},await this.setWithTTL(e.individualCacheKey,JSON.stringify(i)),l.debug(`Cached from namespace: ${e.cleanKey}`),i}}catch(r){l.debug(`Invalid JSON in namespace cache: ${t}`,r),await this.repository.remove(t),this.ttlMap.delete(t)}return null}createResult(e,t,n,r,s){return{value:e.text,styles:e.styles,source:t,status:n,duration:Date.now()-r,...s!==void 0&&{cached:s}}}async checkAndExpireTTL(e){let t=this.ttlMap.get(e);return t&&Date.now()-t>this.ttl?(await this.repository.remove(e),this.ttlMap.delete(e),l.debug(`TTL expired: ${e}`),!0):!1}async setWithTTL(e,t){await this.repository.set(e,t),this.ttlMap.set(e,Date.now())}refreshTTL(e){this.ttlMap.set(e,Date.now())}getTTLInfo(){let e={},t=Date.now();for(let[n,r]of this.ttlMap.entries()){let s=t-r,i=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:i}}return e}async destroy(){await this.repository.clear(),this.ttlMap.clear()}getEntries(){if(this.repository.getEntries!==void 0)return this.repository.getEntries()}};var ae=class extends Error{constructor(t,n,r){super(r);this.key=t;this.status=n;this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},b=class extends ae{constructor(e){super(e,404,`Translation not found: ${e}`)}},N=class extends ae{constructor(t,n){super(t,423,`Translation locked: ${t}`);this.retryAfter=n}},B=class extends ae{constructor(e,t){super(e,t,`Server error ${t}: ${e}`)}},k=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="NetworkError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}};function Ye(a){return a instanceof B||a instanceof k}var be=class{constructor(e,t){d(this,"repository");d(this,"name");d(this,"priority");d(this,"version","1.0.0");d(this,"type","network");d(this,"enabled");d(this,"bus");d(this,"retryCount");d(this,"retryDelay");this.bus=e,this.repository=t,this.name=t.name;let n=t.getConfig();this.enabled=n.enabled??!1,this.priority=n.priority??0,this.retryCount=n.options?.retries??3,this.retryDelay=n.options?.retryDelay??1e3}initialize(){return Promise.resolve()}getSourceType(){return"network"}async lookup(e){let t=Date.now(),n=e.parsedDefaultValue||e.cleanKey;if(!this.enabled)return this.createTranslationResult(n,"fallback",0,t);let r=this.bus.network(e,this.name);r.start(),l.debug(`Network lookup: ${e.cleanKey}`);try{let s=await this.lookupContentUnitWithRetry(e.individualCacheKey);return l.debug(`Network hit: ${e.cleanKey}`),r.success(s.text),this.createTranslationResult(s.text,"network",200,t,void 0,!1,void 0,s.styles)}catch(s){return s instanceof b&&e.namespace?(l.debug(`Individual key not found, trying namespace: ${e.cleanKey}`),this.lookupFromNamespace(e,n,t,r)):s instanceof N?(l.debug(`Translation locked (423): ${e.cleanKey}`),this.handleTranslationLocked(e,n,s,t,r)):(l.debug(`Network error: ${e.cleanKey}`,s),r.error(s),this.createTranslationResult(n,"fallback",0,t,s))}}async lookupFromNamespace(e,t,n,r){try{let s=await this.loadNamespace(e.locale,e.namespace);if(s&&s.data){let o=P(s.data,e.cleanKey);if(o!=null){let c,u={};if(typeof o=="object"&&o!==null&&"text"in o){let p=o;c=String(p.text),u=p.styles||{}}else c=String(o);return l.debug(`Network namespace hit: ${e.cleanKey}, hasStyles=${Object.keys(u).length>0}`),r.success(c),this.createTranslationResult(c,"network",200,n,void 0,!1,{locale:e.locale,namespace:e.namespace,data:s.data},u)}}let i=new b(e.cleanKey);return this.handleTranslationNotFound(e,t,i,n)}catch(s){return l.debug(`Namespace load failed: ${e.cleanKey}`,s),s instanceof b?this.handleTranslationNotFound(e,t,s,n):s instanceof N?this.handleTranslationLocked(e,t,s,n,r):(r.error(s),this.createTranslationResult(t,"fallback",0,n,s))}}async loadNamespace(e,t){let n=Date.now();if(!this.enabled)return this.createNamespaceResult(null,"fallback",0,n);try{let r=await this.loadNamespaceWithRetry(e,t);return r===null?(l.debug(`Network namespace not modified: ${e}:${t}`),this.createNamespaceResult(null,"network",304,n)):(l.debug(`Network namespace loaded: ${e}:${t}`),this.createNamespaceResult(r,"network",200,n))}catch(r){return r instanceof N?(l.debug(`Namespace locked (423): ${e}:${t}`),this.createNamespaceResult(null,"fallback",423,n,r)):r instanceof b?(l.debug(`Network namespace not found: ${e}:${t}`),this.createNamespaceResult(null,"fallback",404,n,r)):(l.debug(`Network namespace error: ${e}:${t}`,r),this.createNamespaceResult(null,"fallback",0,n,r))}}async loadNamespaceWithRetry(e,t){return this.withRetry(()=>this.repository.getNamespace(e,t),`${e}:${t}`,"namespace request")}async save(e,t){}async lookupWithRetry(e){return this.withRetry(()=>this.repository.get(e),e,"network request")}async lookupContentUnitWithRetry(e){let t=this.repository;return typeof t.getContentUnit!="function"?{text:await this.lookupWithRetry(e),styles:{}}:this.withRetry(()=>t.getContentUnit(e),e,"network content unit request")}delay(e){return new Promise(t=>setTimeout(t,e))}calculateBackoff(e){let n=this.retryDelay*Math.pow(2,e-1),r=1e4,s=Math.random()*.1*n;return Math.min(n+s,r)}async withRetry(e,t,n,r=1){let s=this.bus.network(t,"withRetry");try{return await e()}catch(i){if(r<=this.retryCount&&Ye(i)){let o=this.calculateBackoff(r);return s.retry(r,o,i.message),await this.delay(o),l.debug(`Retrying ${n} (${r}/${this.retryCount}) after ${o}ms`),this.withRetry(e,t,n,r+1)}throw i}}handleTranslationNotFound(e,t,n,r){return l.debug(`Network namespace miss: ${e.cleanKey}`),this.bus.translation(e).notFound(t,e.locale,e.namespace||"default"),this.createTranslationResult(t,"fallback",404,r,n)}handleTranslationLocked(e,t,n,r,s){return this.bus.translation(e).locked(t,e.locale,e.namespace||"default"),s.error(n,423),this.createTranslationResult(t,"fallback",423,r,n)}createTranslationResult(e,t,n,r,s,i,o,c){return{value:e,source:t,status:n,duration:Date.now()-r,...s&&{error:s},...i!==void 0&&{cached:i},...o&&{namespaceLoaded:o},...c&&Object.keys(c).length>0&&{styles:c}}}createNamespaceResult(e,t,n,r,s){return{data:e,source:t,status:n,duration:Date.now()-r,...s&&{error:s}}}getPreload(){return this.repository.getConfig().options?.preloadNamespaces||[]}getBaseUrl(){return this.repository.getConfig().options?.baseUrl||""}};var F=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Kt(a){return a.replace(/"/g,""")}function z(a,e){let n=`<${a.toLowerCase()}`;for(let[r,s]of Object.entries(e))n+=` ${r.toLowerCase()}="${Kt(s)}"`;return n+=">",n}function ve(a){let e=a.search(/[\s>]/);return a.slice(1,e===-1?a.length:e).toLowerCase()}function Pe(a){for(let e of a)if(e.startsWith("raw:"))return e.slice(4);return null}function Qe(a){let e={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",rsquo:"\u2019",lsquo:"\u2018",rdquo:"\u201D",ldquo:"\u201C",hellip:"\u2026",mdash:"\u2014",ndash:"\u2013",copy:"\xA9",reg:"\xAE",trade:"\u2122"};return a.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z][a-z0-9]*);/gi,(t,n)=>{if(n[0]==="#"){let r=n[1]==="x"||n[1]==="X"?parseInt(n.slice(2),16):parseInt(n.slice(1),10);if(Number.isFinite(r)&&r>0)try{return String.fromCodePoint(r)}catch{return t}return t}return e[n.toLowerCase()]??t})}var we=class{parse(e){if(/<\/?[0-9]+>/.test(e))return{text:Qe(e),styles:{}};let t={},n=0,r=[],s="",i=0;for(;i<e.length;){let o=this.matchTag(e,i);if(!o){s+=e.slice(i);break}if(s+=e.slice(i,o.startIndex),o.isClosing){let c=null;for(let u=r.length-1;u>=0;u--)if(r[u].tag===o.tag.toLowerCase()){c=r[u].index,r.splice(u,1);break}c!==null&&(s+=`</${c}>`)}else{let c=o.tag.toLowerCase(),u=F.has(c),p=o.isSelfClosing||u;n++,t[String(n)]=[`raw:${z(c,o.attrs)}`],p?s+=`<${n}/>`:(s+=`<${n}>`,r.push({tag:c,index:n}))}i=o.endIndex}for(;r.length>0;){let o=r.pop();s+=`</${o.index}>`}return{text:Qe(s),styles:t}}matchTag(e,t){let n=e.indexOf("<",t);if(n===-1)return null;let r=/^<(\/?)([a-zA-Z][a-zA-Z0-9]*)((?:\s+[a-zA-Z][a-zA-Z0-9-]*(?:=(?:"[^"]*"|'[^']*'|[^\s>]*))?)*)\s*(\/?)>/,i=e.slice(n).match(r);if(!i)return n+1<e.length?this.matchTag(e,n+1):null;let[o,c,u,p,m]=i;return{tag:u,attrs:this.parseAttributes(p),isClosing:c==="/",isSelfClosing:m==="/",startIndex:n,endIndex:n+o.length}}parseAttributes(e){let t={};if(!e.trim())return t;let n=/([a-zA-Z][a-zA-Z0-9-]*)(?:=(?:"([^"]*)"|'([^']*)'|([^\s>]*)))?/g,r;for(;(r=n.exec(e))!==null;){let[,s,i,o,c]=r;t[s.toLowerCase()]=i??o??c??""}return t}};var Ut=new Set(["a","abbr","b","bdi","bdo","br","cite","code","del","dfn","em","i","img","ins","kbd","mark","q","s","samp","small","span","strong","sub","sup","time","u","var","wbr"]),Mt=new Set(["alt","cite","class","datetime","dir","height","href","id","lang","loading","rel","role","src","target","title","width"]),Dt=new Set(["href","src","cite"]),Ht=new Set(["color","background-color","font-family","font-size","font-style","font-weight","letter-spacing","line-height","text-decoration","text-decoration-color","text-decoration-line","text-decoration-style","text-transform","vertical-align","white-space","word-spacing"]),jt=/url\s*\(|expression\s*\(|image-set\s*\(|element\s*\(|paint\s*\(|javascript:|\\|[<>{}@]/i,_t=new Set(["http","https","mailto","tel"]),Bt={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:"\xA0",colon:":",semi:";",sol:"/",bsol:"\\",Tab:" ",NewLine:`
|
|
5
|
-
`};function Ze(a){return a.replace(/&(?:#[xX]([0-9a-fA-F]+);?|#(\d+);?|([a-zA-Z]+);)/g,(e,t,n,r)=>t?String.fromCodePoint(parseInt(t,16)):n?String.fromCodePoint(parseInt(n,10)):Bt[r]??e)}function Oe(a){return a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ft(a){let t=Ze(a).replace(/[\u0000-\u0020\u007f]/g,"").toLowerCase(),n=/^([a-z][a-z0-9+.-]*):/.exec(t);return n?_t.has(n[1])?a:null:a}function zt(a){return Gt(a,!0)}function Gt(a,e){let t=Ze(a),n=[];for(let r of t.split(";")){let s=r.indexOf(":");if(s===-1)continue;let i=r.slice(0,s).trim().toLowerCase(),o=r.slice(s+1).trim();/^[a-z-]+$/.test(i)&&(e&&!Ht.has(i)||o===""||jt.test(o)||n.push(`${i}: ${o}`))}return n.length>0?n.join("; "):null}var Vt=/([^\s=/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]*)))?/g;function qe(a){if(!a.startsWith("<"))return null;let e=ve(a);if(!/^[a-z][a-z0-9-]*$/.test(e)||!Ut.has(e))return null;let t=a.endsWith("/>")?a.length-2:a.endsWith(">")?a.length-1:a.length,n=a.slice(1+e.length,t),r={};for(let s of n.matchAll(Vt)){let i=s[1].toLowerCase(),o=s[2]??s[3]??s[4]??"";if(i in r)continue;if(i==="style"){let u=zt(o);u!==null&&(r[i]=u);continue}(Mt.has(i)||/^data-[a-z0-9-]*$/.test(i)||/^aria-[a-z0-9-]*$/.test(i))&&(Dt.has(i)&&Ft(o)===null||(r[i]=o))}return z(e,r)}var G=class{serialize(e){let{text:t,styles:n}=e,r=/<(\/?)?(\d+)(\/)?>/g,s="",i=0,o;for(;(o=r.exec(t))!==null;){s+=Oe(t.slice(i,o.index));let[c,u,p]=o,m=n[p]??[],g=Pe(m),h=g===null?null:qe(g);if(g&&h!==null){let y=ve(g),x=F.has(y);u?x||(s+=`</${y}>`):s+=h}else s+=c;i=o.index+c.length}return s+=Oe(t.slice(i)),s}};var Ee=class{constructor(e,t,n,r){d(this,"handlerChain");d(this,"bus");d(this,"currentLocale");d(this,"loadNamespaces");this.handlerChain=e,this.bus=t,this.currentLocale=n,this.loadNamespaces=r}get(e){let t=this.handlerChain.getEntries();for(let n in t){let r=t[n];if(r&&typeof r=="object"&&e in r){let s=r[e];try{if(typeof s=="string"){let i=JSON.parse(s);return typeof i=="object"&&"text"in i?{value:String(i.text),styles:i.styles||void 0}:{value:s,styles:void 0}}return{value:JSON.stringify(s),styles:void 0}}catch{return{value:typeof s=="string"?s:JSON.stringify(s),styles:void 0}}}}return null}set(e,t,n){let[r,s,...i]=e.split(":"),o=i.join(":");if(!r||!s||!o)throw new Error(`Invalid cache key format: "${e}". Expected format: "locale:namespace:key"`);this.handlerChain.setCache(e,t,n),this.bus.emit("cache:set",{payload:{key:e,value:t,styles:n,optimistic:!0}})}has(e){return this.get(e)!==null}async invalidate(e={}){let{namespace:t,locale:n,key:r,predicate:s,refetch:i=!0}=e,o=this.currentLocale(),c=0;if(r){let[u,p]=r.split(":");u&&p&&(this.handlerChain.clearNamespace(u,p),c=1)}else if(t&&n)this.handlerChain.clearNamespace(n,t),c=this.countClearedKeys(n,t);else if(t)this.handlerChain.clearNamespace(o,t),c=this.countClearedKeys(o,t);else if(n){let u=this.handlerChain.getEntries(),p=new Set;for(let m in u){let g=u[m];if(g&&typeof g=="object"){for(let h of Object.keys(g))if(h.startsWith(`${n}:`)||h.startsWith(`@${n}:`)){let y=h.replace("@","").split(":");y[1]&&p.add(y[1])}}}for(let m of p)this.handlerChain.clearNamespace(n,m),c++}else if(s){let u=this.handlerChain.getEntries(),p=new Map;for(let m in u){let g=u[m];if(g&&typeof g=="object"){for(let h of Object.keys(g))if(s(h)){let y=h.replace("@","").split(":"),x=y[0],T=y[1];x&&T&&(p.has(x)||p.set(x,new Set),p.get(x).add(T),c++)}}}for(let[m,g]of p)for(let h of g)this.handlerChain.clearNamespace(m,h)}else this.handlerChain.clearCache(),c=-1;this.bus.emit("cache:invalidate",{payload:{filter:e,keysCleared:c,refetch:i}}),i&&await this.refetchAfterInvalidate(e)}countClearedKeys(e,t){let n=this.handlerChain.getEntries(),r=0,s=`${e}:${t}:`,i=`@${e}:${t}`;for(let o in n){let c=n[o];if(c&&typeof c=="object")for(let u of Object.keys(c))(u.startsWith(s)||u===i)&&r++}return r}async refetchAfterInvalidate(e){let{namespace:t,locale:n,key:r}=e,s=this.currentLocale();if(r){let[i,o]=r.split(":");i&&o&&await this.loadNamespaces(i,[o])}else t&&await this.loadNamespaces(n||s,[t])}};var Wt=/<\/?[0-9]+\/?>/,Jt=/<[a-z][a-z0-9]*(?:\s+[^>]*)?\/?>/i,V=class{constructor(e,t,n="en",r){d(this,"handlerChain");d(this,"currentLocale");d(this,"defaultNamespace");d(this,"pendingTranslations",new Map);d(this,"bus");d(this,"plugins",new Map);d(this,"formatters",new Map);d(this,"processors",new Map);d(this,"warnedNoInterpolate",!1);d(this,"eventPlugins",new Set);d(this,"markupParser",new we);d(this,"htmlSerializer",new G);d(this,"cache");this.bus=e,this.handlerChain=t,this.currentLocale=n,this.defaultNamespace=r,this.cache=new Ee(this.handlerChain,this.bus,()=>this.currentLocale,(s,i)=>this.loadNamespaces(s,i))}registerPlugin(e){this.plugins.set(e.name,e),this.isEmbeddedPlugin(e)&&this.integrateEmbeddedPlugin(e),this.isEventPlugin(e)&&this.eventPlugins.add(e)}integrateEmbeddedPlugin(e){if(e.getFormatters){let t=e.getFormatters();Object.entries(t).forEach(([n,r])=>{this.formatters.set(n,r),l.debug(`Embedded formatter: ${n} from ${e.name}`)})}if(e.getProcessors){let t=e.getProcessors();Object.entries(t).forEach(([n,r])=>{this.processors.set(n,r),l.debug(`Embedded processor: ${n} from ${e.name}`)})}}t(e,...t){let[n,r]=t,s=se(e,this.currentLocale,n,r,this.defaultNamespace);l.debug(`Translation requested: ${s.cleanKey}`);let i=this.bus.translation(s);i.request();let o=this.handlerChain.handleSync(s);if(o&&o.status===200){let p=this.processValue(o.value,s);return l.debug(`Translation found: ${s.cleanKey} from ${o.source} (${o.duration}ms)`),i.success(p),p}this.triggerBackgroundLoad(s);let c=s.parsedDefaultValue||s.cleanKey,u=this.processValue(c,s);return l.debug(`Translation fallback: ${s.cleanKey}`),i.fallback(u),u}tHtml(e,...t){let[n,r]=t,s=se(e,this.currentLocale,n,r,this.defaultNamespace);l.debug(`HTML translation requested: ${s.cleanKey}`);let i=this.bus.translation(s);i.request();let o=this.handlerChain.handleSync(s);if(o&&o.status===200){let p=this.processValueAsHtml(o.value,s,o.styles);return l.debug(`HTML translation found: ${s.cleanKey} from ${o.source}`),i.success(p),p}this.triggerBackgroundLoad(s);let c=s.parsedDefaultValue||s.cleanKey,u=this.processValueAsHtml(c,s);return l.debug(`HTML translation fallback: ${s.cleanKey}`),i.fallback(u),u}processValueAsHtml(e,t,n){let r=this.processTranslationValue(e,t);if(this.containsIndexedTags(r)){let s=n||this.getStylesFromNamespace(t),i={text:r,styles:s};return this.htmlSerializer.serialize(i)}if(this.containsHtml(r)){let s=this.markupParser.parse(r);return this.htmlSerializer.serialize(s)}return r}processValue(e,t){return this.containsIndexedTags(e)?this.processIndexedValue(e,t):this.containsHtml(e)?this.processHtmlValue(e,t):this.processTranslationValue(e,t)}containsIndexedTags(e){return Wt.test(e)}processIndexedValue(e,t){return this.processTranslationValue(e,t).replace(/<\/?[0-9]+\/?>/g,"")}getStylesFromNamespace(e){if(!e.namespace)return{};try{let t=S(e.locale,e.namespace),n=this.handlerChain.getNamespaceData(t);if(!n)return{};let r=P(n,e.cleanKey);return r&&typeof r=="object"&&"styles"in r?r.styles:{}}catch(t){return l.debug(`Error getting styles for key ${e.cleanKey}:`,t),{}}}processHtmlValue(e,t){try{let n=this.markupParser.parse(e);return this.processTranslationValue(n.text,t).replace(/<\/?[0-9]+\/?>/g,"")}catch(n){return l.warn(`ContentUnit processing failed for key "${t.cleanKey}" \u2014 ${U(e)}: ${ue(n)}`),this.processTranslationValue(e,t)}}processTranslationValue(e,t,n,r){let s,i,o;if(t&&"cleanKey"in t){let u=t;s=u.parsedParams,i=u.locale,o=u.cleanKey}else s=t,i=n||this.currentLocale,o=r;let c=e;try{if(c=this.applyStructuralFormatters(c,s,o),this.formatters.has("interpolate")?c=this.formatters.get("interpolate")(c,s,i,o):!this.warnedNoInterpolate&&s&&Object.keys(s).length>0&&c.includes("{")&&(this.warnedNoInterpolate=!0,console.warn("[LionRapid] Translation params were passed but no interpolate formatter is registered \u2014 {placeholders} render literally. Install @lionrapid/formatters and add .use(coreFormattersPlugin) to the builder.")),this.processors.size>0)for(let[u,p]of this.processors.entries())try{c=p(c,s,o)}catch(m){l.warn(`Processor ${u} failed:`,m)}return c}catch(u){return l.warn(`Translation processing failed for key "${o??"(no key)"}" \u2014 ${U(e)}: ${ue(u)}`),e}}getContentUnit(e,t,n){let r=se(e,this.currentLocale,t,n,this.defaultNamespace),s=this.handlerChain.handleSync(r),i=s&&s.status===200?s.value:r.parsedDefaultValue||r.cleanKey;return(!s||s.status!==200)&&this.triggerBackgroundLoad(r),this.markupParser.parse(i)}processContentText(e,t){return this.processTranslationValue(e,t,this.currentLocale)}containsHtml(e){return Jt.test(e)}applyStructuralFormatters(e,t,n){let r=e,s=o=>typeof o?.count=="number",i=o=>typeof o?.context=="string";if(this.formatters.has("plural")&&s(t)){let o=this.formatters.get("plural");try{let c=o(r,t,this.currentLocale,n);if(c!==String(r))return c}catch(c){l.warn("Plural formatting failed:",c)}}if(this.formatters.has("context")&&i(t)){let o=this.formatters.get("context");try{let c=o(r,t,this.currentLocale,n);if(c!==String(r))return c}catch(c){l.warn("Context formatting failed:",c)}}return String(r)}triggerBackgroundLoad(e){l.debug(`Background load: ${e.cleanKey}`);let t=e.individualCacheKey;if(!this.pendingTranslations.has(t)){let n=this.handlerChain.handleAsync(e).then(r=>{r&&r.value?l.debug(`Cached: ${e.cleanKey} = "${r.value}"`):l.debug(`Not found: ${e.cleanKey}`)}).catch(r=>{l.warn(`Background load failed: ${e.cleanKey}`,r)});this.pendingTranslations.set(t,n),n.finally(()=>this.pendingTranslations.delete(t))}}getCurrentLocale(){return this.currentLocale}setDefaultNamespace(e){this.defaultNamespace=e}getDefaultNamespace(){return this.defaultNamespace}getEntries(){return this.handlerChain.getEntries()}isCached(e){let t=se(e,this.currentLocale,void 0,void 0,this.defaultNamespace);return this.handlerChain.isCached(t)}getHandlerChainInfo(){return this.handlerChain.getChainInfo()}async changeLanguage(e,t){let n=this.currentLocale;if(n===e){l.debug(`Language already set to ${e}`);return}let r=t?.clear||!1,s=this.bus.language(n,e);try{l.info(`Language change: ${n} \u2192 ${e}`),l.debug("Language change options",{clear:r,preloadNamespaces:t?.preloadNamespaces}),s.start(),this.currentLocale=e,r&&(await this.clearCache(),this.clearOldLocalePendingTranslations(n)),t?.preloadNamespaces?.length&&await this.loadNamespaces(e,t.preloadNamespaces),s.complete(),l.info(`Language changed: ${e}`)}catch(i){throw l.error("Language change failed:",i),s.error(i),i}}async clearCache(){this.handlerChain.clearCache(),l.debug(`Cache cleared for locale: ${this.currentLocale}`)}clearOldLocalePendingTranslations(e){let t=0;for(let n of this.pendingTranslations.keys())n.includes(`${e}:`)&&(this.pendingTranslations.delete(n),t++);t>0&&l.debug(`Cleared ${t} pending translations for ${e}`)}async loadNamespaces(e,t){l.debug(`Preloading ${t.length} namespaces for ${e}`);let n=t.map(async r=>{try{await this.handlerChain.loadNamespace?.(e,r),l.debug(`Preloaded: ${e}:${r}`)}catch(s){l.warn(`Failed to preload ${e}:${r}:`,s)}});await Promise.allSettled(n)}async reloadNamespace(e,t){let n=t||this.currentLocale;l.debug(`Reloading namespace: ${n}:${e}`),await this.cache.invalidate({namespace:e,locale:n,refetch:!0}),l.info(`Namespace reloaded: ${n}:${e}`)}isEmbeddedPlugin(e){return e.capabilities.some(t=>["formatters","processors","pluralization","context"].includes(t))}isEventPlugin(e){return e.capabilities.some(t=>["analytics","logging","react","validation","dev-tools","monitoring"].includes(t))}};var O=class{constructor(e){d(this,"name","MemoryRepository");d(this,"type","memory");d(this,"config",{});d(this,"cache",new Map);d(this,"accessOrder",new Map);d(this,"maxSize",1e3);this.config=e,this.maxSize=this.config.options?.maxSize||1e3}get(e){let t=this.cache.get(e);return t!==void 0?(this.accessOrder.set(e,Date.now()),t):null}set(e,t){this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictOldest(),this.cache.set(e,t),this.accessOrder.set(e,Date.now())}remove(e){this.cache.delete(e),this.accessOrder.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear()}clearNamespace(e,t){let n=S(e,t),r=`${e}:${t}:`;this.cache.delete(n),this.accessOrder.delete(n);for(let s of this.cache.keys())s.startsWith(r)&&(this.cache.delete(s),this.accessOrder.delete(s))}getNamespace(e,t){let n=S(e,t),r=this.cache.get(n);if(!r)return null;try{return JSON.parse(r)}catch{return this.cache.delete(n),null}}setNamespace(e,t,n){let r=S(e,t);this.cache.set(r,JSON.stringify(n))}evictOldest(){let e="",t=Date.now();for(let[n,r]of this.accessOrder.entries())r<t&&(t=r,e=n);e&&(this.cache.delete(e),this.accessOrder.delete(e))}getEntries(){let e={};for(let[t,n]of this.cache.entries())e[t]=n;return e}getConfig(){return this.config}};var Ce=class{constructor(e,t={}){d(this,"name","StaticRepository");d(this,"type","memory");d(this,"config");d(this,"mem");this.config={enabled:t.enabled??!0,priority:t.priority??.5,options:{ttl:Number.MAX_SAFE_INTEGER,maxSize:Number.MAX_SAFE_INTEGER,...t.options}},this.mem=new O({options:{maxSize:Number.MAX_SAFE_INTEGER}});for(let[n,r]of Object.entries(e))for(let[s,i]of Object.entries(r)){this.mem.setNamespace(n,s,i);let o=D(i,"",n,s);for(let[c,u]of Object.entries(o))this.mem.set(c,u)}}get(e){return this.mem.get(e)}getNamespace(e,t){return this.mem.getNamespace(e,t)}getEntries(){return this.mem.getEntries()}getConfig(){return this.config}set(){}remove(){}clear(){}setNamespace(){}};var et=6e4,Re=class{constructor(e,t,n){d(this,"queue",new Map);d(this,"debounceTimer",null);d(this,"repository");d(this,"config");d(this,"eventEmitter");d(this,"recentlySynced",new Map);this.repository=e,this.config=t,this.eventEmitter=n??null,t.enabled?l.debug(`MissingTranslationQueue: debounce=${t.debounceMs}ms, batchSize=${t.batchSize}`):l.debug("MissingTranslationQueue is disabled")}add(e){if(!this.config.enabled)return;let t=`${e.locale}:${e.namespace}:${e.key}`,n=this.recentlySynced.get(t);if(n&&Date.now()-n<et){l.debug(`Skipping recently synced key: ${t}`);return}if(this.queue.set(t,e),l.debug(`Missing translation queued: ${t} (queue size: ${this.queue.size})`),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.queue.size>=this.config.batchSize){l.debug(`Batch size reached (${this.config.batchSize}), flushing`),this.flush();return}this.debounceTimer=setTimeout(()=>{this.flush()},this.config.debounceMs)}flush(){if(this.queue.size===0)return;let e=Date.now();for(let[r,s]of this.recentlySynced)e-s>=et&&this.recentlySynced.delete(r);let t=Array.from(this.queue.entries()).map(([r,s])=>({key:r,value:s.fallbackValue,styles:s.styles})),n=t.length;this.queue.clear(),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),l.debug(`Flushing ${n} missing translations`),this.syncBatch(t).catch(r=>{l.warn(`Failed to sync ${n} missing translations:`,r)})}async syncBatch(e){try{if(e.some(s=>s.styles&&Object.keys(s.styles).length>0)&&"setBatchContentUnits"in this.repository){let s=e.map(i=>({key:i.key,value:{text:i.value,styles:i.styles??{}}}));await this.repository.setBatchContentUnits(s),l.debug(`Synced ${e.length} missing translations (ContentUnit)`)}else if("setBatch"in this.repository){let s=e.map(i=>({key:i.key,value:i.value}));await this.repository.setBatch(s),l.debug(`Synced ${e.length} missing translations`)}else l.warn("Repository does not support setBatch, syncing individually"),await this.syncIndividually(e);let n=Date.now(),r=[];for(let s of e)this.recentlySynced.set(s.key,n),r.push(s.key);this.eventEmitter&&this.eventEmitter.emit("sync:batch:complete",{payload:{count:e.length,keys:r}})}catch(t){throw l.error("Batch sync failed:",t),t}}async syncIndividually(e){let t=e.map(async n=>{try{await this.repository.set(n.key,n.value),l.debug(`Synced: ${n.key}`)}catch(r){l.warn(`Failed to sync ${n.key}:`,r)}});await Promise.allSettled(t)}getQueueSize(){return this.queue.size}getStats(){return{queueSize:this.queue.size,enabled:this.config.enabled,debounceMs:this.config.debounceMs,batchSize:this.config.batchSize}}destroy(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.queue.clear(),this.recentlySynced.clear(),l.debug("MissingTranslationQueue destroyed")}};function Xt(a){return!(a instanceof b||a instanceof N)}var W=class a{constructor(e){d(this,"config");d(this,"plugins",[]);d(this,"syncStorageRepos",[]);d(this,"asyncStorageRepos",[]);d(this,"networkRepos",[]);d(this,"syncQueue",null);this.config={defaultLocale:e.defaultLocale||"en",namespace:e.namespace||"app"}}static init(e={}){return new a(e)}useSyncStorage(e){return this.syncStorageRepos.push(e),this}useAsyncStorage(e){return this.asyncStorageRepos.push(e),this}useNetwork(e){return this.networkRepos.push(e),this}use(e){switch(e.type){case"plugin":this.plugins.push(e);break;case"memory":this.useSyncStorage(e);break;case"storage":this.useAsyncStorage(e);break;case"network":this.useNetwork(e);break}return this}useStaticBundle(e,t=.5){return this.use(new Ce(e,{priority:t}))}async build(){let e=new ge,t=e.builder();l.info("Builder started"),l.debug("Builder config",this.config),t.buildStart(this.config.defaultLocale,this.config.namespace);let n=new me(e);for(let o of this.syncStorageRepos){if(!o.getConfig().enabled)continue;let c=new fe(e,o);t.use("sync"),n.addSyncHandler(c)}for(let o of this.asyncStorageRepos){if(!o.getConfig().enabled)continue;let c=new ye(e,o);t.use("async"),n.addAsyncHandler(c)}let r=null;for(let o of this.networkRepos){if(!o.getConfig().enabled||!o.getConfig().options?.baseUrl)continue;let c=new be(e,o);r||(r=c),t.use("network"),n.addAsyncHandler(c);let u=o.getConfig();u.options?.syncMissing?.enabled&&(this.syncQueue=new Re(o,{enabled:u.options.syncMissing.enabled,debounceMs:u.options.syncMissing.debounceMs||500,batchSize:u.options.syncMissing.batchSize||50},e),e.on("translation:not-found",p=>{this.syncQueue&&this.syncQueue.add({key:p.payload.key,fallbackValue:p.payload.fallbackValue,styles:p.payload.styles,locale:p.payload.locale,namespace:p.payload.namespace})}),l.info("Missing translation sync enabled"),l.debug("Sync queue config",u.options.syncMissing))}l.debug("Handler chain constructed");let s=new V(e,n,this.config.defaultLocale,this.config.namespace);for(let o of this.plugins)t.use("plugin"),await o.initialize({core:s,bus:e}),s.registerPlugin(o),l.info(`Plugin initialized: ${o.name}`),l.debug(`Plugin version: ${o.version}`,o.capabilities);let i=n.getChainInfo();return r&&await this.executePreloading(r,n),l.info("Builder completed"),t.buildDone(i.handlers.map(o=>o.name),this.plugins.map(o=>o.name)),s}async executePreloading(e,t){let n=e.getPreload().filter(o=>o.eager!==!1);if(!n||n.length===0)return;l.info(`Preloading ${n.length} namespaces`),l.debug("Preload targets",{namespaces:n.map(o=>`${o.locale}:${o.namespace}`)});let r=!1,s=(o,c)=>{if(!Xt(c)||r)return;r=!0;let u=e.getBaseUrl()||"(no base URL configured)";console.warn(`[LionRapid] Could not load translations for ${o} from ${u} \u2014 the page stays untranslated until that host is reachable. If it is wrong, set data-base-url on the snippet tag (or \`baseUrl\` in the network repository options).`,c)},i=n.map(async o=>{let c=`${o.locale}:${o.namespace}`;try{let u=await e.loadNamespace(o.locale,o.namespace);if(u&&u.data&&u.status===200){let p={locale:o.locale,namespace:o.namespace};await t.saveNamespaceToHandlers(u.data,p),l.debug(`Preloaded: ${c}`);return}u?.error&&(s(c,u.error),l.warn(`Preload failed: ${c}`,u.error))}catch(u){s(c,u),l.warn(`Preload failed: ${c}`,u)}});await Promise.allSettled(i),l.info("Preloading completed")}};var Yt="X-LR-Surface",Qt="snippet",$=class ${constructor(e={}){d(this,"name","NetworkRepository");d(this,"type","network");d(this,"config",{});d(this,"namespaceSnapshots",new Map);d(this,"inflightGets",new Map);d(this,"negativeCache",new Map);d(this,"authFailedStatus",null);d(this,"writesFailedStatus",null);d(this,"DEFAULT_ENDPOINTS",{getTranslation:"/api/integrations/translations/:key",getNamespace:"/api/integrations/translations/:locale/:namespace",getProjectConfig:"/api/integrations/project-config",setTranslation:"/api/integrations/sync/:key",setNamespace:"/api/integrations/sync/:locale/:namespace",setBatch:"/api/integrations/sync/batch",removeTranslation:"/api/integrations/sync/:key",clearTranslations:"/translations"});this.config={options:{timeout:e.options?.timeout??5e3,baseUrl:e.options?.baseUrl??"",headers:e.options?.headers??{}},...e}}async get(e){if(!this.config?.options?.baseUrl)throw l.debug("API base URL is not set"),new k("API base URL is not set");let t=this.buildUrl("getTranslation",{key:e});l.debug(`API GET: ${t}`);try{let n=await this.makeRequest(t,"GET");n.ok||this.handleHttpError(n,e);let r=await n.json();l.debug("API response data:",r);let s=r.translations[r.meta?.key]||r.translations[e]||Object.values(r.translations)[0];if(l.debug(`Fetched translation for key "${e}":`,s),!s)throw new b(e);return typeof s=="object"&&"text"in s?(l.debug(`ContentUnit text: ${U(s.text)}`),s.text):String(s)}catch(n){this.handleCaughtError(n)}}async getContentUnit(e){if(!this.config?.options?.baseUrl)throw l.debug("API base URL is not set"),new k("API base URL is not set");let t=this.buildUrl("getTranslation",{key:e});l.debug(`API GET ContentUnit: ${t}`);try{let n=await this.makeRequest(t,"GET");n.ok||this.handleHttpError(n,e);let r=await n.json();l.debug("API response data:",r);let s=r.translations[r.meta?.key]||r.translations[e]||Object.values(r.translations)[0];if(!s)throw new b(e);return typeof s=="object"&&"text"in s?(l.debug(`ContentUnit for "${e}": text=${U(s.text)}, styles=`,s.styles),{text:s.text,styles:s.styles||{}}):(l.debug(`Plain string for "${e}": ${U(String(s))} (no styles)`),{text:String(s),styles:{}})}catch(n){this.handleCaughtError(n)}}async getNamespace(e,t){if(!this.config?.options?.baseUrl)throw l.debug("API base URL is not set"),new k("API base URL is not set");try{return await this.fetchNamespaceRaw(e,t)}catch(n){this.handleCaughtError(n)}}async getProjectConfig(){if(!this.config?.options?.baseUrl)throw new k("API base URL is not set");let e=this.buildUrl("getProjectConfig",{});l.debug(`API GET ProjectConfig: ${e}`);try{let t=await this.makeRequest(e,"GET");if(t.status===404)return null;t.ok||this.handleHttpError(t,"project-config");let n=await t.json();return!n||typeof n.defaultLocale!="string"||!Array.isArray(n.languages)?(l.warn("project-config payload unusable \u2014 keeping local fallback"),null):{defaultLocale:n.defaultLocale,languages:n.languages.map(String)}}catch(t){this.handleCaughtError(t)}}async fetchNamespaceRaw(e,t,n=!0){let r=this.buildUrl("getNamespace",{locale:e,namespace:t});l.debug(`API GET Namespace: ${r}`);let s=`${e}:${t}`,i=n?this.getSnapshot(s):void 0,o={};i&&(o["If-None-Match"]=`W/"${i.version}"`);let c=await this.makeRequest(r,"GET",void 0,o);if(c.status===304)return i?(l.debug(`Namespace ${s}: 304 Not Modified (snapshot served)`),i.translations):(l.debug(`Namespace ${s}: unexpected 304 with no snapshot \u2014 refetching`),this.fetchNamespaceRaw(e,t,!1));c.ok||this.handleHttpError(c,s);let u=await c.json();if(l.debug("API response data:",u),!u.translations)throw new b(s);let p=u.meta?.version!=null?String(u.meta.version):null;return p&&this.setSnapshot(s,{version:p,translations:u.translations}),u.translations}async set(e,t){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let n=this.buildUrl("setTranslation",{key:e}),r=await this.makeRequest(n,"PUT",{translation:t});if(!r.ok)throw new Error(`Failed to save translation: ${r.status}`)}catch(n){throw l.debug(`API set failed for key "${e}":`,n),n}}async setNamespace(e,t,n){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let r=this.buildUrl("setNamespace",{locale:e,namespace:t}),s=await this.makeRequest(r,"PUT",{translations:n});if(!s.ok)throw new Error(`Failed to save namespace: ${s.status}`)}catch(r){throw l.debug(`API setNamespace failed for ${e}:${t}:`,r),r}}async setBatch(e){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("setBatch");l.debug(`API POST Batch: ${t} (${e.length} items)`);let n=await this.makeRequest(t,"POST",{translations:e});if(!n.ok)throw new Error(`Failed to sync batch: ${n.status}`);l.debug(`Batch sync successful: ${e.length} items`)}catch(t){throw l.debug(`API setBatch failed for ${e.length} items:`,t),t}}async getNamespaceContentUnits(e,t){if(!this.config?.options?.baseUrl)throw l.debug("API base URL is not set"),new k("API base URL is not set");try{return await this.fetchNamespaceRaw(e,t)}catch(n){this.handleCaughtError(n)}}async setContentUnit(e,t){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let n=this.buildUrl("setTranslation",{key:e}),r=await this.makeRequest(n,"PUT",{translation:t,format:"contentunit"});if(!r.ok)throw new Error(`Failed to save ContentUnit: ${r.status}`);l.debug(`Saved ContentUnit for key "${e}"`)}catch(n){throw l.debug(`API setContentUnit failed for key "${e}":`,n),n}}async setBatchContentUnits(e){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("setBatch");l.debug(`API POST Batch ContentUnits: ${t} (${e.length} items)`);let n=await this.makeRequest(t,"POST",{translations:e,format:"contentunit"});if(!n.ok)throw new Error(`Failed to sync batch ContentUnits: ${n.status}`);l.debug(`Batch ContentUnit sync successful: ${e.length} items`)}catch(t){throw l.debug(`API setBatchContentUnits failed for ${e.length} items:`,t),t}}async remove(e){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("removeTranslation",{key:e}),n=await this.makeRequest(t,"DELETE");if(!n.ok)throw new Error(`Failed to remove translation: ${n.status}`)}catch(t){throw l.debug(`API remove failed for key "${e}":`,t),t}}async clear(){if(!this.config?.options?.baseUrl)return l.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let e=this.buildUrl("clearTranslations"),t=await this.makeRequest(e,"DELETE");if(!t.ok)throw new Error(`Failed to clear translations: ${t.status}`)}catch(e){throw l.debug("API clear failed:",e),e}}getConfig(){return this.config}getSnapshot(e){let t=this.namespaceSnapshots.get(e);if(t)return t;try{localStorage.removeItem($.LEGACY_VERSION_PREFIX+e);let n=localStorage.getItem($.SNAPSHOT_PREFIX+e);if(n){let r=JSON.parse(n);if(r&&typeof r.version=="string"&&r.version.length>0&&r.translations&&typeof r.translations=="object")return this.namespaceSnapshots.set(e,r),r;localStorage.removeItem($.SNAPSHOT_PREFIX+e)}}catch{}}setSnapshot(e,t){this.namespaceSnapshots.set(e,t);try{localStorage.setItem($.SNAPSHOT_PREFIX+e,JSON.stringify(t)),localStorage.removeItem($.LEGACY_VERSION_PREFIX+e)}catch{}}handleHttpError(e,t){if(l.debug(`API response: ${e.status} ${e.statusText}`),e.status===404)throw new b(t);if(e.status===423){let n=e.headers.get("Retry-After");throw new N(t,n?parseInt(n,10)*1e3:void 0)}throw e.status>=500&&e.status<600?new B(t,e.status):new k(`HTTP ${e.status}: ${e.statusText}`)}handleCaughtError(e){throw e instanceof b||e instanceof N||e instanceof B||e instanceof k?e:new k("Network request failed",e)}buildUrl(e,t={}){let n=this.config.options?.baseUrl||"",r=this.config.options?.endpoints?.[e]||this.DEFAULT_ENDPOINTS[e];r.startsWith("/")||(r=`/${r}`);let s=r;for(let[i,o]of Object.entries(t)){let c=new RegExp(`:${i}`,"g");s=s.replace(c,encodeURIComponent(o))}return`${n}${s}`}makeRequest(e,t,n,r){if(this.authFailedStatus!==null)return Promise.resolve(new Response(null,{status:this.authFailedStatus,statusText:`auth latched off after ${this.authFailedStatus}`}));if(t!=="GET")return this.writesFailedStatus!==null?Promise.resolve(new Response(null,{status:this.writesFailedStatus,statusText:`writes latched off after ${this.writesFailedStatus}`})):this.doFetch(e,t,n,r).then(u=>this.recordOutcome(e,t,u));let s=this.negativeCache.get(e);if(s){if(Date.now()<s.until){l.debug(`Negative-cache hit (${s.status}): ${e}`);let u=s.status===423?{"Retry-After":String(Math.ceil((s.until-Date.now())/1e3))}:void 0;return Promise.resolve(new Response(null,{status:s.status,statusText:"negative cache",headers:u}))}this.negativeCache.delete(e)}let i=`${e}|${r?.["If-None-Match"]??""}`,o=this.inflightGets.get(i);if(o)return o.then(u=>this.cloneResponse(u));let c=this.doFetch(e,t,n,r).then(u=>this.recordOutcome(e,t,u)).finally(()=>this.inflightGets.delete(i));return this.inflightGets.set(i,c),c.then(u=>this.cloneResponse(u))}recordOutcome(e,t,n){let r=n.status;if(r===401||r===403&&t==="GET")return this.authFailedStatus===null&&(this.authFailedStatus=r,console.warn(`[LionRapid] API key rejected (${r}) \u2014 network translations are disabled for this session. Fix the key and reload; retrying cannot heal an auth failure.`)),n;if((r===403||r===429)&&t!=="GET")return this.writesFailedStatus===null&&(this.writesFailedStatus=r,l.warn(`Write path disabled after ${r} (scope/quota) \u2014 running read-only`)),n;if(t==="GET"&&(r===404||r===423)){let s=r===423?Number(n.headers?.get?.("Retry-After")):NaN,i=Number.isFinite(s)&&s>0?s*1e3:this.config.options?.negativeCacheTtlMs??$.DEFAULT_NEGATIVE_TTL_MS;this.negativeCache.set(e,{status:r,until:Date.now()+i})}else t!=="GET"&&n.ok?this.negativeCache.clear():t==="GET"&&n.ok&&this.negativeCache.delete(e);return n}cloneResponse(e){return typeof e.clone=="function"?e.clone():e}async doFetch(e,t,n,r){let s=new AbortController,i=this.config.options?.timeout??1e4,o=setTimeout(()=>s.abort(),i);try{let c={"Content-Type":"application/json",[Yt]:Qt,...this.config.options?.headers,...r};return this.config.options?.apiKey&&(c.Authorization=`Bearer ${this.config.options.apiKey}`),await fetch(e,{method:t,headers:c,body:n?JSON.stringify(n):void 0,signal:s.signal})}finally{clearTimeout(o)}}};d($,"SNAPSHOT_PREFIX","lionrapid:ns:"),d($,"LEGACY_VERSION_PREFIX","lionrapid:v:"),d($,"DEFAULT_NEGATIVE_TTL_MS",6e4);var J=$;var Zt={emails:!0,urls:!0,numbers:!0,phones:!0},Se={email:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,url:/^(https?:\/\/|www\.)[^\s]+$/i,number:/^[\d\s.,+-]+$/,phone:/^[+\d][\d\s().-]{6,}$/},K=class{constructor(e={},t=2){d(this,"patterns");d(this,"minTextLength");this.patterns={...Zt,...e},this.minTextLength=t}shouldExclude(e){let t=e.trim();return!!(t.length<this.minTextLength||this.patterns.emails&&Se.email.test(t)||this.patterns.urls&&Se.url.test(t)||this.patterns.numbers&&Se.number.test(t)||this.patterns.phones&&Se.phone.test(t))}};function H(a){let e={},t=0;function n(s){if(s.nodeType===Node.TEXT_NODE)return s.nodeValue??"";if(s.nodeType!==Node.ELEMENT_NODE)return"";let i=s,o=i.tagName.toLowerCase(),c={};for(let m=0;m<i.attributes.length;m++){let g=i.attributes[m];c[g.name.toLowerCase()]=g.value}t++;let u=t;if(e[String(u)]=[`raw:${z(o,c)}`],F.has(o))return`<${u}/>`;let p="";for(let m=0;m<s.childNodes.length;m++)p+=n(s.childNodes[m]);return`<${u}>${p}</${u}>`}let r="";for(let s=0;s<a.childNodes.length;s++)r+=n(a.childNodes[s]);return{text:r,styles:e}}var ie="p,h1,h2,h3,h4,h5,h6,li,td,th,label,button,figcaption,dt,dd,summary,caption",Ke="a",qt=new Set(["SCRIPT","STYLE","CODE","PRE","TEXTAREA","NOSCRIPT","SVG"]),en=["data-lionrapid-translated","data-lionrapid-client","data-no-translate","data-lr-block"],X=class{constructor(e={},t=[],n=2){d(this,"excludeFilter");d(this,"excludeSelectors");this.excludeFilter=new K(e,n),this.excludeSelectors=t}extract(e,t=!1){let n=[],r=e.querySelectorAll(ie),s=[];e instanceof Element&&e.matches(ie)&&s.push(e);for(let i=0;i<r.length;i++)s.push(r[i]);for(let i=0;i<s.length;i++){let o=s[i];if(this.isInsideSkipTag(o)||!t&&this.hasSkipAttribute(o)||this.matchesExcludeSelector(o)||o.getAttribute("translate")==="no"||o.querySelector(ie))continue;let c=o.getAttribute("data-lr-block"),u=o.getAttribute("data-lr-original"),p;if(u){let h=document.createElement(o.tagName);h.innerHTML=u,p=H(h)}else p=H(o);let m=p.text.replace(/<\/?[0-9]+\/?>/g,"");if(this.excludeFilter.shouldExclude(m))continue;let g;if(c)g=c;else{let h=o.getAttribute("data-i18n");h?g=h.includes(":")?h:`common:${h}`:g=A(p.text)}n.push({element:o,unit:p,key:g})}return this.extractOrphanInline(e,n,t),n}extractOrphanInline(e,t,n){let r=e.querySelectorAll(Ke),s=[];e instanceof Element&&e.matches(Ke)&&s.push(e);for(let i=0;i<r.length;i++)s.push(r[i]);for(let i=0;i<s.length;i++){let o=s[i];if(this.isInsideSkipTag(o)||!n&&this.hasSkipAttribute(o)||this.matchesExcludeSelector(o)||o.getAttribute("translate")==="no"||o.parentElement?.closest(ie)||o.parentElement?.closest(Ke)||o.querySelector(ie))continue;let c=o.getAttribute("data-lr-original"),u;if(c){let h=document.createElement(o.tagName);h.innerHTML=c,u=H(h)}else u=H(o);let p=u.text.replace(/<\/?[0-9]+\/?>/g,"");if(this.excludeFilter.shouldExclude(p))continue;let m=o.getAttribute("data-lr-block"),g;if(m)g=m;else{let h=o.getAttribute("data-i18n");h?g=h.includes(":")?h:`common:${h}`:g=A(u.text)}t.push({element:o,unit:u,key:g})}}isInsideSkipTag(e){let t=e.parentElement;for(;t;){if(qt.has(t.tagName.toUpperCase()))return!0;t=t.parentElement}return!1}hasSkipAttribute(e){let t=e;for(;t;){for(let n of en)if(t.hasAttribute(n))return!0;t=t.parentElement}return!1}matchesExcludeSelector(e){for(let t of this.excludeSelectors)try{if(e.matches(t)||e.closest(t))return!0}catch{}return!1}};var tn=[{selector:'img[alt], area[alt], input[type="image"][alt]',attr:"alt",type:"alt"},{selector:"[title]",attr:"title",type:"title"},{selector:"input[placeholder], textarea[placeholder]",attr:"placeholder",type:"placeholder"},{selector:'meta[name="description"][content]',attr:"content",type:"meta-description"},{selector:'meta[property="og:title"][content], meta[name="og:title"][content], meta[property="twitter:title"][content], meta[name="twitter:title"][content]',attr:"content",type:"title"},{selector:'meta[property="og:description"][content], meta[name="og:description"][content], meta[property="twitter:description"][content], meta[name="twitter:description"][content]',attr:"content",type:"meta-description"},{selector:'input[type="submit"][value], input[type="button"][value], input[type="reset"][value]',attr:"value",type:"input-value"}],nn=new Set(["SCRIPT","STYLE","CODE","PRE","NOSCRIPT","SVG"]),rn=["data-lionrapid-translated","data-lionrapid-client","data-no-translate"];function sn(a){return`data-lr-attr-${a.toLowerCase()}`}var Y=class{constructor(e={},t=[],n=2){d(this,"excludeFilter");d(this,"excludeSelectors");this.excludeFilter=new K(e,n),this.excludeSelectors=t}extract(e,t=!1){let n=[];for(let r of tn){let s=e.querySelectorAll(r.selector),i=[];e instanceof Element&&e.matches(r.selector)&&i.push(e);for(let o=0;o<s.length;o++)i.push(s[o]);for(let o=0;o<i.length;o++){let c=i[o];if(this.isInsideSkipTag(c)||this.hasSkipAncestor(c)||this.matchesExcludeSelector(c)||c.getAttribute("translate")==="no")continue;let u=c.getAttribute(r.attr);if(u===null)continue;let p=u.trim();if(this.excludeFilter.shouldExclude(p))continue;let m=sn(r.attr),g=c.getAttribute(m);if(!t&&g)continue;let h={text:u,type:r.type},y=g??A(u);n.push({element:c,attrName:r.attr,unit:h,key:y})}}return n}isInsideSkipTag(e){let t=e.parentElement;for(;t;){if(nn.has(t.tagName.toUpperCase()))return!0;t=t.parentElement}return!1}hasSkipAncestor(e){let t=e;for(;t;){for(let n of rn)if(t.hasAttribute(n))return!0;t=t.parentElement}return!1}matchesExcludeSelector(e){for(let t of this.excludeSelectors)try{if(e.matches(t)||e.closest(t))return!0}catch{}return!1}};var Q=class{constructor(e,t=50){d(this,"observer",null);d(this,"callbacks");d(this,"debounceTimer",null);d(this,"pendingElements",new Set);d(this,"debounceMs");this.callbacks=e,this.debounceMs=t}start(){this.observer||(this.observer=new MutationObserver(e=>{this.handleMutations(e)}),this.observer.observe(document.body,{childList:!0,subtree:!0}))}stop(){this.observer&&(this.observer.disconnect(),this.observer=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingElements.clear()}handleMutations(e){let t=!1;for(let n of e)for(let r of Array.from(n.addedNodes)){if(r.nodeType!==Node.ELEMENT_NODE)continue;let s=r;this.hasLanguageSwitcher(s)&&(t=!0),this.callbacks.onNewContent&&this.pendingElements.add(s)}t&&this.callbacks.onNewSwitchers&&this.callbacks.onNewSwitchers(),this.pendingElements.size>0&&this.scheduleFlush()}scheduleFlush(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.flushPendingElements()},this.debounceMs)}flushPendingElements(){if(!(!this.callbacks.onNewContent||this.pendingElements.size===0)){for(let e of this.pendingElements)document.body.contains(e)&&this.callbacks.onNewContent(e);this.pendingElements.clear()}}hasLanguageSwitcher(e){return e.hasAttribute("data-lionrapid-switcher")||e.querySelector("[data-lionrapid-switcher]")!==null}};var an=new G,Z=class{constructor(e={}){d(this,"core",null);d(this,"blockExtractor");d(this,"attributeExtractor");d(this,"domObserver",null);d(this,"locale","");d(this,"sourceLocale","");d(this,"namespace","");d(this,"debounceMs");d(this,"pendingElements",new Set);d(this,"debounceTimer",null);d(this,"translatedCount",0);this.blockExtractor=new X(e.excludePatterns,e.excludeSelectors,e.minTextLength),this.attributeExtractor=new Y(e.excludePatterns,e.excludeSelectors,e.minTextLength),this.debounceMs=e.debounceMs??100}setCore(e){this.core=e}init(e){this.locale=e.locale,this.sourceLocale=e.sourceLocale,this.namespace=e.namespace}updateLocale(e){this.locale=e}isReady(){return this.core!==null}generateAutoKey(e){return A(e)}queueElement(e){this.pendingElements.add(e),this.scheduleProcessing()}translateElement(e){if(!this.core)return 0;let t=this.translateBlocks(this.blockExtractor.extract(e)),n=this.translateAttributesIn(this.attributeExtractor.extract(e));return t+n}translatePage(){return this.translateElement(document.body)}observe(){this.domObserver||(this.domObserver=new Q({onNewContent:e=>this.queueElement(e)}),this.domObserver.start())}stopObserving(){this.domObserver&&(this.domObserver.stop(),this.domObserver=null)}scheduleProcessing(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processPendingElements()},this.debounceMs)}processPendingElements(){if(!this.core||this.pendingElements.size===0)return;let e=0;for(let t of this.pendingElements){if(!document.body.contains(t))continue;let n=this.translateElement(t);e+=n}this.pendingElements.clear(),this.translatedCount+=e}translateBlocks(e){if(!this.core)return 0;let t=0;for(let{element:n,unit:r,key:s}of e){let i=`${this.locale}:${this.namespace}:${s}`,o=this.core.cache.get(i);if(o&&o.value!==r.text&&o.value!==s){n.hasAttribute("data-lr-original")||n.setAttribute("data-lr-original",n.innerHTML);let c=o.styles&&Object.keys(o.styles).length>0,u=Object.keys(r.styles).length>0,p=/<\/?[0-9]+\/?>/.test(o.value);if(!(u&&!p)){let m=c?o.styles:r.styles,g={text:o.value,styles:m};n.innerHTML=an.serialize(g)}n.setAttribute("data-lr-block",s),n.setAttribute("data-lionrapid-client","1"),t++}else this.core.bus.emit("translation:not-found",{payload:{key:s,fallbackValue:r.text,locale:this.sourceLocale,namespace:this.namespace,status:404,styles:r.styles}})}return t}translateAttributesIn(e){if(!this.core)return 0;let t=0;for(let{element:n,attrName:r,unit:s,key:i}of e){let o=`${this.locale}:${this.namespace}:${i}`,c=this.core.cache.get(o);if(c&&c.value!==s.text&&c.value!==i){let u=r.toLowerCase(),p=`data-lr-orig-${u}`;n.hasAttribute(p)||n.setAttribute(p,s.text),n.setAttribute(r,c.value),n.setAttribute(`data-lr-attr-${u}`,i);let m=n.getAttribute("data-lionrapid-client-attrs")??"",g=new Set(m.split(",").filter(Boolean));g.add(u),n.setAttribute("data-lionrapid-client-attrs",Array.from(g).join(",")),t++}else this.core.bus.emit("translation:not-found",{payload:{key:i,fallbackValue:s.text,locale:this.sourceLocale,namespace:this.namespace,status:404,styles:{}}})}return t}getTranslatedCount(){return this.translatedCount}restoreClientAttributes(e){let t=e.getAttribute("data-lionrapid-client-attrs");if(t!==null){for(let n of t.split(",").filter(Boolean)){let r=e.getAttribute(`data-lr-orig-${n}`);r!==null&&(e.setAttribute(n,r),e.removeAttribute(`data-lr-orig-${n}`)),e.removeAttribute(`data-lr-attr-${n}`)}e.removeAttribute("data-lionrapid-client-attrs")}}retranslateElement(e){let t=e.getAttribute("data-lr-original");t!==null&&(e.innerHTML=t),e.removeAttribute("data-lionrapid-client"),e.removeAttribute("data-lr-block"),this.restoreClientAttributes(e),this.translateElement(e)}retranslate(){document.querySelectorAll("[data-lionrapid-client]").forEach(n=>{let r=n.getAttribute("data-lr-original");r!==null&&(n.innerHTML=r),n.removeAttribute("data-lionrapid-client"),n.removeAttribute("data-lr-block")}),document.querySelectorAll("[data-lionrapid-client-attrs]").forEach(n=>this.restoreClientAttributes(n)),this.translatedCount=0,this.locale!==this.sourceLocale&&this.translatePage()}};var tt={en:{code:"en",name:"English",flag:"\u{1F1EC}\u{1F1E7}"},es:{code:"es",name:"Espa\xF1ol",flag:"\u{1F1EA}\u{1F1F8}"},fr:{code:"fr",name:"Fran\xE7ais",flag:"\u{1F1EB}\u{1F1F7}"},de:{code:"de",name:"Deutsch",flag:"\u{1F1E9}\u{1F1EA}"},it:{code:"it",name:"Italiano",flag:"\u{1F1EE}\u{1F1F9}"},pt:{code:"pt",name:"Portugu\xEAs",flag:"\u{1F1F5}\u{1F1F9}"},nl:{code:"nl",name:"Nederlands",flag:"\u{1F1F3}\u{1F1F1}"},pl:{code:"pl",name:"Polski",flag:"\u{1F1F5}\u{1F1F1}"},ru:{code:"ru",name:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",flag:"\u{1F1F7}\u{1F1FA}"},ja:{code:"ja",name:"\u65E5\u672C\u8A9E",flag:"\u{1F1EF}\u{1F1F5}"},ko:{code:"ko",name:"\uD55C\uAD6D\uC5B4",flag:"\u{1F1F0}\u{1F1F7}"},zh:{code:"zh",name:"\u4E2D\u6587",flag:"\u{1F1E8}\u{1F1F3}"},ar:{code:"ar",name:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",flag:"\u{1F1F8}\u{1F1E6}"},hi:{code:"hi",name:"\u0939\u093F\u0928\u094D\u0926\u0940",flag:"\u{1F1EE}\u{1F1F3}"},tr:{code:"tr",name:"T\xFCrk\xE7e",flag:"\u{1F1F9}\u{1F1F7}"},vi:{code:"vi",name:"Ti\u1EBFng Vi\u1EC7t",flag:"\u{1F1FB}\u{1F1F3}"},th:{code:"th",name:"\u0E44\u0E17\u0E22",flag:"\u{1F1F9}\u{1F1ED}"},sv:{code:"sv",name:"Svenska",flag:"\u{1F1F8}\u{1F1EA}"},da:{code:"da",name:"Dansk",flag:"\u{1F1E9}\u{1F1F0}"},fi:{code:"fi",name:"Suomi",flag:"\u{1F1EB}\u{1F1EE}"},no:{code:"no",name:"Norsk",flag:"\u{1F1F3}\u{1F1F4}"},cs:{code:"cs",name:"\u010Ce\u0161tina",flag:"\u{1F1E8}\u{1F1FF}"},el:{code:"el",name:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",flag:"\u{1F1EC}\u{1F1F7}"},he:{code:"he",name:"\u05E2\u05D1\u05E8\u05D9\u05EA",flag:"\u{1F1EE}\u{1F1F1}"},id:{code:"id",name:"Bahasa Indonesia",flag:"\u{1F1EE}\u{1F1E9}"},ms:{code:"ms",name:"Bahasa Melayu",flag:"\u{1F1F2}\u{1F1FE}"},uk:{code:"uk",name:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",flag:"\u{1F1FA}\u{1F1E6}"},ro:{code:"ro",name:"Rom\xE2n\u0103",flag:"\u{1F1F7}\u{1F1F4}"},hu:{code:"hu",name:"Magyar",flag:"\u{1F1ED}\u{1F1FA}"},sk:{code:"sk",name:"Sloven\u010Dina",flag:"\u{1F1F8}\u{1F1F0}"},bg:{code:"bg",name:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",flag:"\u{1F1E7}\u{1F1EC}"},hr:{code:"hr",name:"Hrvatski",flag:"\u{1F1ED}\u{1F1F7}"},sr:{code:"sr",name:"\u0421\u0440\u043F\u0441\u043A\u0438",flag:"\u{1F1F7}\u{1F1F8}"},sl:{code:"sl",name:"Sloven\u0161\u010Dina",flag:"\u{1F1F8}\u{1F1EE}"},lt:{code:"lt",name:"Lietuvi\u0173",flag:"\u{1F1F1}\u{1F1F9}"},lv:{code:"lv",name:"Latvie\u0161u",flag:"\u{1F1F1}\u{1F1FB}"},et:{code:"et",name:"Eesti",flag:"\u{1F1EA}\u{1F1EA}"}},on=`
|
|
3
|
+
`).slice(t).map(r=>r.trim()).filter(r=>r.startsWith("at ")).slice(0,Nt).map(r=>le(r,Lt));return[ce(a),...n].join(" | ")}let e;try{e=JSON.stringify(a)}catch{return"[unserializable]"}return le(e??Te(String(a)),kt)}function U(a){return`${xt(a)}, ${Tt(a)}`}var Ne=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.NONE=4]="NONE",s))(Ne||{});var _=typeof process<"u"&&process.env?process.env:{},Ve=_.NODE_ENV==="production",Le=_.NODE_ENV==="development",Fe=_.CI==="true",$t=_.LIONRAPID_DEV==="true",At=_.LIONRAPID_PERFORMANCE_TRACKING==="true";function Pt(){try{if(typeof localStorage<"u"){let a=localStorage.getItem("LIONRAPID_LOG_LEVEL");if(a&&typeof a=="string")return a}}catch{}return null}var ze=Pt()||_.LOG_LEVEL||"WARN",w={RESET:"\x1B[0m",BLACK:"\x1B[30m",RED:"\x1B[31m",GREEN:"\x1B[32m",YELLOW:"\x1B[33m",BLUE:"\x1B[34m",MAGENTA:"\x1B[35m",CYAN:"\x1B[36m",WHITE:"\x1B[37m",ORANGE:"\x1B[38;5;208m",BRIGHT_BLACK:"\x1B[90m",BRIGHT_RED:"\x1B[91m",BRIGHT_GREEN:"\x1B[92m",BRIGHT_YELLOW:"\x1B[93m",BRIGHT_BLUE:"\x1B[94m",BRIGHT_MAGENTA:"\x1B[95m",BRIGHT_CYAN:"\x1B[96m",BRIGHT_WHITE:"\x1B[97m",BOLD:"\x1B[1m",DIM:"\x1B[2m",UNDERLINE:"\x1B[4m"},$e=class a{constructor(e={}){d(this,"config");this.config={level:this.getLogLevelFromEnv(),enabled:this.shouldEnableLogging(),prefix:`${e.packageEmoji||"\u{1F4E6}"} ${e.packageName||"LionRapid"}`,showLineNumbers:$t&&!Fe,useColors:this.shouldUseColors(),...e}}configure(e){this.config={...this.config,...e}}debug(e,t){!this.config.enabled||this.config.level>0||this.log(0,e,t)}info(e,t){this.config.level>1||this.log(1,e,t)}warn(e,t){this.log(2,e,t)}error(e,t){this.log(3,e,t)}time(e){if(!At||Ve)return()=>{};let t=Le?performance.now():0;return()=>{if(Le){let n=performance.now()-t;this.debug(`\u23F1\uFE0F ${e}: ${n.toFixed(2)}ms`,{duration:n})}}}log(e,t,n){if(!this.config.enabled||e<this.config.level)return;let r=Ne[e],s=this.getLevelEmoji(e),i=this.config.showLineNumbers?this.getCallSite():null,o=this.buildColoredMessage(e,s,r,t,i,n);switch(e){case 3:console.error(o);break;case 2:console.warn(o);break;case 1:console.info(o);break;default:console.log(o)}}buildColoredMessage(e,t,n,r,s,i){if(!this.config.useColors){let T=s?` (${s.fileName}:${s.lineNumber})`:"",x=`${this.config.prefix} ${t} ${n} ${r}${T}`;return i!==void 0&&(x+=` ${ke(i)}`),x}let o=this.getLevelColor(e),l=w.RESET,u=`${w.BOLD}${w.ORANGE}${this.config.prefix}${l}`,p=t,m=`${o}${w.BOLD}${n}${l}`,g=`${o}${r}${l}`,h=s?`${w.DIM}${w.BRIGHT_BLACK} (${s.fileName}:${s.lineNumber})${l}`:"",f=i!==void 0?`${w.DIM}${w.CYAN} ${ke(i)}${l}`:"";return`${u} ${p} ${m} ${g}${h}${f}`}getLevelColor(e){switch(e){case 0:return w.BRIGHT_GREEN;case 1:return w.BRIGHT_CYAN;case 2:return w.BRIGHT_YELLOW;case 3:return w.BRIGHT_RED;default:return w.BRIGHT_BLACK}}getLevelEmoji(e){switch(e){case 0:return"\u{1F50D}";case 1:return"\u2139\uFE0F";case 2:return"\u26A0\uFE0F";case 3:return"\u274C";default:return"\u{1F4DD}"}}getCallSite(){try{let e=new Error().stack;if(!e)return null;let t=e.split(`
|
|
4
|
+
`);for(let n=3;n<t.length;n++){let r=t[n];if(r&&!r.includes("logger.ts")&&!r.includes("Logger"))return this.parseStackLine(r)}}catch{}return null}parseStackLine(e){let t=e.match(/at\s+(.+?)\s+\((.+):(\d+):(\d+)\)/);return t?{functionName:t[1],fileName:this.extractFileName(t[2]),lineNumber:parseInt(t[3],10)}:(t=e.match(/at\s+(.+):(\d+):(\d+)/),t?{fileName:this.extractFileName(t[1]),lineNumber:parseInt(t[2],10)}:null)}extractFileName(e){let t=e.split("/");return t[t.length-1]||e}colorize(e,t){return this.config.useColors?`${w[t]}${e}${w.RESET}`:e}getColors(){return w}createPackageLogger(e,t){return new a({...this.config,packageName:e,packageEmoji:t||"\u{1F4E6}"})}getLogLevelFromEnv(){switch(ze.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":return 2;case"ERROR":return 3;case"NONE":return 4;default:return 2}}shouldEnableLogging(){return ze!=="NONE"}shouldUseColors(){return Fe?!1:typeof window<"u"?!0:(typeof process<"u",Le)}},D=()=>{},Ge=()=>()=>{},c=Ve?{configure:D,debug:D,info:D,warn:(a,e)=>{console.warn(`\u{1F981} LionRapid Core \u26A0\uFE0F ${a}`,e||"")},error:(a,e)=>{console.error(`\u{1F981} LionRapid Core \u274C ${a}`,e||"")},time:Ge,colorize:a=>a,getColors:()=>w,createPackageLogger:(a,e)=>({configure:D,debug:D,info:D,warn:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${a}`;console.warn(`${r} \u26A0\uFE0F ${t}`,n||"")},error:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${a}`;console.error(`${r} \u274C ${t}`,n||"")},time:Ge,colorize:t=>t,getColors:()=>w,createPackageLogger:D})}:new $e({packageName:"LionRapid Core",packageEmoji:"\u{1F981}"});var We=/^[a-z]{2,3}(?:-[a-z0-9]{2,4})*$/i,It=new Set(["ar","fa","he","ur","yi"]);function Ot(a){return a.split("-")[0].toLowerCase()}function Ae(a){let e=a.trim();if(!e)return e;let[t,...n]=e.split("-"),r=[t.toLowerCase()];for(let s of n)s.length===4?r.push(s[0].toUpperCase()+s.slice(1).toLowerCase()):s.length===2?r.push(s.toUpperCase()):r.push(s.toLowerCase());return r.join("-")}var Kt=Object.freeze({ara:"ar",ben:"bn",bul:"bg",ces:"cs",cmn:"zh",dan:"da",deu:"de",ell:"el",eng:"en",est:"et",fas:"fa",fin:"fi",fra:"fr",heb:"he",hin:"hi",hrv:"hr",hun:"hu",ind:"id",isl:"is",ita:"it",jpn:"ja",kor:"ko",lav:"lv",lit:"lt",msa:"ms",nld:"nl",nor:"no",pol:"pl",por:"pt",ron:"ro",rus:"ru",slk:"sk",slv:"sl",spa:"es",srp:"sr",swe:"sv",tha:"th",tur:"tr",ukr:"uk",urd:"ur",vie:"vi",yid:"yi",zho:"zh"});function Mt(a){let e=a.trim().toLowerCase();if(!e)return[];let t=e.split("-"),n=[];for(;t.length>0;){let r=t.join("-");n.includes(r)||n.push(r);let s=Kt[r];s&&!n.includes(s)&&n.push(s),t.pop()}return n}function ue(a,e,t){if(e.length===0)return t;let n=e.map(r=>({raw:r,lower:Ae(r).toLowerCase()}));for(let r of a)if(r)for(let s of Mt(r)){let i=n.find(o=>o.lower===s);if(i)return i.raw}return t}function de(a){return It.has(Ot(a))?"rtl":"ltr"}var pe=class{constructor(){d(this,"eventListeners",new Map);d(this,"debugMode",typeof process<"u"&&!1)}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}off(e,t){let n=this.eventListeners.get(e);n&&n.delete(t)}emit(e,t){let n=this.eventListeners.get(e);n&&n.forEach(r=>{try{r(t)}catch(s){console.error(`Error in event listener for ${String(e)}:`,s)}})}hasListeners(e){return this.eventListeners.has(e)&&this.eventListeners.get(e).size>0}clearEvents(){this.eventListeners.clear()}createContext(e,t,n){return{requestId:e,timestamp:performance.now(),trace:t,...n}}emitEvent(e,t,n,r){this.emit(e,{context:this.createContext(n,r),payload:t})}translation(e,t){let n=["translation"],r=t?[...n,t]:n;return{request:()=>{this.emit("translation:request",{context:this.createContext(e.id,[...n,"request"]),payload:{key:e.cleanKey}})},success:s=>{this.emit("translation:success",{context:this.createContext(e.id,[...r,"success"]),payload:{key:e.cleanKey,value:s}})},fallback:s=>{this.emit("translation:fallback",{context:this.createContext(e.id,[...n,"fallback"]),payload:{key:e.cleanKey,value:s}})},missing:(s,i,o)=>{this.emit("translation:missing",{context:this.createContext(e.id,[...n,"missing"]),payload:{key:e.cleanKey,fallbackValue:s,locale:i,namespace:o}})},notFound:(s,i,o)=>{this.emit("translation:not-found",{context:this.createContext(e.id,[...n,"not-found"]),payload:{key:e.cleanKey,fallbackValue:s,locale:i,namespace:o,status:404}})},locked:(s,i,o)=>{this.emit("translation:locked",{context:this.createContext(e.id,[...n,"locked"]),payload:{key:e.cleanKey,fallbackValue:s,locale:i,namespace:o,status:423}})}}}repo(e,t){let n=["repo",t];return{getStart:()=>{typeof e!="string"&&this.emit("repo:get:start",{context:this.createContext(e.id,[...n,"get","start"]),payload:{key:e.cleanKey,source:t}})},getSuccess:r=>{typeof e!="string"&&this.emit("repo:get:success",{context:this.createContext(e.id,[...n,"get","success"]),payload:{key:e.cleanKey,value:r,source:t}})},getMiss:()=>{typeof e!="string"&&this.emit("repo:get:miss",{context:this.createContext(e.id,[...n,"get","miss"]),payload:{key:e.cleanKey,source:t}})},setStart:r=>{typeof e!="string"&&this.emit("repo:set:start",{context:this.createContext(e.id,[...n,"set","start"]),payload:{key:e.cleanKey,value:r,source:t}})},setSuccess:r=>{let s=typeof e=="string"?"system":e.id,i=typeof e=="string"?e:e.cleanKey;this.emit("repo:set:success",{context:this.createContext(s,[...n,"set","success"]),payload:{key:i,value:r,source:t}})},error:r=>{typeof e!="string"&&this.emit("repo:error",{context:this.createContext(e.id,[...n,"error"]),payload:{key:e.cleanKey,source:t,error:r}})}}}network(e,t){let n=typeof e=="string"?e:e.cleanKey,r=typeof e=="string"?"network":e.id,s=["network",t||"request"];return{start:()=>{this.emit("network:request:start",{context:this.createContext(r,[...s,"start"]),payload:{key:n}})},success:i=>{this.emit("network:request:success",{context:this.createContext(r,[...s,"success"]),payload:{key:n,value:i,method:t||"GET"}})},error:(i,o)=>{this.emit("network:request:error",{context:this.createContext(r,[...s,"error"]),payload:{key:n,method:t||"GET",error:i,...o&&{status:o}}})},retry:(i,o,l)=>{this.emit("network:retry",{context:this.createContext(r,[...s,"retry"]),payload:{key:n,attempt:i,delayMs:o,...l&&{reason:l}}})}}}builder(){let e=["builder"],t=`build-${Date.now()}`;return{use:n=>{this.emit("builder:use",{context:this.createContext(t,[...e,"use"]),payload:{type:n}})},buildStart:(n,r)=>{this.emit("builder:build:start",{context:this.createContext(t,[...e,"build","start"]),payload:{locale:n,namespace:r}})},buildDone:(n,r)=>{this.emit("builder:build:done",{context:this.createContext(t,[...e,"build","done"]),payload:{repositories:n,plugins:r}})}}}language(e,t){let n=`lang-change-${Date.now()}`,r=["language","change"];return{start:()=>{this.emit("language:change:start",{context:this.createContext(n,[...r,"start"]),payload:{oldLocale:e,newLocale:t}})},complete:()=>{this.emit("language:change:success",{context:this.createContext(n,[...r,"complete"]),payload:{oldLocale:e,newLocale:t,dir:de(t)}})},error:s=>{this.emit("language:change:error",{context:this.createContext(n,[...r,"error"]),payload:{oldLocale:e,newLocale:t,error:s}})}}}cache(e,t,n){return this.debugMode?{start:()=>{c.debug(`\u{1F9F9} Cache ${e} starting: ${t}`)},complete:()=>{c.debug(`\u2705 Cache ${e} complete: ${n?.clearedCount||0} entries`)}}:{start:()=>{},complete:()=>{}}}};var ge=class{constructor(e){d(this,"asyncHandlers",[]);d(this,"syncHandlers",[]);d(this,"bus");this.bus=e}addSyncHandler(e){e.enabled&&(this.syncHandlers.push(e),this.sortHandlersIfNeeded(this.syncHandlers),c.debug(`Sync handler added: ${e.name}`))}handleSync(e){for(let t of this.syncHandlers)try{let n=t.lookup(e);if(n!==null&&n.value)return c.debug(`Sync hit: ${t.name} (${n.duration}ms)`),n}catch(n){c.warn(`Sync lookup failed in ${t.name}:`,n),this.bus.repo(e,t.name).error(n);continue}return null}saveToMemoryHandlers(e,t,n){let r=this.syncHandlers;r.length!==0&&(c.debug(`Saving to ${r.length} memory handlers`),r.forEach(s=>{try{s.save(e,t),c.debug(`Saved to memory: ${s.name}`)}catch(i){c.warn(`Failed to save to memory ${s.name}:`,i),this.bus.repo(e,s.name).error(i)}}))}saveNamespaceToMemoryHandlers(e,t){let n=this.syncHandlers.filter(r=>r.type==="memory"&&r.saveNamespace);n.length!==0&&(c.debug(`Saving namespace to ${n.length} memory handlers`),n.forEach(r=>{try{r.saveNamespace(e,t),c.debug(`Namespace saved to memory: ${r.name}`,{locale:t.locale,namespace:t.namespace})}catch(s){c.warn(`Failed to save namespace to memory ${r.name}:`,s),this.bus.repo(`${t.locale}:${t.namespace}`,r.name).error(s)}}))}addAsyncHandler(e){e.enabled&&(this.asyncHandlers.push(e),this.sortHandlersIfNeeded(this.asyncHandlers),c.debug(`Async handler added: ${e.name}`))}async handleAsync(e){for(let t of this.asyncHandlers)try{c.debug(`Trying handler: ${t.name}`);let n=await t.lookup(e);if(n.value&&n.status===200)return c.debug(`Async hit: ${t.name} (${n.duration}ms)`),n.namespaceLoaded?(c.debug(`Saving loaded namespace: ${n.namespaceLoaded.locale}:${n.namespaceLoaded.namespace}`),await this.saveNamespaceToHandlers(n.namespaceLoaded.data,{locale:n.namespaceLoaded.locale,namespace:n.namespaceLoaded.namespace}),n):(await this.saveToStorageHandlers(e,n,t),this.saveToMemoryHandlers(e,n,t),n);c.debug(`Handler ${t.name} returned fallback (status: ${n.status})`)}catch(n){c.warn(`Handler ${t.name} failed:`,n),this.bus.repo(e,t.name).error(n);continue}return c.debug(`No async handlers found translation for ${e.cleanKey}`),null}async saveToStorageHandlers(e,t,n){let r=this.asyncHandlers.indexOf(n),s=this.asyncHandlers.slice(0,r).filter(o=>o.type==="storage");if(s.length===0)return;c.debug(`Saving to ${s.length} storage handlers`);let i=s.map(async o=>{try{await o.save(e,t),c.debug(`Saved to storage: ${o.name}`)}catch(l){c.warn(`Failed to save to storage ${o.name}:`,l),this.bus.repo(e,o.name).error(l)}});await Promise.allSettled(i)}async saveNamespaceToStorageHandlers(e,t){let n=this.asyncHandlers.filter(s=>s.type==="storage"&&s.saveNamespace);if(n.length===0)return;c.debug(`Saving namespace to ${n.length} storage handlers`);let r=n.map(async s=>{try{await s.saveNamespace(e,t),c.debug(`Namespace saved to storage: ${s.name}`,{locale:t.locale,namespace:t.namespace})}catch(i){c.warn(`Failed to save namespace to storage ${s.name}:`,i),this.bus.repo(`${t.locale}:${t.namespace}`,s.name).error(i)}});await Promise.allSettled(r)}async forgetNamespaceInHandlers(e){for(let t of this.syncHandlers)try{t.forgetNamespace?.(e)}catch(n){c.warn(`Failed to clear namespace in ${t.name}`,n)}for(let t of this.asyncHandlers)if(!(t.type!=="storage"&&t.type!=="memory"))try{await t.forgetNamespace?.(e)}catch(n){c.warn(`Failed to clear namespace in ${t.name}`,n)}}async saveNamespaceToHandlers(e,t){this.saveNamespaceToMemoryHandlers(e,t),await this.saveNamespaceToStorageHandlers(e,t)}getSyncHandlers(){return[...this.syncHandlers]}getAsyncHandlers(){return[...this.asyncHandlers]}getChainInfo(){return{length:this.syncHandlers.length+this.asyncHandlers.length,handlers:[...this.syncHandlers.map(e=>({name:e.name,priority:e.priority,type:e.type,enabled:e.enabled})),...this.asyncHandlers.map(e=>({name:e.name,priority:e.priority,type:e.type,enabled:e.enabled}))]}}isCached(e){return this.syncHandlers.some(t=>t.isCached?.(e)===!0)||this.asyncHandlers.some(t=>t.isCached?.(e)===!0)}getEntries(){let e={},t=[...this.syncHandlers,...this.asyncHandlers];for(let n of t)n.getEntries&&(e[n.name]=n.getEntries());return e}async destroy(){let t=[...this.syncHandlers,...this.asyncHandlers].map(async n=>{try{await n.destroy?.(),c.debug(`Handler destroyed: ${n.name}`)}catch(r){c.warn(`Failed to destroy handler: ${n.name}`,r)}});await Promise.allSettled(t),this.syncHandlers=[],this.asyncHandlers=[]}sortHandlersIfNeeded(e){e.some(n=>n.priority>0)&&e.sort((n,r)=>{let s=n.priority||Number.MAX_SAFE_INTEGER,i=r.priority||Number.MAX_SAFE_INTEGER;return s-i})}async loadNamespace(e,t){for(let n of this.asyncHandlers)if(n.type==="network")try{c.debug(`Trying to load namespace: ${e}:${t} from ${n.name}`);let r=await n.loadNamespace?.(e,t);if(r&&r.data&&r.status===200)return c.debug(`Loaded namespace: ${e}:${t} from ${n.name}`),await this.saveNamespaceToStorageHandlers(r.data,{namespace:t,locale:e}),this.saveNamespaceToMemoryHandlers(r.data,{namespace:t,locale:e}),r.data;if(r&&r.status===404)return await this.forgetNamespaceInHandlers({namespace:t,locale:e}),null}catch(r){c.warn(`Failed to load namespace: ${e}:${t} from ${n.name}`,r),this.bus.repo(`${e}:${t}`,n.name).error(r);continue}return c.debug(`No handlers found namespace: ${e}:${t}`),null}clearCache(){let e=[...this.syncHandlers,...this.asyncHandlers];for(let t of e)try{t.destroy?.(),c.debug(`Cache cleared for handler: ${t.name}`)}catch(n){c.warn(`Failed to clear cache for handler: ${t.name}`,n)}c.debug("Cache cleared for all handlers")}clearNamespace(e,t){for(let n of this.syncHandlers)try{n.clearNamespace?.(e,t)}catch(r){c.warn(`Failed to clear namespace for handler: ${n.name}`,r)}c.debug(`Cleared namespace: ${e}:${t}`)}setCache(e,t,n){for(let r of this.syncHandlers)if(r.type==="memory"&&r.setCache)try{r.setCache(e,t,n)}catch(s){c.warn(`Failed to set cache in handler: ${r.name}`,s)}c.debug(`Cache set: ${e}`)}getNamespaceData(e){for(let t of this.syncHandlers)if(t.type==="memory")try{let n=t.getEntries?.();if(n&&n[e]){let r=n[e];return typeof r=="string"?JSON.parse(r):r}}catch(n){c.debug(`Error getting namespace data from ${t.name}:`,n)}return null}};function Je(a){let e=a.indexOf(":");if(e>0&&e<a.length-1){let t=a.substring(0,e),n=a.substring(e+1);return{originalKey:a,namespace:t,cleanKey:n,hasExplicitNamespace:!0}}return{originalKey:a,cleanKey:a,hasExplicitNamespace:!1}}function Xe(a,e,t){let n=a.hasExplicitNamespace?a.namespace:t;return{locale:e,namespace:n}}function I(a,e){if(!(!a||!e)){if(!e.includes(".")&&!e.includes("["))return a[e];try{let t=Ut(e),n=a;for(let r of t){if(n==null){c.debug(`\u{1F50D} Nested key resolution stopped at null/undefined for: ${e}`);return}if(typeof r=="number"){if(!Array.isArray(n)){c.debug(`\u{1F50D} Expected array for index ${r} in path: ${e}`);return}n=n[r]}else{if(typeof n!="object"){c.debug(`\u{1F50D} Expected object for key '${r}' in path: ${e}`);return}n=n[r]}}return c.debug(`\u{1F50D} Nested key resolved: ${e} \u2192 ${typeof n=="object"?"[Object]":n}`),n}catch(t){c.debug(`\u{1F50D} Nested key resolution error for '${e}':`,t);return}}}function Ut(a){let e=[],t="",n=!1;for(let r=0;r<a.length;r++){let s=a[r];if(s==="."&&!n)t&&(e.push(t),t="");else if(s==="[")t&&(e.push(t),t=""),n=!0;else if(s==="]"&&n){if(t){let i=parseInt(t,10);isNaN(i)?e.push(t):e.push(i),t=""}n=!1}else t+=s}return t&&e.push(t),e}function me(a,e,t){let n=[a];return e&&n.push(e),n.push(t),n.join(":")}function v(a,e){return`@${a}:${e}`}function A(a,e="",t,n){let r={};for(let[s,i]of Object.entries(a)){let o=e?`${e}.${s}`:s,l=me(t,n,o);typeof i=="object"&&i!==null&&"text"in i&&"styles"in i?r[l]=JSON.stringify(i):typeof i=="object"&&i!==null?Object.assign(r,A(i,o,t,n)):r[l]=JSON.stringify({text:String(i),styles:{}})}return r}function re(a,e,t,n,r){let s=performance.now(),{defaultValue:i,params:o}=Dt(t,n),l=Je(a),u=Xe(l,e,r),p=me(u.locale,u.namespace,l.cleanKey),m=u.namespace?v(u.locale,u.namespace):void 0;return{id:`${p}-${s}`,originalKey:a,originalParams:t,originalDefaultValue:n,cleanKey:l.cleanKey,hasExplicitNamespace:l.hasExplicitNamespace,parsedParams:o,parsedDefaultValue:i,locale:e,namespace:u.namespace,individualCacheKey:p,namespaceCacheKey:m,startTime:s}}function Dt(a,e){let t,n;return typeof a=="object"&&typeof e=="object"&&(typeof process>"u"||!1)&&console.warn("[LionRapid] Warning: Both secondParam and thirdParam are objects. Expected pattern: t(key, params, defaultValue) or t(key, defaultValue, params). Second object will be ignored as it cannot be a defaultValue."),typeof a=="string"?(t=a,typeof e=="object"&&(n=e)):typeof a=="object"&&(n=a,typeof e=="string"&&(t=e)),{defaultValue:t,params:n}}var he=class{constructor(e,t){d(this,"name");d(this,"version","1.0.0");d(this,"priority");d(this,"type","memory");d(this,"enabled");d(this,"ttlMap",new Map);d(this,"ttl");d(this,"repository");d(this,"bus");this.bus=e,this.repository=t,this.name=t.name;let n=t.getConfig();this.enabled=n.enabled??!0,this.priority=n.priority??0,this.ttl=n.options?.ttl??1800*1e3}getSourceType(){return"memory"}lookup(e){let t=Date.now();c.debug(`Sync lookup: ${e.cleanKey}`);let n=this.bus.repo(e,this.name);n.getStart();let r=this.tryDirectLookup(e);if(r!==null)return c.debug(`Cache hit: ${e.cleanKey}`),n.getSuccess(r.text),this.createResult(r,"memory",200,t,!0);if(e.cleanKey.includes(".")&&e.namespace){let s=this.tryNamespaceLookup(e);if(s!==null)return c.debug(`Namespace hit: ${e.cleanKey}`),n.getSuccess(s.text),this.createResult(s,"memory",200,t,!0)}return c.debug(`Cache miss: ${e.cleanKey}`),n.getMiss(),this.createResult({text:e.parsedDefaultValue||e.cleanKey,styles:{}},"fallback",404,t)}save(e,t){if(!t.value)return;let n=this.bus.repo(e,this.name),r={text:t.value,styles:t.styles||{}};this.setWithTTL(e.individualCacheKey,JSON.stringify(r)),c.debug(`Saved to cache: ${e.cleanKey}`),n.setSuccess(t.value)}saveNamespace(e,t){if(!t.namespace)return;let n=this.bus.repo(t.locale+":"+t.namespace,this.name),r=this.storedNamespaceKeys(t.locale,t.namespace),s=v(t.locale,t.namespace);this.setWithTTL(s,JSON.stringify(e));let i=A(e,"",t.locale,t.namespace);for(let o of r)o in i||this.removeQuietly(o);for(let[o,l]of Object.entries(i))this.setWithTTL(o,l);n.setSuccess(JSON.stringify(e))}forgetNamespace(e){if(e.namespace){for(let t of this.storedNamespaceKeys(e.locale,e.namespace))this.removeQuietly(t);this.clearNamespace(e.locale,e.namespace)}}storedNamespaceKeys(e,t){try{let n=this.repository.get(v(e,t));return n?Object.keys(A(JSON.parse(n),"",e,t)):[]}catch{return[]}}removeQuietly(e){this.ttlMap.delete(e);try{this.repository.remove(e)}catch{}}tryDirectLookup(e){if(this.checkAndExpireTTL(e.individualCacheKey))return null;let t=this.repository.get(e.individualCacheKey);if(!t)return null;this.refreshTTL(e.individualCacheKey);try{let n=JSON.parse(t);return typeof n=="object"&&"text"in n?{text:String(n.text),styles:n.styles||{}}:{text:t,styles:{}}}catch{return{text:t,styles:{}}}}tryNamespaceLookup(e){if(!e.namespace)return null;let t=v(e.locale,e.namespace);if(this.checkAndExpireTTL(t))return null;let n=this.repository.get(t);if(!n)return null;this.refreshTTL(t);try{let r=JSON.parse(n),s=I(r,e.cleanKey);if(s!=null){let i;return typeof s=="object"&&s!==null&&"text"in s?i={text:String(s.text),styles:s.styles||{}}:i={text:String(s),styles:{}},this.setWithTTL(e.individualCacheKey,JSON.stringify(i)),c.debug(`Cached from namespace: ${e.cleanKey}`),i}}catch(r){c.debug(`Invalid JSON in namespace cache: ${t}`,r),this.repository.remove(t),this.ttlMap.delete(t)}return null}createResult(e,t,n,r,s){return{value:e.text,styles:e.styles,source:t,status:n,duration:Date.now()-r,...s!==void 0&&{cached:s}}}checkAndExpireTTL(e){let t=this.ttlMap.get(e);return t&&Date.now()-t>this.ttl?(this.repository.remove(e),this.ttlMap.delete(e),c.debug(`TTL expired: ${e}`),!0):!1}setWithTTL(e,t){this.repository.set(e,t),this.ttlMap.set(e,Date.now())}refreshTTL(e){this.ttlMap.set(e,Date.now())}getTTLInfo(){let e={},t=Date.now();for(let[n,r]of this.ttlMap.entries()){let s=t-r,i=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:i}}return e}getEntries(){if(this.repository.getEntries!==void 0)return this.repository.getEntries()}clearNamespace(e,t){let n=v(e,t),r=`${e}:${t}:`;this.repository.remove(n),this.ttlMap.delete(n);let s=this.repository.getEntries?.();if(s)for(let i of Object.keys(s))i.startsWith(r)&&(this.repository.remove(i),this.ttlMap.delete(i));c.debug(`Cleared namespace: ${e}:${t}`)}destroy(){this.repository.clear(),this.ttlMap.clear()}setCache(e,t,n){let r={text:t,styles:n||{}};this.setWithTTL(e,JSON.stringify(r)),c.debug(`Direct cache set: ${e}`)}};var fe=class{constructor(e,t){d(this,"name");d(this,"version","1.0.0");d(this,"priority");d(this,"type","storage");d(this,"enabled");d(this,"ttlMap",new Map);d(this,"ttl");d(this,"repository");d(this,"bus");this.bus=e,this.repository=t,this.name=t.name;let n=t.getConfig();this.enabled=n.enabled??!0,this.priority=n.priority??0,this.ttl=n.options?.ttl??1800*1e3}getSourceType(){return"memory"}async lookup(e){let t=Date.now();c.debug(`Async lookup: ${e.cleanKey}`);let n=this.bus.repo(e,this.name),r=await this.tryDirectLookup(e);if(r!==null)return c.debug(`Cache hit: ${e.cleanKey}`),n.getSuccess(r.text),this.createResult(r,"storage",200,t,!0);if(e.cleanKey.includes(".")&&e.namespace){let s=await this.tryNamespaceLookup(e);if(s!==null)return c.debug(`Namespace hit: ${e.cleanKey}`),n.getSuccess(s.text),this.createResult(s,"storage",200,t,!0)}return c.debug(`Cache miss: ${e.cleanKey}`),n.getMiss(),this.createResult({text:e.parsedDefaultValue||e.cleanKey,styles:{}},"fallback",404,t)}async save(e,t){if(!t.value)return;let n=this.bus.repo(e,this.name),r={text:t.value,styles:t.styles||{}};await this.setWithTTL(e.individualCacheKey,JSON.stringify(r)),c.debug(`Saved to cache: ${e.cleanKey}`),n.setSuccess(t.value)}async saveNamespace(e,t){if(!t.namespace)return;let n=this.bus.repo(t.locale+":"+t.namespace,this.name),r=Object.keys(e).length;c.debug(`Saving namespace: ${t.locale}:${t.namespace} (${r} keys)`);let s=await this.storedNamespaceKeys(t.locale,t.namespace),i=v(t.locale,t.namespace);await this.setWithTTL(i,JSON.stringify(e));let o=A(e,"",t.locale,t.namespace);for(let u of s)u in o||await this.removeQuietly(u);let l=0;for(let[u,p]of Object.entries(o))await this.setWithTTL(u,p),l++;c.debug(`Saved: ${l} keys + namespace blob`),n.setSuccess(JSON.stringify(e))}async forgetNamespace(e){if(e.namespace){for(let t of await this.storedNamespaceKeys(e.locale,e.namespace))await this.removeQuietly(t);await this.removeQuietly(v(e.locale,e.namespace))}}async storedNamespaceKeys(e,t){try{let n=await this.repository.get(v(e,t));return n?Object.keys(A(JSON.parse(n),"",e,t)):[]}catch{return[]}}async removeQuietly(e){this.ttlMap.delete(e);try{await this.repository.remove(e)}catch{}}async tryDirectLookup(e){if(await this.checkAndExpireTTL(e.individualCacheKey))return null;let t=await this.repository.get(e.individualCacheKey);if(!t)return null;this.refreshTTL(e.individualCacheKey);try{let n=JSON.parse(t);return typeof n=="object"&&"text"in n?{text:String(n.text),styles:n.styles||{}}:{text:t,styles:{}}}catch{return{text:t,styles:{}}}}async tryNamespaceLookup(e){if(!e.namespace)return null;let t=v(e.locale,e.namespace);if(await this.checkAndExpireTTL(t))return null;let n=await this.repository.get(t);if(!n)return null;this.refreshTTL(t);try{let r=JSON.parse(n),s=I(r,e.cleanKey);if(s!=null){let i;return typeof s=="object"&&s!==null&&"text"in s?i={text:String(s.text),styles:s.styles||{}}:i={text:String(s),styles:{}},await this.setWithTTL(e.individualCacheKey,JSON.stringify(i)),c.debug(`Cached from namespace: ${e.cleanKey}`),i}}catch(r){c.debug(`Invalid JSON in namespace cache: ${t}`,r),await this.repository.remove(t),this.ttlMap.delete(t)}return null}createResult(e,t,n,r,s){return{value:e.text,styles:e.styles,source:t,status:n,duration:Date.now()-r,...s!==void 0&&{cached:s}}}async checkAndExpireTTL(e){let t=this.ttlMap.get(e);return t&&Date.now()-t>this.ttl?(await this.repository.remove(e),this.ttlMap.delete(e),c.debug(`TTL expired: ${e}`),!0):!1}async setWithTTL(e,t){await this.repository.set(e,t),this.ttlMap.set(e,Date.now())}refreshTTL(e){this.ttlMap.set(e,Date.now())}getTTLInfo(){let e={},t=Date.now();for(let[n,r]of this.ttlMap.entries()){let s=t-r,i=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:i}}return e}async destroy(){await this.repository.clear(),this.ttlMap.clear()}getEntries(){if(this.repository.getEntries!==void 0)return this.repository.getEntries()}};var se=class extends Error{constructor(t,n,r){super(r);this.key=t;this.status=n;this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},b=class extends se{constructor(e){super(e,404,`Translation not found: ${e}`)}},N=class extends se{constructor(t,n){super(t,423,`Translation locked: ${t}`);this.retryAfter=n}},B=class extends se{constructor(e,t){super(e,t,`Server error ${t}: ${e}`)}},k=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="NetworkError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}};function Qe(a){return a instanceof B||a instanceof k}var ye=class{constructor(e,t){d(this,"repository");d(this,"name");d(this,"priority");d(this,"version","1.0.0");d(this,"type","network");d(this,"enabled");d(this,"bus");d(this,"retryCount");d(this,"retryDelay");this.bus=e,this.repository=t,this.name=t.name;let n=t.getConfig();this.enabled=n.enabled??!1,this.priority=n.priority??0,this.retryCount=n.options?.retries??3,this.retryDelay=n.options?.retryDelay??1e3}initialize(){return Promise.resolve()}getSourceType(){return"network"}async lookup(e){let t=Date.now(),n=e.parsedDefaultValue||e.cleanKey;if(!this.enabled)return this.createTranslationResult(n,"fallback",0,t);let r=this.bus.network(e,this.name);r.start(),c.debug(`Network lookup: ${e.cleanKey}`);try{let s=await this.lookupContentUnitWithRetry(e.individualCacheKey);return c.debug(`Network hit: ${e.cleanKey}`),r.success(s.text),this.createTranslationResult(s.text,"network",200,t,void 0,!1,void 0,s.styles)}catch(s){return s instanceof b&&e.namespace?(c.debug(`Individual key not found, trying namespace: ${e.cleanKey}`),this.lookupFromNamespace(e,n,t,r)):s instanceof N?(c.debug(`Translation locked (423): ${e.cleanKey}`),this.handleTranslationLocked(e,n,s,t,r)):(c.debug(`Network error: ${e.cleanKey}`,s),r.error(s),this.createTranslationResult(n,"fallback",0,t,s))}}async lookupFromNamespace(e,t,n,r){try{let s=await this.loadNamespace(e.locale,e.namespace);if(s&&s.data){let o=I(s.data,e.cleanKey);if(o!=null){let l,u={};if(typeof o=="object"&&o!==null&&"text"in o){let p=o;l=String(p.text),u=p.styles||{}}else l=String(o);return c.debug(`Network namespace hit: ${e.cleanKey}, hasStyles=${Object.keys(u).length>0}`),r.success(l),this.createTranslationResult(l,"network",200,n,void 0,!1,{locale:e.locale,namespace:e.namespace,data:s.data},u)}}let i=new b(e.cleanKey);return this.handleTranslationNotFound(e,t,i,n)}catch(s){return c.debug(`Namespace load failed: ${e.cleanKey}`,s),s instanceof b?this.handleTranslationNotFound(e,t,s,n):s instanceof N?this.handleTranslationLocked(e,t,s,n,r):(r.error(s),this.createTranslationResult(t,"fallback",0,n,s))}}async loadNamespace(e,t){let n=Date.now();if(!this.enabled)return this.createNamespaceResult(null,"fallback",0,n);try{let r=await this.loadNamespaceWithRetry(e,t);return r===null?(c.debug(`Network namespace not modified: ${e}:${t}`),this.createNamespaceResult(null,"network",304,n)):(c.debug(`Network namespace loaded: ${e}:${t}`),this.createNamespaceResult(r,"network",200,n))}catch(r){return r instanceof N?(c.debug(`Namespace locked (423): ${e}:${t}`),this.createNamespaceResult(null,"fallback",423,n,r)):r instanceof b?(c.debug(`Network namespace not found: ${e}:${t}`),this.createNamespaceResult(null,"fallback",404,n,r)):(c.debug(`Network namespace error: ${e}:${t}`,r),this.createNamespaceResult(null,"fallback",0,n,r))}}async loadNamespaceWithRetry(e,t){return this.withRetry(()=>this.repository.getNamespace(e,t),`${e}:${t}`,"namespace request")}async save(e,t){}async lookupWithRetry(e){return this.withRetry(()=>this.repository.get(e),e,"network request")}async lookupContentUnitWithRetry(e){let t=this.repository;return typeof t.getContentUnit!="function"?{text:await this.lookupWithRetry(e),styles:{}}:this.withRetry(()=>t.getContentUnit(e),e,"network content unit request")}delay(e){return new Promise(t=>setTimeout(t,e))}calculateBackoff(e){let n=this.retryDelay*Math.pow(2,e-1),r=1e4,s=Math.random()*.1*n;return Math.min(n+s,r)}async withRetry(e,t,n,r=1){let s=this.bus.network(t,"withRetry");try{return await e()}catch(i){if(r<=this.retryCount&&Qe(i)){let o=this.calculateBackoff(r);return s.retry(r,o,i.message),await this.delay(o),c.debug(`Retrying ${n} (${r}/${this.retryCount}) after ${o}ms`),this.withRetry(e,t,n,r+1)}throw i}}handleTranslationNotFound(e,t,n,r){return c.debug(`Network namespace miss: ${e.cleanKey}`),this.bus.translation(e).notFound(t,e.locale,e.namespace||"default"),this.createTranslationResult(t,"fallback",404,r,n)}handleTranslationLocked(e,t,n,r,s){return this.bus.translation(e).locked(t,e.locale,e.namespace||"default"),s.error(n,423),this.createTranslationResult(t,"fallback",423,r,n)}createTranslationResult(e,t,n,r,s,i,o,l){return{value:e,source:t,status:n,duration:Date.now()-r,...s&&{error:s},...i!==void 0&&{cached:i},...o&&{namespaceLoaded:o},...l&&Object.keys(l).length>0&&{styles:l}}}createNamespaceResult(e,t,n,r,s){return{data:e,source:t,status:n,duration:Date.now()-r,...s&&{error:s}}}getPreload(){return this.repository.getConfig().options?.preloadNamespaces||[]}getBaseUrl(){return this.repository.getConfig().options?.baseUrl||""}};var F=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function Ht(a){return a.replace(/"/g,""")}function z(a,e){let n=`<${a.toLowerCase()}`;for(let[r,s]of Object.entries(e))n+=` ${r.toLowerCase()}="${Ht(s)}"`;return n+=">",n}function be(a){let e=a.search(/[\s>]/);return a.slice(1,e===-1?a.length:e).toLowerCase()}function Pe(a){for(let e of a)if(e.startsWith("raw:"))return e.slice(4);return null}function Ye(a){let e={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",rsquo:"\u2019",lsquo:"\u2018",rdquo:"\u201D",ldquo:"\u201C",hellip:"\u2026",mdash:"\u2014",ndash:"\u2013",copy:"\xA9",reg:"\xAE",trade:"\u2122"};return a.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z][a-z0-9]*);/gi,(t,n)=>{if(n[0]==="#"){let r=n[1]==="x"||n[1]==="X"?parseInt(n.slice(2),16):parseInt(n.slice(1),10);if(Number.isFinite(r)&&r>0)try{return String.fromCodePoint(r)}catch{return t}return t}return e[n.toLowerCase()]??t})}var ve=class{parse(e){if(/<\/?[0-9]+>/.test(e))return{text:Ye(e),styles:{}};let t={},n=0,r=[],s="",i=0;for(;i<e.length;){let o=this.matchTag(e,i);if(!o){s+=e.slice(i);break}if(s+=e.slice(i,o.startIndex),o.isClosing){let l=null;for(let u=r.length-1;u>=0;u--)if(r[u].tag===o.tag.toLowerCase()){l=r[u].index,r.splice(u,1);break}l!==null&&(s+=`</${l}>`)}else{let l=o.tag.toLowerCase(),u=F.has(l),p=o.isSelfClosing||u;n++,t[String(n)]=[`raw:${z(l,o.attrs)}`],p?s+=`<${n}/>`:(s+=`<${n}>`,r.push({tag:l,index:n}))}i=o.endIndex}for(;r.length>0;){let o=r.pop();s+=`</${o.index}>`}return{text:Ye(s),styles:t}}matchTag(e,t){let n=e.indexOf("<",t);if(n===-1)return null;let r=/^<(\/?)([a-zA-Z][a-zA-Z0-9]*)((?:\s+[a-zA-Z][a-zA-Z0-9-]*(?:=(?:"[^"]*"|'[^']*'|[^\s>]*))?)*)\s*(\/?)>/,i=e.slice(n).match(r);if(!i)return n+1<e.length?this.matchTag(e,n+1):null;let[o,l,u,p,m]=i;return{tag:u,attrs:this.parseAttributes(p),isClosing:l==="/",isSelfClosing:m==="/",startIndex:n,endIndex:n+o.length}}parseAttributes(e){let t={};if(!e.trim())return t;let n=/([a-zA-Z][a-zA-Z0-9-]*)(?:=(?:"([^"]*)"|'([^']*)'|([^\s>]*)))?/g,r;for(;(r=n.exec(e))!==null;){let[,s,i,o,l]=r;t[s.toLowerCase()]=i??o??l??""}return t}};var jt=new Set(["a","abbr","b","bdi","bdo","br","cite","code","del","dfn","em","i","img","ins","kbd","mark","q","s","samp","small","span","strong","sub","sup","time","u","var","wbr"]),_t=new Set(["alt","cite","class","datetime","dir","height","href","id","lang","loading","rel","role","src","target","title","width"]),Bt=new Set(["href","src","cite"]),Ft=new Set(["color","background-color","font-family","font-size","font-style","font-weight","letter-spacing","line-height","text-decoration","text-decoration-color","text-decoration-line","text-decoration-style","text-transform","vertical-align","white-space","word-spacing"]),zt=/url\s*\(|expression\s*\(|image-set\s*\(|element\s*\(|paint\s*\(|javascript:|\\|[<>{}@]/i,Gt=new Set(["http","https","mailto","tel"]),Vt={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:"\xA0",colon:":",semi:";",sol:"/",bsol:"\\",Tab:" ",NewLine:`
|
|
5
|
+
`};function Ze(a){return a.replace(/&(?:#[xX]([0-9a-fA-F]+);?|#(\d+);?|([a-zA-Z]+);)/g,(e,t,n,r)=>t?String.fromCodePoint(parseInt(t,16)):n?String.fromCodePoint(parseInt(n,10)):Vt[r]??e)}function Ie(a){return a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Wt(a){let t=Ze(a).replace(/[\u0000-\u0020\u007f]/g,"").toLowerCase(),n=/^([a-z][a-z0-9+.-]*):/.exec(t);return n?Gt.has(n[1])?a:null:a}function Jt(a){return Xt(a,!0)}function Xt(a,e){let t=Ze(a),n=[];for(let r of t.split(";")){let s=r.indexOf(":");if(s===-1)continue;let i=r.slice(0,s).trim().toLowerCase(),o=r.slice(s+1).trim();/^[a-z-]+$/.test(i)&&(e&&!Ft.has(i)||o===""||zt.test(o)||n.push(`${i}: ${o}`))}return n.length>0?n.join("; "):null}var Qt=/([^\s=/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]*)))?/g;function qe(a){if(!a.startsWith("<"))return null;let e=be(a);if(!/^[a-z][a-z0-9-]*$/.test(e)||!jt.has(e))return null;let t=a.endsWith("/>")?a.length-2:a.endsWith(">")?a.length-1:a.length,n=a.slice(1+e.length,t),r={};for(let s of n.matchAll(Qt)){let i=s[1].toLowerCase(),o=s[2]??s[3]??s[4]??"";if(i in r)continue;if(i==="style"){let u=Jt(o);u!==null&&(r[i]=u);continue}(_t.has(i)||/^data-[a-z0-9-]*$/.test(i)||/^aria-[a-z0-9-]*$/.test(i))&&(Bt.has(i)&&Wt(o)===null||(r[i]=o))}return z(e,r)}var G=class{serialize(e){let{text:t,styles:n}=e,r=/<(\/?)?(\d+)(\/)?>/g,s="",i=0,o;for(;(o=r.exec(t))!==null;){s+=Ie(t.slice(i,o.index));let[l,u,p]=o,m=n[p]??[],g=Pe(m),h=g===null?null:qe(g);if(g&&h!==null){let f=be(g),T=F.has(f);u?T||(s+=`</${f}>`):s+=h}else s+=l;i=o.index+l.length}return s+=Ie(t.slice(i)),s}};var we=class{constructor(e,t,n,r){d(this,"handlerChain");d(this,"bus");d(this,"currentLocale");d(this,"loadNamespaces");this.handlerChain=e,this.bus=t,this.currentLocale=n,this.loadNamespaces=r}get(e){let t=this.handlerChain.getEntries();for(let n in t){let r=t[n];if(r&&typeof r=="object"&&e in r){let s=r[e];try{if(typeof s=="string"){let i=JSON.parse(s);return typeof i=="object"&&"text"in i?{value:String(i.text),styles:i.styles||void 0}:{value:s,styles:void 0}}return{value:JSON.stringify(s),styles:void 0}}catch{return{value:typeof s=="string"?s:JSON.stringify(s),styles:void 0}}}}return null}set(e,t,n){let[r,s,...i]=e.split(":"),o=i.join(":");if(!r||!s||!o)throw new Error(`Invalid cache key format: "${e}". Expected format: "locale:namespace:key"`);this.handlerChain.setCache(e,t,n),this.bus.emit("cache:set",{payload:{key:e,value:t,styles:n,optimistic:!0}})}has(e){return this.get(e)!==null}async invalidate(e={}){let{namespace:t,locale:n,key:r,predicate:s,refetch:i=!0}=e,o=this.currentLocale(),l=0;if(r){let[u,p]=r.split(":");u&&p&&(this.handlerChain.clearNamespace(u,p),l=1)}else if(t&&n)this.handlerChain.clearNamespace(n,t),l=this.countClearedKeys(n,t);else if(t)this.handlerChain.clearNamespace(o,t),l=this.countClearedKeys(o,t);else if(n){let u=this.handlerChain.getEntries(),p=new Set;for(let m in u){let g=u[m];if(g&&typeof g=="object"){for(let h of Object.keys(g))if(h.startsWith(`${n}:`)||h.startsWith(`@${n}:`)){let f=h.replace("@","").split(":");f[1]&&p.add(f[1])}}}for(let m of p)this.handlerChain.clearNamespace(n,m),l++}else if(s){let u=this.handlerChain.getEntries(),p=new Map;for(let m in u){let g=u[m];if(g&&typeof g=="object"){for(let h of Object.keys(g))if(s(h)){let f=h.replace("@","").split(":"),T=f[0],x=f[1];T&&x&&(p.has(T)||p.set(T,new Set),p.get(T).add(x),l++)}}}for(let[m,g]of p)for(let h of g)this.handlerChain.clearNamespace(m,h)}else this.handlerChain.clearCache(),l=-1;this.bus.emit("cache:invalidate",{payload:{filter:e,keysCleared:l,refetch:i}}),i&&await this.refetchAfterInvalidate(e)}countClearedKeys(e,t){let n=this.handlerChain.getEntries(),r=0,s=`${e}:${t}:`,i=`@${e}:${t}`;for(let o in n){let l=n[o];if(l&&typeof l=="object")for(let u of Object.keys(l))(u.startsWith(s)||u===i)&&r++}return r}async refetchAfterInvalidate(e){let{namespace:t,locale:n,key:r}=e,s=this.currentLocale();if(r){let[i,o]=r.split(":");i&&o&&await this.loadNamespaces(i,[o])}else t&&await this.loadNamespaces(n||s,[t])}};var Yt=/<\/?[0-9]+\/?>/,Zt=/<[a-z][a-z0-9]*(?:\s+[^>]*)?\/?>/i,V=class{constructor(e,t,n="en",r){d(this,"handlerChain");d(this,"currentLocale");d(this,"defaultNamespace");d(this,"pendingTranslations",new Map);d(this,"bus");d(this,"plugins",new Map);d(this,"formatters",new Map);d(this,"processors",new Map);d(this,"warnedNoInterpolate",!1);d(this,"eventPlugins",new Set);d(this,"markupParser",new ve);d(this,"htmlSerializer",new G);d(this,"cache");this.bus=e,this.handlerChain=t,this.currentLocale=n,this.defaultNamespace=r,this.cache=new we(this.handlerChain,this.bus,()=>this.currentLocale,(s,i)=>this.loadNamespaces(s,i))}registerPlugin(e){this.plugins.set(e.name,e),this.isEmbeddedPlugin(e)&&this.integrateEmbeddedPlugin(e),this.isEventPlugin(e)&&this.eventPlugins.add(e)}integrateEmbeddedPlugin(e){if(e.getFormatters){let t=e.getFormatters();Object.entries(t).forEach(([n,r])=>{this.formatters.set(n,r),c.debug(`Embedded formatter: ${n} from ${e.name}`)})}if(e.getProcessors){let t=e.getProcessors();Object.entries(t).forEach(([n,r])=>{this.processors.set(n,r),c.debug(`Embedded processor: ${n} from ${e.name}`)})}}t(e,...t){let[n,r]=t,s=re(e,this.currentLocale,n,r,this.defaultNamespace);c.debug(`Translation requested: ${s.cleanKey}`);let i=this.bus.translation(s);i.request();let o=this.handlerChain.handleSync(s);if(o&&o.status===200){let p=this.processValue(o.value,s);return c.debug(`Translation found: ${s.cleanKey} from ${o.source} (${o.duration}ms)`),i.success(p),p}this.triggerBackgroundLoad(s);let l=s.parsedDefaultValue||s.cleanKey,u=this.processValue(l,s);return c.debug(`Translation fallback: ${s.cleanKey}`),i.fallback(u),u}tHtml(e,...t){let[n,r]=t,s=re(e,this.currentLocale,n,r,this.defaultNamespace);c.debug(`HTML translation requested: ${s.cleanKey}`);let i=this.bus.translation(s);i.request();let o=this.handlerChain.handleSync(s);if(o&&o.status===200){let p=this.processValueAsHtml(o.value,s,o.styles);return c.debug(`HTML translation found: ${s.cleanKey} from ${o.source}`),i.success(p),p}this.triggerBackgroundLoad(s);let l=s.parsedDefaultValue||s.cleanKey,u=this.processValueAsHtml(l,s);return c.debug(`HTML translation fallback: ${s.cleanKey}`),i.fallback(u),u}processValueAsHtml(e,t,n){let r=this.processTranslationValue(e,t);if(this.containsIndexedTags(r)){let s=n||this.getStylesFromNamespace(t),i={text:r,styles:s};return this.htmlSerializer.serialize(i)}if(this.containsHtml(r)){let s=this.markupParser.parse(r);return this.htmlSerializer.serialize(s)}return r}processValue(e,t){return this.containsIndexedTags(e)?this.processIndexedValue(e,t):this.containsHtml(e)?this.processHtmlValue(e,t):this.processTranslationValue(e,t)}containsIndexedTags(e){return Yt.test(e)}processIndexedValue(e,t){return this.processTranslationValue(e,t).replace(/<\/?[0-9]+\/?>/g,"")}getStylesFromNamespace(e){if(!e.namespace)return{};try{let t=v(e.locale,e.namespace),n=this.handlerChain.getNamespaceData(t);if(!n)return{};let r=I(n,e.cleanKey);return r&&typeof r=="object"&&"styles"in r?r.styles:{}}catch(t){return c.debug(`Error getting styles for key ${e.cleanKey}:`,t),{}}}processHtmlValue(e,t){try{let n=this.markupParser.parse(e);return this.processTranslationValue(n.text,t).replace(/<\/?[0-9]+\/?>/g,"")}catch(n){return c.warn(`ContentUnit processing failed for key "${t.cleanKey}" \u2014 ${U(e)}: ${ce(n)}`),this.processTranslationValue(e,t)}}processTranslationValue(e,t,n,r){let s,i,o;if(t&&"cleanKey"in t){let u=t;s=u.parsedParams,i=u.locale,o=u.cleanKey}else s=t,i=n||this.currentLocale,o=r;let l=e;try{if(l=this.applyStructuralFormatters(l,s,o),this.formatters.has("interpolate")?l=this.formatters.get("interpolate")(l,s,i,o):!this.warnedNoInterpolate&&s&&Object.keys(s).length>0&&l.includes("{")&&(this.warnedNoInterpolate=!0,console.warn("[LionRapid] Translation params were passed but no interpolate formatter is registered \u2014 {placeholders} render literally. Install @lionrapid/formatters and add .use(coreFormattersPlugin) to the builder.")),this.processors.size>0)for(let[u,p]of this.processors.entries())try{l=p(l,s,o)}catch(m){c.warn(`Processor ${u} failed:`,m)}return l}catch(u){return c.warn(`Translation processing failed for key "${o??"(no key)"}" \u2014 ${U(e)}: ${ce(u)}`),e}}getContentUnit(e,t,n){let r=re(e,this.currentLocale,t,n,this.defaultNamespace),s=this.handlerChain.handleSync(r),i=s&&s.status===200?s.value:r.parsedDefaultValue||r.cleanKey;return(!s||s.status!==200)&&this.triggerBackgroundLoad(r),this.markupParser.parse(i)}processContentText(e,t){return this.processTranslationValue(e,t,this.currentLocale)}containsHtml(e){return Zt.test(e)}applyStructuralFormatters(e,t,n){let r=e,s=o=>typeof o?.count=="number",i=o=>typeof o?.context=="string";if(this.formatters.has("plural")&&s(t)){let o=this.formatters.get("plural");try{let l=o(r,t,this.currentLocale,n);if(l!==String(r))return l}catch(l){c.warn("Plural formatting failed:",l)}}if(this.formatters.has("context")&&i(t)){let o=this.formatters.get("context");try{let l=o(r,t,this.currentLocale,n);if(l!==String(r))return l}catch(l){c.warn("Context formatting failed:",l)}}return String(r)}triggerBackgroundLoad(e){c.debug(`Background load: ${e.cleanKey}`);let t=e.individualCacheKey;if(!this.pendingTranslations.has(t)){let n=this.handlerChain.handleAsync(e).then(r=>{r&&r.value?c.debug(`Cached: ${e.cleanKey} = "${r.value}"`):c.debug(`Not found: ${e.cleanKey}`)}).catch(r=>{c.warn(`Background load failed: ${e.cleanKey}`,r)});this.pendingTranslations.set(t,n),n.finally(()=>this.pendingTranslations.delete(t))}}getCurrentLocale(){return this.currentLocale}setDefaultNamespace(e){this.defaultNamespace=e}getDefaultNamespace(){return this.defaultNamespace}getEntries(){return this.handlerChain.getEntries()}isCached(e){let t=re(e,this.currentLocale,void 0,void 0,this.defaultNamespace);return this.handlerChain.isCached(t)}getHandlerChainInfo(){return this.handlerChain.getChainInfo()}async changeLanguage(e,t){let n=this.currentLocale;if(n===e){c.debug(`Language already set to ${e}`);return}let r=t?.clear||!1,s=this.bus.language(n,e);try{c.info(`Language change: ${n} \u2192 ${e}`),c.debug("Language change options",{clear:r,preloadNamespaces:t?.preloadNamespaces}),s.start(),this.currentLocale=e,r&&(await this.clearCache(),this.clearOldLocalePendingTranslations(n)),t?.preloadNamespaces?.length&&await this.loadNamespaces(e,t.preloadNamespaces),s.complete(),c.info(`Language changed: ${e}`)}catch(i){throw c.error("Language change failed:",i),s.error(i),i}}async clearCache(){this.handlerChain.clearCache(),c.debug(`Cache cleared for locale: ${this.currentLocale}`)}clearOldLocalePendingTranslations(e){let t=0;for(let n of this.pendingTranslations.keys())n.includes(`${e}:`)&&(this.pendingTranslations.delete(n),t++);t>0&&c.debug(`Cleared ${t} pending translations for ${e}`)}async loadNamespaces(e,t){c.debug(`Preloading ${t.length} namespaces for ${e}`);let n=t.map(async r=>{try{await this.handlerChain.loadNamespace?.(e,r),c.debug(`Preloaded: ${e}:${r}`)}catch(s){c.warn(`Failed to preload ${e}:${r}:`,s)}});await Promise.allSettled(n)}async reloadNamespace(e,t){let n=t||this.currentLocale;c.debug(`Reloading namespace: ${n}:${e}`),await this.cache.invalidate({namespace:e,locale:n,refetch:!0}),c.info(`Namespace reloaded: ${n}:${e}`)}isEmbeddedPlugin(e){return e.capabilities.some(t=>["formatters","processors","pluralization","context"].includes(t))}isEventPlugin(e){return e.capabilities.some(t=>["analytics","logging","react","validation","dev-tools","monitoring"].includes(t))}};var O=class{constructor(e){d(this,"name","MemoryRepository");d(this,"type","memory");d(this,"config",{});d(this,"cache",new Map);d(this,"accessOrder",new Map);d(this,"maxSize",1e3);this.config=e,this.maxSize=this.config.options?.maxSize||1e3}get(e){let t=this.cache.get(e);return t!==void 0?(this.accessOrder.set(e,Date.now()),t):null}set(e,t){this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictOldest(),this.cache.set(e,t),this.accessOrder.set(e,Date.now())}remove(e){this.cache.delete(e),this.accessOrder.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear()}clearNamespace(e,t){let n=v(e,t),r=`${e}:${t}:`;this.cache.delete(n),this.accessOrder.delete(n);for(let s of this.cache.keys())s.startsWith(r)&&(this.cache.delete(s),this.accessOrder.delete(s))}getNamespace(e,t){let n=v(e,t),r=this.cache.get(n);if(!r)return null;try{return JSON.parse(r)}catch{return this.cache.delete(n),null}}setNamespace(e,t,n){let r=v(e,t);this.cache.set(r,JSON.stringify(n))}evictOldest(){let e="",t=Date.now();for(let[n,r]of this.accessOrder.entries())r<t&&(t=r,e=n);e&&(this.cache.delete(e),this.accessOrder.delete(e))}getEntries(){let e={};for(let[t,n]of this.cache.entries())e[t]=n;return e}getConfig(){return this.config}};var Ee=class{constructor(e,t={}){d(this,"name","StaticRepository");d(this,"type","memory");d(this,"config");d(this,"mem");this.config={enabled:t.enabled??!0,priority:t.priority??.5,options:{ttl:Number.MAX_SAFE_INTEGER,maxSize:Number.MAX_SAFE_INTEGER,...t.options}},this.mem=new O({options:{maxSize:Number.MAX_SAFE_INTEGER}});for(let[n,r]of Object.entries(e))for(let[s,i]of Object.entries(r)){this.mem.setNamespace(n,s,i);let o=A(i,"",n,s);for(let[l,u]of Object.entries(o))this.mem.set(l,u)}}get(e){return this.mem.get(e)}getNamespace(e,t){return this.mem.getNamespace(e,t)}getEntries(){return this.mem.getEntries()}getConfig(){return this.config}set(){}remove(){}clear(){}setNamespace(){}};var et=6e4,Ce=class{constructor(e,t,n){d(this,"queue",new Map);d(this,"debounceTimer",null);d(this,"repository");d(this,"config");d(this,"eventEmitter");d(this,"recentlySynced",new Map);this.repository=e,this.config=t,this.eventEmitter=n??null,t.enabled?c.debug(`MissingTranslationQueue: debounce=${t.debounceMs}ms, batchSize=${t.batchSize}`):c.debug("MissingTranslationQueue is disabled")}add(e){if(!this.config.enabled)return;let t=`${e.locale}:${e.namespace}:${e.key}`,n=this.recentlySynced.get(t);if(n&&Date.now()-n<et){c.debug(`Skipping recently synced key: ${t}`);return}if(this.queue.set(t,e),c.debug(`Missing translation queued: ${t} (queue size: ${this.queue.size})`),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.queue.size>=this.config.batchSize){c.debug(`Batch size reached (${this.config.batchSize}), flushing`),this.flush();return}this.debounceTimer=setTimeout(()=>{this.flush()},this.config.debounceMs)}flush(){if(this.queue.size===0)return;let e=Date.now();for(let[r,s]of this.recentlySynced)e-s>=et&&this.recentlySynced.delete(r);let t=Array.from(this.queue.entries()).map(([r,s])=>({key:r,value:s.fallbackValue,styles:s.styles})),n=t.length;this.queue.clear(),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),c.debug(`Flushing ${n} missing translations`),this.syncBatch(t).catch(r=>{c.warn(`Failed to sync ${n} missing translations:`,r)})}async syncBatch(e){try{if(e.some(s=>s.styles&&Object.keys(s.styles).length>0)&&"setBatchContentUnits"in this.repository){let s=e.map(i=>({key:i.key,value:{text:i.value,styles:i.styles??{}}}));await this.repository.setBatchContentUnits(s),c.debug(`Synced ${e.length} missing translations (ContentUnit)`)}else if("setBatch"in this.repository){let s=e.map(i=>({key:i.key,value:i.value}));await this.repository.setBatch(s),c.debug(`Synced ${e.length} missing translations`)}else c.warn("Repository does not support setBatch, syncing individually"),await this.syncIndividually(e);let n=Date.now(),r=[];for(let s of e)this.recentlySynced.set(s.key,n),r.push(s.key);this.eventEmitter&&this.eventEmitter.emit("sync:batch:complete",{payload:{count:e.length,keys:r}})}catch(t){throw c.error("Batch sync failed:",t),t}}async syncIndividually(e){let t=e.map(async n=>{try{await this.repository.set(n.key,n.value),c.debug(`Synced: ${n.key}`)}catch(r){c.warn(`Failed to sync ${n.key}:`,r)}});await Promise.allSettled(t)}getQueueSize(){return this.queue.size}getStats(){return{queueSize:this.queue.size,enabled:this.config.enabled,debounceMs:this.config.debounceMs,batchSize:this.config.batchSize}}destroy(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.queue.clear(),this.recentlySynced.clear(),c.debug("MissingTranslationQueue destroyed")}};function qt(a){return!(a instanceof b||a instanceof N)}var W=class a{constructor(e){d(this,"config");d(this,"plugins",[]);d(this,"syncStorageRepos",[]);d(this,"asyncStorageRepos",[]);d(this,"networkRepos",[]);d(this,"syncQueue",null);this.config={defaultLocale:e.defaultLocale||"en",namespace:e.namespace||"app"}}static init(e={}){return new a(e)}useSyncStorage(e){return this.syncStorageRepos.push(e),this}useAsyncStorage(e){return this.asyncStorageRepos.push(e),this}useNetwork(e){return this.networkRepos.push(e),this}use(e){switch(e.type){case"plugin":this.plugins.push(e);break;case"memory":this.useSyncStorage(e);break;case"storage":this.useAsyncStorage(e);break;case"network":this.useNetwork(e);break}return this}useStaticBundle(e,t=.5){return this.use(new Ee(e,{priority:t}))}async build(){let e=new pe,t=e.builder();c.info("Builder started"),c.debug("Builder config",this.config),t.buildStart(this.config.defaultLocale,this.config.namespace);let n=new ge(e);for(let o of this.syncStorageRepos){if(!o.getConfig().enabled)continue;let l=new he(e,o);t.use("sync"),n.addSyncHandler(l)}for(let o of this.asyncStorageRepos){if(!o.getConfig().enabled)continue;let l=new fe(e,o);t.use("async"),n.addAsyncHandler(l)}let r=null;for(let o of this.networkRepos){if(!o.getConfig().enabled||!o.getConfig().options?.baseUrl)continue;let l=new ye(e,o);r||(r=l),t.use("network"),n.addAsyncHandler(l);let u=o.getConfig();u.options?.syncMissing?.enabled&&(this.syncQueue=new Ce(o,{enabled:u.options.syncMissing.enabled,debounceMs:u.options.syncMissing.debounceMs||500,batchSize:u.options.syncMissing.batchSize||50},e),e.on("translation:not-found",p=>{this.syncQueue&&this.syncQueue.add({key:p.payload.key,fallbackValue:p.payload.fallbackValue,styles:p.payload.styles,locale:p.payload.locale,namespace:p.payload.namespace})}),c.info("Missing translation sync enabled"),c.debug("Sync queue config",u.options.syncMissing))}c.debug("Handler chain constructed");let s=new V(e,n,this.config.defaultLocale,this.config.namespace);for(let o of this.plugins)t.use("plugin"),await o.initialize({core:s,bus:e}),s.registerPlugin(o),c.info(`Plugin initialized: ${o.name}`),c.debug(`Plugin version: ${o.version}`,o.capabilities);let i=n.getChainInfo();return r&&await this.executePreloading(r,n),c.info("Builder completed"),t.buildDone(i.handlers.map(o=>o.name),this.plugins.map(o=>o.name)),s}async executePreloading(e,t){let n=e.getPreload().filter(o=>o.eager!==!1);if(!n||n.length===0)return;c.info(`Preloading ${n.length} namespaces`),c.debug("Preload targets",{namespaces:n.map(o=>`${o.locale}:${o.namespace}`)});let r=!1,s=(o,l)=>{if(!qt(l)||r)return;r=!0;let u=e.getBaseUrl()||"(no base URL configured)";console.warn(`[LionRapid] Could not load translations for ${o} from ${u} \u2014 the page stays untranslated until that host is reachable. If it is wrong, set data-base-url on the snippet tag (or \`baseUrl\` in the network repository options).`,l)},i=n.map(async o=>{let l=`${o.locale}:${o.namespace}`;try{let u=await e.loadNamespace(o.locale,o.namespace);if(u&&u.data&&u.status===200){let p={locale:o.locale,namespace:o.namespace};await t.saveNamespaceToHandlers(u.data,p),c.debug(`Preloaded: ${l}`);return}u?.status===404&&await t.forgetNamespaceInHandlers({locale:o.locale,namespace:o.namespace}),u?.error&&(s(l,u.error),c.warn(`Preload failed: ${l}`,u.error))}catch(u){s(l,u),c.warn(`Preload failed: ${l}`,u)}});await Promise.allSettled(i),c.info("Preloading completed")}};var en="X-LR-Surface",tn="snippet",L=class L{constructor(e={}){d(this,"name","NetworkRepository");d(this,"type","network");d(this,"config",{});d(this,"namespaceSnapshots",new Map);d(this,"inflightGets",new Map);d(this,"negativeCache",new Map);d(this,"authFailedStatus",null);d(this,"writesFailedStatus",null);d(this,"DEFAULT_ENDPOINTS",{getTranslation:"/api/integrations/translations/:key",getNamespace:"/api/integrations/translations/:locale/:namespace",getProjectConfig:"/api/integrations/project-config",setTranslation:"/api/integrations/sync/:key",setNamespace:"/api/integrations/sync/:locale/:namespace",setBatch:"/api/integrations/sync/batch",removeTranslation:"/api/integrations/sync/:key",clearTranslations:"/translations"});this.config={options:{timeout:e.options?.timeout??5e3,baseUrl:e.options?.baseUrl??"",headers:e.options?.headers??{}},...e}}async get(e){if(!this.config?.options?.baseUrl)throw c.debug("API base URL is not set"),new k("API base URL is not set");let t=this.buildUrl("getTranslation",{key:e});c.debug(`API GET: ${t}`);try{let n=await this.makeRequest(t,"GET");n.ok||this.handleHttpError(n,e);let r=await n.json();c.debug("API response data:",r);let s=r.translations[r.meta?.key]||r.translations[e]||Object.values(r.translations)[0];if(c.debug(`Fetched translation for key "${e}":`,s),!s)throw new b(e);return typeof s=="object"&&"text"in s?(c.debug(`ContentUnit text: ${U(s.text)}`),s.text):String(s)}catch(n){this.handleCaughtError(n)}}async getContentUnit(e){if(!this.config?.options?.baseUrl)throw c.debug("API base URL is not set"),new k("API base URL is not set");let t=this.buildUrl("getTranslation",{key:e});c.debug(`API GET ContentUnit: ${t}`);try{let n=await this.makeRequest(t,"GET");n.ok||this.handleHttpError(n,e);let r=await n.json();c.debug("API response data:",r);let s=r.translations[r.meta?.key]||r.translations[e]||Object.values(r.translations)[0];if(!s)throw new b(e);return typeof s=="object"&&"text"in s?(c.debug(`ContentUnit for "${e}": text=${U(s.text)}, styles=`,s.styles),{text:s.text,styles:s.styles||{}}):(c.debug(`Plain string for "${e}": ${U(String(s))} (no styles)`),{text:String(s),styles:{}})}catch(n){this.handleCaughtError(n)}}async getNamespace(e,t){if(!this.config?.options?.baseUrl)throw c.debug("API base URL is not set"),new k("API base URL is not set");try{return await this.fetchNamespaceRaw(e,t)}catch(n){this.handleCaughtError(n)}}async getProjectConfig(){if(!this.config?.options?.baseUrl)throw new k("API base URL is not set");let e=this.buildUrl("getProjectConfig",{});c.debug(`API GET ProjectConfig: ${e}`);try{let t=await this.makeRequest(e,"GET");if(t.status===404)return null;t.ok||this.handleHttpError(t,"project-config");let n=await t.json();return!n||typeof n.defaultLocale!="string"||!Array.isArray(n.languages)?(c.warn("project-config payload unusable \u2014 keeping local fallback"),null):{defaultLocale:n.defaultLocale,languages:n.languages.map(String)}}catch(t){this.handleCaughtError(t)}}async fetchNamespaceRaw(e,t,n=!0){let r=this.buildUrl("getNamespace",{locale:e,namespace:t});c.debug(`API GET Namespace: ${r}`);let s=`${e}:${t}`,i=n?this.getSnapshot(s):void 0,o={};i&&(o["If-None-Match"]=`W/"${i.version}"`);let l=await this.makeRequest(r,"GET",void 0,o);if(l.status===304)return i?(c.debug(`Namespace ${s}: 304 Not Modified (snapshot served)`),i.translations):(c.debug(`Namespace ${s}: unexpected 304 with no snapshot \u2014 refetching`),this.fetchNamespaceRaw(e,t,!1));l.ok||this.handleHttpError(l,s);let u=await l.json();if(c.debug("API response data:",u),!u.translations)throw new b(s);let p=u.meta?.version!=null?String(u.meta.version):null;return p&&this.setSnapshot(s,{version:p,translations:u.translations}),u.translations}async set(e,t){if(!this.config?.options?.baseUrl)return c.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let n=this.buildUrl("setTranslation",{key:e}),r=await this.makeRequest(n,"PUT",{translation:t});if(!r.ok)throw new Error(`Failed to save translation: ${r.status}`)}catch(n){throw c.debug(`API set failed for key "${e}":`,n),n}}async setNamespace(e,t,n){if(!this.config?.options?.baseUrl)return c.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let r=this.buildUrl("setNamespace",{locale:e,namespace:t}),s=await this.makeRequest(r,"PUT",{translations:n});if(!s.ok)throw new Error(`Failed to save namespace: ${s.status}`)}catch(r){throw c.debug(`API setNamespace failed for ${e}:${t}:`,r),r}}async setBatch(e){if(!this.config?.options?.baseUrl)return c.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("setBatch");c.debug(`API POST Batch: ${t} (${e.length} items)`);let n=await this.makeRequest(t,"POST",{translations:e});if(!n.ok)throw new Error(`Failed to sync batch: ${n.status}`);c.debug(`Batch sync successful: ${e.length} items`)}catch(t){throw c.debug(`API setBatch failed for ${e.length} items:`,t),t}}async getNamespaceContentUnits(e,t){if(!this.config?.options?.baseUrl)throw c.debug("API base URL is not set"),new k("API base URL is not set");try{return await this.fetchNamespaceRaw(e,t)}catch(n){this.handleCaughtError(n)}}async setContentUnit(e,t){if(!this.config?.options?.baseUrl)return c.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let n=this.buildUrl("setTranslation",{key:e}),r=await this.makeRequest(n,"PUT",{translation:t,format:"contentunit"});if(!r.ok)throw new Error(`Failed to save ContentUnit: ${r.status}`);c.debug(`Saved ContentUnit for key "${e}"`)}catch(n){throw c.debug(`API setContentUnit failed for key "${e}":`,n),n}}async setBatchContentUnits(e){if(!this.config?.options?.baseUrl)return c.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("setBatch");c.debug(`API POST Batch ContentUnits: ${t} (${e.length} items)`);let n=await this.makeRequest(t,"POST",{translations:e,format:"contentunit"});if(!n.ok)throw new Error(`Failed to sync batch ContentUnits: ${n.status}`);c.debug(`Batch ContentUnit sync successful: ${e.length} items`)}catch(t){throw c.debug(`API setBatchContentUnits failed for ${e.length} items:`,t),t}}async remove(e){if(!this.config?.options?.baseUrl)return c.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("removeTranslation",{key:e}),n=await this.makeRequest(t,"DELETE");if(!n.ok)throw new Error(`Failed to remove translation: ${n.status}`)}catch(t){throw c.debug(`API remove failed for key "${e}":`,t),t}}async clear(){if(!this.config?.options?.baseUrl)return c.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let e=this.buildUrl("clearTranslations"),t=await this.makeRequest(e,"DELETE");if(!t.ok)throw new Error(`Failed to clear translations: ${t.status}`)}catch(e){throw c.debug("API clear failed:",e),e}}getConfig(){return this.config}getSnapshot(e){let t=this.namespaceSnapshots.get(e);if(t)return t;try{localStorage.removeItem(L.LEGACY_VERSION_PREFIX+e);let n=localStorage.getItem(L.SNAPSHOT_PREFIX+e);if(n){let r=JSON.parse(n);if(r&&typeof r.version=="string"&&r.version.length>0&&r.translations&&typeof r.translations=="object")return this.namespaceSnapshots.set(e,r),r;localStorage.removeItem(L.SNAPSHOT_PREFIX+e)}}catch{}}setSnapshot(e,t){this.namespaceSnapshots.set(e,t);try{localStorage.setItem(L.SNAPSHOT_PREFIX+e,JSON.stringify(t)),localStorage.removeItem(L.LEGACY_VERSION_PREFIX+e)}catch{}}handleHttpError(e,t){if(c.debug(`API response: ${e.status} ${e.statusText}`),e.status===404)throw new b(t);if(e.status===423){let n=e.headers.get("Retry-After");throw new N(t,n?parseInt(n,10)*1e3:void 0)}throw e.status>=500&&e.status<600?new B(t,e.status):new k(`HTTP ${e.status}: ${e.statusText}`)}handleCaughtError(e){throw e instanceof b||e instanceof N||e instanceof B||e instanceof k?e:new k("Network request failed",e)}buildUrl(e,t={}){let n=this.config.options?.baseUrl||"",r=this.config.options?.endpoints?.[e]||this.DEFAULT_ENDPOINTS[e];r.startsWith("/")||(r=`/${r}`);let s=r;for(let[i,o]of Object.entries(t)){let l=new RegExp(`:${i}`,"g");s=s.replace(l,encodeURIComponent(o))}return`${n}${s}`}makeRequest(e,t,n,r){if(this.authFailedStatus!==null)return Promise.resolve(new Response(null,{status:this.authFailedStatus,statusText:`auth latched off after ${this.authFailedStatus}`}));if(t!=="GET")return this.writesFailedStatus!==null?Promise.resolve(new Response(null,{status:this.writesFailedStatus,statusText:`writes latched off after ${this.writesFailedStatus}`})):this.doFetch(e,t,n,r).then(u=>this.recordOutcome(e,t,u));let s=this.negativeCache.get(e);if(s){if(Date.now()<s.until){c.debug(`Negative-cache hit (${s.status}): ${e}`);let u=s.status===423?{"Retry-After":String(Math.ceil((s.until-Date.now())/1e3))}:void 0;return Promise.resolve(new Response(null,{status:s.status,statusText:"negative cache",headers:u}))}this.negativeCache.delete(e)}let i=`${e}|${r?.["If-None-Match"]??""}`,o=this.inflightGets.get(i);if(o)return o.then(u=>this.cloneResponse(u));let l=this.doFetch(e,t,n,r).then(u=>this.recordOutcome(e,t,u)).finally(()=>this.inflightGets.delete(i));return this.inflightGets.set(i,l),l.then(u=>this.cloneResponse(u))}recordOutcome(e,t,n){let r=n.status;if(r===401||r===403&&t==="GET")return this.authFailedStatus===null&&(this.authFailedStatus=r,console.warn(`[LionRapid] API key rejected (${r}) \u2014 network translations are disabled for this session. Fix the key and reload; retrying cannot heal an auth failure.`)),n;if((r===403||r===429)&&t!=="GET")return this.writesFailedStatus===null&&(this.writesFailedStatus=r,c.warn(`Write path disabled after ${r} (scope/quota) \u2014 running read-only`)),n;if(t==="GET"&&(r===404||r===423)){let s=r===423?Number(n.headers?.get?.("Retry-After")):NaN,i=Number.isFinite(s)&&s>0?s*1e3:this.config.options?.negativeCacheTtlMs??L.DEFAULT_NEGATIVE_TTL_MS;this.negativeCache.set(e,{status:r,until:Date.now()+i})}else t!=="GET"&&n.ok?this.negativeCache.clear():t==="GET"&&n.ok&&this.negativeCache.delete(e);return n}cloneResponse(e){return typeof e.clone=="function"?e.clone():e}async doFetch(e,t,n,r){let s=new AbortController,i=this.config.options?.timeout??1e4,o=setTimeout(()=>s.abort(),i);try{let l={"Content-Type":"application/json",[en]:tn,...this.config.options?.headers,...r};return this.config.options?.apiKey&&(l.Authorization=`Bearer ${this.config.options.apiKey}`),await fetch(e,{method:t,headers:l,body:n?JSON.stringify(n):void 0,signal:s.signal})}finally{clearTimeout(o)}}};d(L,"SNAPSHOT_PREFIX","lionrapid:ns:"),d(L,"LEGACY_VERSION_PREFIX","lionrapid:v:"),d(L,"DEFAULT_NEGATIVE_TTL_MS",6e4);var J=L;var nn={emails:!0,urls:!0,numbers:!0,phones:!0},Re={email:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,url:/^(https?:\/\/|www\.)[^\s]+$/i,number:/^[\d\s.,+-]+$/,phone:/^[+\d][\d\s().-]{6,}$/},K=class{constructor(e={},t=2){d(this,"patterns");d(this,"minTextLength");this.patterns={...nn,...e},this.minTextLength=t}shouldExclude(e){let t=e.trim();return!!(t.length<this.minTextLength||this.patterns.emails&&Re.email.test(t)||this.patterns.urls&&Re.url.test(t)||this.patterns.numbers&&Re.number.test(t)||this.patterns.phones&&Re.phone.test(t))}};function H(a){let e={},t=0;function n(s){if(s.nodeType===Node.TEXT_NODE)return s.nodeValue??"";if(s.nodeType!==Node.ELEMENT_NODE)return"";let i=s,o=i.tagName.toLowerCase(),l={};for(let m=0;m<i.attributes.length;m++){let g=i.attributes[m];l[g.name.toLowerCase()]=g.value}t++;let u=t;if(e[String(u)]=[`raw:${z(o,l)}`],F.has(o))return`<${u}/>`;let p="";for(let m=0;m<s.childNodes.length;m++)p+=n(s.childNodes[m]);return`<${u}>${p}</${u}>`}let r="";for(let s=0;s<a.childNodes.length;s++)r+=n(a.childNodes[s]);return{text:r,styles:e}}var ae="p,h1,h2,h3,h4,h5,h6,li,td,th,label,button,figcaption,dt,dd,summary,caption",Oe="a",rn=new Set(["SCRIPT","STYLE","CODE","PRE","TEXTAREA","NOSCRIPT","SVG"]),sn=["data-lionrapid-translated","data-lionrapid-client","data-no-translate","data-lr-block"],X=class{constructor(e={},t=[],n=2){d(this,"excludeFilter");d(this,"excludeSelectors");this.excludeFilter=new K(e,n),this.excludeSelectors=t}extract(e,t=!1){let n=[],r=e.querySelectorAll(ae),s=[];e instanceof Element&&e.matches(ae)&&s.push(e);for(let i=0;i<r.length;i++)s.push(r[i]);for(let i=0;i<s.length;i++){let o=s[i];if(this.isInsideSkipTag(o)||!t&&this.hasSkipAttribute(o)||this.matchesExcludeSelector(o)||o.getAttribute("translate")==="no"||o.querySelector(ae))continue;let l=o.getAttribute("data-lr-block"),u=o.getAttribute("data-lr-original"),p;if(u){let h=document.createElement(o.tagName);h.innerHTML=u,p=H(h)}else p=H(o);let m=p.text.replace(/<\/?[0-9]+\/?>/g,"");if(this.excludeFilter.shouldExclude(m))continue;let g;if(l)g=l;else{let h=o.getAttribute("data-i18n");h?g=h.includes(":")?h:`common:${h}`:g=$(p.text)}n.push({element:o,unit:p,key:g})}return this.extractOrphanInline(e,n,t),n}extractOrphanInline(e,t,n){let r=e.querySelectorAll(Oe),s=[];e instanceof Element&&e.matches(Oe)&&s.push(e);for(let i=0;i<r.length;i++)s.push(r[i]);for(let i=0;i<s.length;i++){let o=s[i];if(this.isInsideSkipTag(o)||!n&&this.hasSkipAttribute(o)||this.matchesExcludeSelector(o)||o.getAttribute("translate")==="no"||o.parentElement?.closest(ae)||o.parentElement?.closest(Oe)||o.querySelector(ae))continue;let l=o.getAttribute("data-lr-original"),u;if(l){let h=document.createElement(o.tagName);h.innerHTML=l,u=H(h)}else u=H(o);let p=u.text.replace(/<\/?[0-9]+\/?>/g,"");if(this.excludeFilter.shouldExclude(p))continue;let m=o.getAttribute("data-lr-block"),g;if(m)g=m;else{let h=o.getAttribute("data-i18n");h?g=h.includes(":")?h:`common:${h}`:g=$(u.text)}t.push({element:o,unit:u,key:g})}}isInsideSkipTag(e){let t=e.parentElement;for(;t;){if(rn.has(t.tagName.toUpperCase()))return!0;t=t.parentElement}return!1}hasSkipAttribute(e){let t=e;for(;t;){for(let n of sn)if(t.hasAttribute(n))return!0;t=t.parentElement}return!1}matchesExcludeSelector(e){for(let t of this.excludeSelectors)try{if(e.matches(t)||e.closest(t))return!0}catch{}return!1}};var an=[{selector:'img[alt], area[alt], input[type="image"][alt]',attr:"alt",type:"alt"},{selector:"[title]",attr:"title",type:"title"},{selector:"input[placeholder], textarea[placeholder]",attr:"placeholder",type:"placeholder"},{selector:'meta[name="description"][content]',attr:"content",type:"meta-description"},{selector:'meta[property="og:title"][content], meta[name="og:title"][content], meta[property="twitter:title"][content], meta[name="twitter:title"][content]',attr:"content",type:"title"},{selector:'meta[property="og:description"][content], meta[name="og:description"][content], meta[property="twitter:description"][content], meta[name="twitter:description"][content]',attr:"content",type:"meta-description"},{selector:'input[type="submit"][value], input[type="button"][value], input[type="reset"][value]',attr:"value",type:"input-value"}],on=new Set(["SCRIPT","STYLE","CODE","PRE","NOSCRIPT","SVG"]),ln=["data-lionrapid-translated","data-lionrapid-client","data-no-translate"];function cn(a){return`data-lr-attr-${a.toLowerCase()}`}var Q=class{constructor(e={},t=[],n=2){d(this,"excludeFilter");d(this,"excludeSelectors");this.excludeFilter=new K(e,n),this.excludeSelectors=t}extract(e,t=!1){let n=[];for(let r of an){let s=e.querySelectorAll(r.selector),i=[];e instanceof Element&&e.matches(r.selector)&&i.push(e);for(let o=0;o<s.length;o++)i.push(s[o]);for(let o=0;o<i.length;o++){let l=i[o];if(this.isInsideSkipTag(l)||this.hasSkipAncestor(l)||this.matchesExcludeSelector(l)||l.getAttribute("translate")==="no")continue;let u=l.getAttribute(r.attr);if(u===null)continue;let p=u.trim();if(this.excludeFilter.shouldExclude(p))continue;let m=cn(r.attr),g=l.getAttribute(m);if(!t&&g)continue;let h={text:u,type:r.type},f=g??$(u);n.push({element:l,attrName:r.attr,unit:h,key:f})}}return n}isInsideSkipTag(e){let t=e.parentElement;for(;t;){if(on.has(t.tagName.toUpperCase()))return!0;t=t.parentElement}return!1}hasSkipAncestor(e){let t=e;for(;t;){for(let n of ln)if(t.hasAttribute(n))return!0;t=t.parentElement}return!1}matchesExcludeSelector(e){for(let t of this.excludeSelectors)try{if(e.matches(t)||e.closest(t))return!0}catch{}return!1}};var Y=class{constructor(e,t=50){d(this,"observer",null);d(this,"callbacks");d(this,"debounceTimer",null);d(this,"pendingElements",new Set);d(this,"debounceMs");this.callbacks=e,this.debounceMs=t}start(){this.observer||(this.observer=new MutationObserver(e=>{this.handleMutations(e)}),this.observer.observe(document.body,{childList:!0,subtree:!0}))}stop(){this.observer&&(this.observer.disconnect(),this.observer=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingElements.clear()}handleMutations(e){let t=!1;for(let n of e)for(let r of Array.from(n.addedNodes)){if(r.nodeType!==Node.ELEMENT_NODE)continue;let s=r;this.hasLanguageSwitcher(s)&&(t=!0),this.callbacks.onNewContent&&this.pendingElements.add(s)}t&&this.callbacks.onNewSwitchers&&this.callbacks.onNewSwitchers(),this.pendingElements.size>0&&this.scheduleFlush()}scheduleFlush(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.flushPendingElements()},this.debounceMs)}flushPendingElements(){if(!(!this.callbacks.onNewContent||this.pendingElements.size===0)){for(let e of this.pendingElements)document.body.contains(e)&&this.callbacks.onNewContent(e);this.pendingElements.clear()}}hasLanguageSwitcher(e){return e.hasAttribute("data-lionrapid-switcher")||e.querySelector("[data-lionrapid-switcher]")!==null}};var un=new G,Z=class{constructor(e={}){d(this,"core",null);d(this,"blockExtractor");d(this,"attributeExtractor");d(this,"domObserver",null);d(this,"locale","");d(this,"sourceLocale","");d(this,"namespace","");d(this,"debounceMs");d(this,"pendingElements",new Set);d(this,"debounceTimer",null);d(this,"translatedCount",0);this.blockExtractor=new X(e.excludePatterns,e.excludeSelectors,e.minTextLength),this.attributeExtractor=new Q(e.excludePatterns,e.excludeSelectors,e.minTextLength),this.debounceMs=e.debounceMs??100}setCore(e){this.core=e}init(e){this.locale=e.locale,this.sourceLocale=e.sourceLocale,this.namespace=e.namespace}updateLocale(e){this.locale=e}isReady(){return this.core!==null}generateAutoKey(e){return $(e)}queueElement(e){this.pendingElements.add(e),this.scheduleProcessing()}translateElement(e){if(!this.core)return 0;let t=this.translateBlocks(this.blockExtractor.extract(e)),n=this.translateAttributesIn(this.attributeExtractor.extract(e));return t+n}translatePage(){return this.translateElement(document.body)}observe(){this.domObserver||(this.domObserver=new Y({onNewContent:e=>this.queueElement(e)}),this.domObserver.start())}stopObserving(){this.domObserver&&(this.domObserver.stop(),this.domObserver=null)}scheduleProcessing(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processPendingElements()},this.debounceMs)}processPendingElements(){if(!this.core||this.pendingElements.size===0)return;let e=0;for(let t of this.pendingElements){if(!document.body.contains(t))continue;let n=this.translateElement(t);e+=n}this.pendingElements.clear(),this.translatedCount+=e}translateBlocks(e){if(!this.core)return 0;let t=0;for(let{element:n,unit:r,key:s}of e){let i=`${this.locale}:${this.namespace}:${s}`,o=this.core.cache.get(i);if(o&&o.value!==r.text&&o.value!==s){n.hasAttribute("data-lr-original")||n.setAttribute("data-lr-original",n.innerHTML);let l=o.styles&&Object.keys(o.styles).length>0,u=Object.keys(r.styles).length>0,p=/<\/?[0-9]+\/?>/.test(o.value);if(!(u&&!p)){let m=l?o.styles:r.styles,g={text:o.value,styles:m};n.innerHTML=un.serialize(g)}n.setAttribute("data-lr-block",s),n.setAttribute("data-lionrapid-client","1"),t++}else this.core.bus.emit("translation:not-found",{payload:{key:s,fallbackValue:r.text,locale:this.sourceLocale,namespace:this.namespace,status:404,styles:r.styles}})}return t}translateAttributesIn(e){if(!this.core)return 0;let t=0;for(let{element:n,attrName:r,unit:s,key:i}of e){let o=`${this.locale}:${this.namespace}:${i}`,l=this.core.cache.get(o);if(l&&l.value!==s.text&&l.value!==i){let u=r.toLowerCase(),p=`data-lr-orig-${u}`;n.hasAttribute(p)||n.setAttribute(p,s.text),n.setAttribute(r,l.value),n.setAttribute(`data-lr-attr-${u}`,i);let m=n.getAttribute("data-lionrapid-client-attrs")??"",g=new Set(m.split(",").filter(Boolean));g.add(u),n.setAttribute("data-lionrapid-client-attrs",Array.from(g).join(",")),t++}else this.core.bus.emit("translation:not-found",{payload:{key:i,fallbackValue:s.text,locale:this.sourceLocale,namespace:this.namespace,status:404,styles:{}}})}return t}getTranslatedCount(){return this.translatedCount}restoreClientAttributes(e){let t=e.getAttribute("data-lionrapid-client-attrs");if(t!==null){for(let n of t.split(",").filter(Boolean)){let r=e.getAttribute(`data-lr-orig-${n}`);r!==null&&(e.setAttribute(n,r),e.removeAttribute(`data-lr-orig-${n}`)),e.removeAttribute(`data-lr-attr-${n}`)}e.removeAttribute("data-lionrapid-client-attrs")}}retranslateElement(e){let t=e.getAttribute("data-lr-original");t!==null&&(e.innerHTML=t),e.removeAttribute("data-lionrapid-client"),e.removeAttribute("data-lr-block"),this.restoreClientAttributes(e),this.translateElement(e)}retranslate(){document.querySelectorAll("[data-lionrapid-client]").forEach(n=>{let r=n.getAttribute("data-lr-original");r!==null&&(n.innerHTML=r),n.removeAttribute("data-lionrapid-client"),n.removeAttribute("data-lr-block")}),document.querySelectorAll("[data-lionrapid-client-attrs]").forEach(n=>this.restoreClientAttributes(n)),this.translatedCount=0,this.locale!==this.sourceLocale&&this.translatePage()}};var tt={en:{code:"en",name:"English",flag:"\u{1F1EC}\u{1F1E7}"},es:{code:"es",name:"Espa\xF1ol",flag:"\u{1F1EA}\u{1F1F8}"},fr:{code:"fr",name:"Fran\xE7ais",flag:"\u{1F1EB}\u{1F1F7}"},de:{code:"de",name:"Deutsch",flag:"\u{1F1E9}\u{1F1EA}"},it:{code:"it",name:"Italiano",flag:"\u{1F1EE}\u{1F1F9}"},pt:{code:"pt",name:"Portugu\xEAs",flag:"\u{1F1F5}\u{1F1F9}"},nl:{code:"nl",name:"Nederlands",flag:"\u{1F1F3}\u{1F1F1}"},pl:{code:"pl",name:"Polski",flag:"\u{1F1F5}\u{1F1F1}"},ru:{code:"ru",name:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",flag:"\u{1F1F7}\u{1F1FA}"},ja:{code:"ja",name:"\u65E5\u672C\u8A9E",flag:"\u{1F1EF}\u{1F1F5}"},ko:{code:"ko",name:"\uD55C\uAD6D\uC5B4",flag:"\u{1F1F0}\u{1F1F7}"},zh:{code:"zh",name:"\u4E2D\u6587",flag:"\u{1F1E8}\u{1F1F3}"},ar:{code:"ar",name:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",flag:"\u{1F1F8}\u{1F1E6}"},hi:{code:"hi",name:"\u0939\u093F\u0928\u094D\u0926\u0940",flag:"\u{1F1EE}\u{1F1F3}"},tr:{code:"tr",name:"T\xFCrk\xE7e",flag:"\u{1F1F9}\u{1F1F7}"},vi:{code:"vi",name:"Ti\u1EBFng Vi\u1EC7t",flag:"\u{1F1FB}\u{1F1F3}"},th:{code:"th",name:"\u0E44\u0E17\u0E22",flag:"\u{1F1F9}\u{1F1ED}"},sv:{code:"sv",name:"Svenska",flag:"\u{1F1F8}\u{1F1EA}"},da:{code:"da",name:"Dansk",flag:"\u{1F1E9}\u{1F1F0}"},fi:{code:"fi",name:"Suomi",flag:"\u{1F1EB}\u{1F1EE}"},no:{code:"no",name:"Norsk",flag:"\u{1F1F3}\u{1F1F4}"},cs:{code:"cs",name:"\u010Ce\u0161tina",flag:"\u{1F1E8}\u{1F1FF}"},el:{code:"el",name:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC",flag:"\u{1F1EC}\u{1F1F7}"},he:{code:"he",name:"\u05E2\u05D1\u05E8\u05D9\u05EA",flag:"\u{1F1EE}\u{1F1F1}"},id:{code:"id",name:"Bahasa Indonesia",flag:"\u{1F1EE}\u{1F1E9}"},ms:{code:"ms",name:"Bahasa Melayu",flag:"\u{1F1F2}\u{1F1FE}"},uk:{code:"uk",name:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430",flag:"\u{1F1FA}\u{1F1E6}"},ro:{code:"ro",name:"Rom\xE2n\u0103",flag:"\u{1F1F7}\u{1F1F4}"},hu:{code:"hu",name:"Magyar",flag:"\u{1F1ED}\u{1F1FA}"},sk:{code:"sk",name:"Sloven\u010Dina",flag:"\u{1F1F8}\u{1F1F0}"},bg:{code:"bg",name:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438",flag:"\u{1F1E7}\u{1F1EC}"},hr:{code:"hr",name:"Hrvatski",flag:"\u{1F1ED}\u{1F1F7}"},sr:{code:"sr",name:"\u0421\u0440\u043F\u0441\u043A\u0438",flag:"\u{1F1F7}\u{1F1F8}"},sl:{code:"sl",name:"Sloven\u0161\u010Dina",flag:"\u{1F1F8}\u{1F1EE}"},lt:{code:"lt",name:"Lietuvi\u0173",flag:"\u{1F1F1}\u{1F1F9}"},lv:{code:"lv",name:"Latvie\u0161u",flag:"\u{1F1F1}\u{1F1FB}"},et:{code:"et",name:"Eesti",flag:"\u{1F1EA}\u{1F1EA}"}},dn=`
|
|
6
6
|
.lionrapid-switcher {
|
|
7
7
|
position: fixed;
|
|
8
8
|
z-index: 999999;
|
|
@@ -79,5 +79,5 @@
|
|
|
79
79
|
.lionrapid-btn-row button:last-child { border-right: none; }
|
|
80
80
|
.lionrapid-btn-row button:hover { background: #f5f5f5; }
|
|
81
81
|
.lionrapid-btn-row button.active { background: #3b82f6; color: #fff; }
|
|
82
|
-
`,q=class{constructor(){d(this,"core",null);d(this,"languages",[]);d(this,"initialLocale","en");d(this,"onLanguageChange",null);d(this,"stylesInjected",!1)}setCore(e){this.core=e}setInitialLocale(e){this.initialLocale=e}setLanguages(e){this.languages=e.map(t=>typeof t=="string"?tt[t]||{code:t,name:t}:t)}setOnLanguageChange(e){this.onLanguageChange=e}initAll(){this.injectStyles(),document.querySelectorAll("[data-lionrapid-switcher]").forEach(t=>this.initSwitcher(t))}initSwitcher(e){let t=e.dataset.lionrapidSwitcher||"floating",n=this.core?.getCurrentLocale()||this.initialLocale;e.innerHTML="",e.classList.add("lionrapid-switcher"),e.setAttribute("data-no-translate",""),e.setAttribute("translate","no");let r=e.dataset.lionrapidSwitcherPosition||"top-right",s=e.dataset.lionrapidSwitcherShowFlags!=="false",i=e.dataset.lionrapidSwitcherShowNames!=="false",o=e.dataset.lionrapidSwitcherCustomCss||null;if(e.dataset.position=r,o){let c=document.createElement("style");c.textContent=o,document.head.appendChild(c)}switch(t){case"flags":this.renderButtonRow(e,n,!0,!0);break;case"buttons":this.renderButtonRow(e,n,s,i);break;case"floating":default:this.renderFloating(e,n,r,s,i);break}}renderFloating(e,t,n,r,s){let i={};n.startsWith("bottom")?i.bottom="100%":i.top="100%",n.endsWith("left")?i.left="0":i.right="0";let o=g=>{let h=r&&g.flag||"",y=s?g.name:g.code.toUpperCase();return`${h}${h&&y?" ":""}${y}`},c=this.languages.find(g=>g.code===t)||this.languages[0],u=c?o(c):t,p=document.createElement("button");p.type="button",p.className="lionrapid-floating-btn",p.setAttribute("aria-expanded","false"),p.setAttribute("aria-haspopup","true"),p.textContent=`${u} \u25BE`;let m=document.createElement("div");m.className="lionrapid-floating-menu",Object.assign(m.style,i);for(let g of this.languages){let h=document.createElement("button");h.type="button",h.dataset.lang=g.code,h.textContent=o(g),g.code===t&&h.classList.add("active"),h.addEventListener("click",()=>{this.handleLanguageChange(g.code),p.textContent=o(g)+" \u25BE",m.querySelectorAll("button").forEach(y=>{y.classList.toggle("active",y.dataset.lang===g.code)}),m.classList.remove("open"),p.setAttribute("aria-expanded","false")}),m.appendChild(h)}p.addEventListener("click",g=>{g.stopPropagation();let h=m.classList.contains("open");m.classList.toggle("open",!h),p.setAttribute("aria-expanded",String(!h))}),document.addEventListener("click",()=>{m.classList.remove("open"),p.setAttribute("aria-expanded","false")}),e.appendChild(p),e.appendChild(m)}renderButtonRow(e,t,n,r){let s=document.createElement("div");s.className="lionrapid-btn-row";for(let i of this.languages){let o=document.createElement("button");o.type="button",o.dataset.lang=i.code;let c=n&&i.flag||"",u=r?i.name:i.code.toUpperCase();o.textContent=`${c}${c&&u?" ":""}${u}`,i.code===t&&o.classList.add("active"),o.addEventListener("click",()=>{this.handleLanguageChange(i.code),s.querySelectorAll("button").forEach(p=>{p.classList.toggle("active",p.dataset.lang===i.code)})}),s.appendChild(o)}e.appendChild(s)}handleLanguageChange(e){this.onLanguageChange&&this.onLanguageChange(e),document.querySelectorAll(".lionrapid-btn-row button").forEach(t=>{let n=t;n.classList.toggle("active",n.dataset.lang===e)})}injectStyles(){if(this.stylesInjected)return;let e=document.createElement("style");e.textContent=on,document.head.appendChild(e),this.stylesInjected=!0}static getLanguage(e){return tt[e]}};var Ue="lionrapid:",ee=`${Ue}version`,nt="1",te=class{constructor(e={}){d(this,"name","LocalStorageRepository");d(this,"type","memory");d(this,"config");d(this,"available");d(this,"prefix");d(this,"defaultTTL");d(this,"maxSize");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{prefix:e.options?.prefix??Ue,ttl:e.options?.ttl??1440*60*1e3,maxSize:e.options?.maxSize??500,...e.options}},this.prefix=this.config.options?.prefix??Ue,this.defaultTTL=this.config.options?.ttl??1440*60*1e3,this.maxSize=this.config.options?.maxSize??500,this.available=this.checkAvailability(),this.available&&this.migrateIfNeeded()}checkAvailability(){if(typeof window>"u")return!1;try{let e=`${this.prefix}__test__`;return window.localStorage.setItem(e,"test"),window.localStorage.removeItem(e),!0}catch{return!1}}migrateIfNeeded(){try{window.localStorage.getItem(ee)!==nt&&(this.clear(),window.localStorage.setItem(ee,nt))}catch{}}get(e){if(!this.available)return null;try{let t=this.prefix+e,n=window.localStorage.getItem(t);if(!n)return null;let r=JSON.parse(n);return r.expiry!==null&&Date.now()>r.expiry?(window.localStorage.removeItem(t),null):r.value}catch{return null}}set(e,t){if(!this.available)return;let n=this.prefix+e,r={value:t,expiry:this.defaultTTL?Date.now()+this.defaultTTL:null,timestamp:Date.now()};try{this.getEntryCount()>=this.maxSize&&this.evictOldest(),window.localStorage.setItem(n,JSON.stringify(r))}catch(s){if(this.isQuotaError(s)){this.evictOldest();try{window.localStorage.setItem(n,JSON.stringify(r))}catch{}}}}remove(e){if(this.available)try{window.localStorage.removeItem(this.prefix+e)}catch{}}clear(){if(this.available)try{let e=[];for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);n?.startsWith(this.prefix)&&n!==ee&&e.push(n)}e.forEach(t=>window.localStorage.removeItem(t))}catch{}}clearNamespace(e,t){if(!this.available)return;let n=`@${e}:${t}`,r=`${e}:${t}:`;try{let s=[];for(let i=0;i<window.localStorage.length;i++){let o=window.localStorage.key(i);if(!o?.startsWith(this.prefix))continue;let c=o.slice(this.prefix.length);(c===n||c.startsWith(r))&&s.push(o)}s.forEach(i=>window.localStorage.removeItem(i))}catch{}}getNamespace(e,t){let n=`@${e}:${t}`,r=this.get(n);if(!r)return null;try{return JSON.parse(r)}catch{return this.remove(n),null}}setNamespace(e,t,n){let r=`@${e}:${t}`;this.set(r,JSON.stringify(n))}getEntries(){let e={};if(!this.available)return e;try{for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);if(!n?.startsWith(this.prefix)||n===ee)continue;let r=n.slice(this.prefix.length),s=this.get(r);s!==null&&(e[r]=s)}}catch{}return e}getConfig(){return this.config}isAvailable(){return this.available}getEntryCount(){if(!this.available)return 0;let e=0;try{for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);n?.startsWith(this.prefix)&&n!==ee&&e++}}catch{}return e}isQuotaError(e){return e instanceof DOMException?e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED":!1}evictOldest(){if(this.available)try{let e=[];for(let n=0;n<window.localStorage.length;n++){let r=window.localStorage.key(n);if(!(!r?.startsWith(this.prefix)||r===ee))try{let s=window.localStorage.getItem(r);if(s){let i=JSON.parse(s);e.push({key:r,timestamp:i.timestamp})}}catch{window.localStorage.removeItem(r)}}e.sort((n,r)=>n.timestamp-r.timestamp);let t=Math.max(1,Math.floor(e.length*.25));for(let n=0;n<t&&n<e.length;n++)window.localStorage.removeItem(e[n].key)}catch{}}getCacheStats(){let e=this.getEntryCount(),t=this.maxSize>0?`${Math.round(e/this.maxSize*100)}%`:"0%";return{size:e,maxSize:this.maxSize,usage:t}}};var xe=Object.freeze({translations:"lionrapid-v1",offlineFloor:"lionrapid-offline-v1"}),rt="https://cache.lionrapid.internal/";var st=xe.translations,L=rt,j=class{constructor(e={}){d(this,"name","CacheStorageRepository");d(this,"type","storage");d(this,"config");d(this,"cacheName");d(this,"defaultTTL");d(this,"available");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{cacheName:e.options?.cacheName??st,ttl:e.options?.ttl??10080*60*1e3,...e.options}},this.cacheName=this.config.options?.cacheName??st,this.defaultTTL=this.config.options?.ttl??10080*60*1e3,this.available=this.checkAvailability()}checkAvailability(){return typeof caches<"u"}async get(e){if(!this.available)throw new b(e);try{let t=await caches.open(this.cacheName),n=await t.match(L+e);if(!n)throw new b(e);let r=await n.json();if(r.expiry!==null&&Date.now()>r.expiry)throw await t.delete(L+e),new b(e);return r.value}catch(t){throw t instanceof b?t:new b(e)}}async set(e,t){if(this.available)try{let n=await caches.open(this.cacheName),r={value:t,expiry:this.defaultTTL?Date.now()+this.defaultTTL:null,timestamp:Date.now()};await n.put(L+e,new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}}))}catch{}}async remove(e){if(this.available)try{await(await caches.open(this.cacheName)).delete(L+e)}catch{}}async clear(){if(this.available)try{let e=await caches.open(this.cacheName),t=await e.keys();await Promise.all(t.filter(n=>n.url.includes(L)).map(n=>e.delete(n)))}catch{}}async clearNamespace(e,t){if(!this.available)return;let n=`@${e}:${t}`,r=`${e}:${t}:`;try{let s=await caches.open(this.cacheName),i=await s.keys();await Promise.all(i.filter(o=>{let c=o.url,u=c.includes(L)?c.substring(c.indexOf(L)+L.length):"";return u===n||u.startsWith(r)}).map(o=>s.delete(o)))}catch{}}async getNamespace(e,t){let n=`@${e}:${t}`,r=await this.get(n);try{return JSON.parse(r)}catch{throw await this.remove(n),new b(n)}}async setNamespace(e,t,n){let r=`@${e}:${t}`;await this.set(r,JSON.stringify(n))}getConfig(){return this.config}isAvailable(){return this.available}async getEntries(){let e={};if(!this.available)return e;try{let n=await(await caches.open(this.cacheName)).keys();for(let r of n){let s=r.url;if(!s.includes(L))continue;let i=s.substring(s.indexOf(L)+L.length);try{let o=await this.get(i);e[i]=o}catch{}}}catch{}return e}async getCacheStats(){if(!this.available)return{size:0,cacheName:this.cacheName};try{return{size:(await(await caches.open(this.cacheName)).keys()).filter(r=>r.url.includes(L)).length,cacheName:this.cacheName}}catch{return{size:0,cacheName:this.cacheName}}}};var at="https://app.lionrapid.com";function ln(a){let e=a.startsWith("pk_");return{bootNetwork:e,syncMissing:{enabled:e},warnRefused:!e}}function cn(a){return{...a,apiKey:""}}function un(a){let e=null,t=null;return{onChange:async n=>{if(a.setCookie(n),a.navigate){a.navigate(n);return}if(e){await e(n);return}t=n},attach:n=>{if(e=n,t!==null){let r=t;t=null,n(r).catch(()=>{})}}}}function it(a){document.readyState==="loading"?document.addEventListener("DOMContentLoaded",a,{once:!0}):a()}function De(a){let e=a.dataset.apiKey||"",t=a.dataset.baseUrl||at,n=a.dataset.defaultLocale||"en",r=a.dataset.namespace||"default",s=(a.dataset.languages||n).split(",").map(T=>T.trim()).filter(Boolean),i=(a.dataset.exclude||"").split(",").map(T=>T.trim()).filter(Boolean),o=a.dataset.autoDetect==="true",c=a.dataset.mode==="dynamic-only"?"dynamic-only":"full",u=a.dataset.switcher&&a.dataset.switcher!=="false"?a.dataset.switcher:void 0,p=a.dataset.switcherPosition||void 0,m=a.dataset.switcherShowFlags!=="false",g=a.dataset.switcherShowNames==="true",h=a.dataset.switcherCustomCss||void 0,y=a.dataset.editorCdn||void 0,x=a.dataset.offline!=="false";return{apiKey:e,baseUrl:t,defaultLocale:n,namespace:r,languages:s,excludeSelectors:i,autoDetect:o,mode:c,switcherStyle:u,switcherPosition:p,switcherShowFlags:m,switcherShowNames:g,switcherCustomCss:h,editorCdnUrl:y,offline:x}}function dn(a){if(typeof document>"u")return null;let e=document.cookie.match(/(?:^|;\s*)lionrapid_locale=([a-z]{2,3}(?:-[a-z0-9]{2,4})*)/i);return e&&de([e[1]],a,"")||null}function pn(a,e){if(typeof navigator>"u")return e;let t=navigator.languages&&navigator.languages.length>0?[...navigator.languages]:[navigator.language||navigator.userLanguage||""];return de(t,a,e)}function gn(a,e,t,n,r){let s=a.split("/"),i=s[1]??"",c=We.test(i)&&de([i],r,"")!==""?"/"+s.slice(2).join("/"):a;return(t===n?"":"/"+t)+(c||"/")+e}function mn(a,e,t){window.location.href=gn(window.location.pathname,window.location.search,a,e,t)}function hn(a){if(a.mode==="dynamic-only"){let t=typeof document<"u"?document.documentElement.lang:"";return t?Ie(t):a.defaultLocale}let e=dn(a.languages);return e||(a.autoDetect?pn(a.languages,a.defaultLocale):a.defaultLocale)}function Me(a){typeof document<"u"&&(document.documentElement.dir=pe(a))}function fn(){let a=document.currentScript;if(a instanceof HTMLScriptElement&&a.dataset.apiKey)return a;let e=document.querySelectorAll("script[data-api-key]");return e.length>1&&console.warn(`[LionRapid] ${e.length} script tags with data-api-key found; using the last one`),e[e.length-1]}async function He(){let a=fn();if(!a){console.warn("[LionRapid] No script tag with data-api-key found");return}let e=De(a);if(window.__lionrapidConfig=cn(e),!e.apiKey){console.warn("[LionRapid] Missing data-api-key attribute");return}let t=ln(e.apiKey);t.warnRefused&&console.error("[LionRapid] data-api-key must be a publishable pk_ key \u2014 network translations are disabled. Copy the snippet from the integration hub to get the pk_ key for this project.");let n=hn(e);Me(n);let r=new q;r.setLanguages(e.languages),r.setInitialLocale(n),it(()=>{if(e.mode!=="dynamic-only"&&e.switcherStyle&&!document.querySelector("[data-lionrapid-switcher]")){let o=document.createElement("div");o.dataset.lionrapidSwitcher=e.switcherStyle,e.switcherPosition&&(o.dataset.lionrapidSwitcherPosition=e.switcherPosition),e.switcherShowFlags||(o.dataset.lionrapidSwitcherShowFlags="false"),e.switcherShowNames||(o.dataset.lionrapidSwitcherShowNames="false"),e.switcherCustomCss&&(o.dataset.lionrapidSwitcherCustomCss=e.switcherCustomCss),document.body.appendChild(o)}r.initAll()});let i=un({setCookie:o=>{document.cookie=`lionrapid_locale=${o}; path=/; max-age=31536000; SameSite=Lax`},navigate:e.mode==="dynamic-only"?o=>mn(o,e.defaultLocale,e.languages):null});r.setOnLanguageChange(i.onChange);try{let o=W.init({defaultLocale:n,namespace:e.namespace}).use(new O({enabled:!0})).use(new te({enabled:!0})).use(new j({enabled:!0}));e.offline!==!1&&o.use(new j({enabled:!0,options:{ttl:Number.MAX_SAFE_INTEGER,cacheName:xe.offlineFloor}})),t.bootNetwork&&o.use(new J({enabled:!0,options:{baseUrl:e.baseUrl,apiKey:e.apiKey,syncMissing:t.syncMissing,preloadNamespaces:[{locale:n,namespace:e.namespace,eager:!0}]}}));let c=await o.build(),u=new Z({excludeSelectors:e.excludeSelectors});u.setCore(c),u.init({namespace:e.namespace,locale:n,sourceLocale:e.defaultLocale}),r.setCore(c),i.attach(async f=>{await c.changeLanguage(f,{preloadNamespaces:[e.namespace]}),Me(f),u.updateLocale(f),u.retranslate()});let p=[2e3,8e3,3e4],m=6e4,g=!1,h=[],y=Date.now(),x=async()=>{await c.reloadNamespace(e.namespace),u.translatePage(),y=Date.now()},T=()=>{h.forEach(f=>clearTimeout(f)),h=[]};c.bus.on("sync:batch:complete",()=>{g=!0,T(),p.forEach(f=>{h.push(setTimeout(()=>x().catch(()=>{}),f))})}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&(g?(g=!1,T(),x().catch(()=>{})):Date.now()-y>m&&x().catch(()=>{}))});let ot={t:(f,ne,Te)=>c.t(f,ne||{},Te),tHtml:(f,ne,Te)=>c.tHtml(f,ne||{},Te),changeLanguage:async f=>{await c.changeLanguage(f,{preloadNamespaces:[e.namespace]}),Me(f),u.updateLocale(f),u.retranslate(),r.initAll()},getCurrentLocale:()=>c.getCurrentLocale(),on:(f,ne)=>c.bus.on(f,ne),retranslate:()=>u.retranslate(),reloadTranslations:x,autoTranslator:u,languageSwitcher:r};window.LionRapid=ot;let je=new URLSearchParams(window.location.search).get("__lr_editor");if(je&&!document.querySelector("script[data-grant], script[data-lr-editor]")){let f=document.createElement("script");f.src=e.editorCdnUrl||"https://cdn.lionrapid.com/lionrapid.editor.min.js",f.dataset.grant=je,f.dataset.locale=c.getCurrentLocale(),f.dataset.api=e.baseUrl,f.async=!0,document.body.appendChild(f)}it(()=>{e.mode!=="dynamic-only"&&u.translatePage(),u.observe()})}catch(o){console.error("[LionRapid] Initialization failed:",o)}}He();return mt(yn);})();
|
|
82
|
+
`,nt=8,pn=20;function gn(a=document,e=window){let t=e.innerHeight||a.documentElement.clientHeight||0,n=l=>{let u=e.getComputedStyle(l);if(u.display==="none"||u.visibility==="hidden")return null;let p=l.getBoundingClientRect();if(p.height<=0)return null;let g=u.position==="fixed"||u.position==="sticky"?0:e.scrollY;return[p.top+g,p.bottom+g]},r=a.getElementById("wpadminbar"),s=r&&n(r)?.[1]||0,i=s;if(a.querySelectorAll('header, [role="banner"]').forEach(l=>{if(l.closest("article, main, aside"))return;let u=n(l);!u||u[0]>s+nt*4||(i=Math.max(i,u[1]))}),i===0)return pn;let o=Math.ceil(i)+nt;return t>0?Math.min(o,Math.floor(t/2)):o}var q=class{constructor(){d(this,"core",null);d(this,"languages",[]);d(this,"initialLocale","en");d(this,"onLanguageChange",null);d(this,"stylesInjected",!1)}setCore(e){this.core=e}setInitialLocale(e){this.initialLocale=e}setLanguages(e){this.languages=e.map(t=>typeof t=="string"?tt[t]||{code:t,name:t}:t)}setOnLanguageChange(e){this.onLanguageChange=e}initAll(){this.injectStyles(),document.querySelectorAll("[data-lionrapid-switcher]").forEach(t=>this.initSwitcher(t))}initSwitcher(e){let t=e.dataset.lionrapidSwitcher||"floating",n=this.core?.getCurrentLocale()||this.initialLocale;e.innerHTML="",e.classList.add("lionrapid-switcher"),e.setAttribute("data-no-translate",""),e.setAttribute("translate","no");let r=e.dataset.lionrapidSwitcherPosition||"top-right",s=e.dataset.lionrapidSwitcherShowFlags!=="false",i=e.dataset.lionrapidSwitcherShowNames!=="false",o=e.dataset.lionrapidSwitcherCustomCss||null;if(e.dataset.position=r,r.startsWith("top")){let l=()=>{e.style.top=`${gn()}px`};l(),window.addEventListener("load",l),window.addEventListener("resize",l)}if(o){let l=document.createElement("style");l.textContent=o,document.head.appendChild(l)}switch(t){case"flags":this.renderButtonRow(e,n,!0,!0);break;case"buttons":this.renderButtonRow(e,n,s,i);break;case"floating":default:this.renderFloating(e,n,r,s,i);break}}renderFloating(e,t,n,r,s){let i={};n.startsWith("bottom")?i.bottom="100%":i.top="100%",n.endsWith("left")?i.left="0":i.right="0";let o=g=>{let h=r&&g.flag||"",f=s?g.name:g.code.toUpperCase();return`${h}${h&&f?" ":""}${f}`},l=this.languages.find(g=>g.code===t)||this.languages[0],u=l?o(l):t,p=document.createElement("button");p.type="button",p.className="lionrapid-floating-btn",p.setAttribute("aria-expanded","false"),p.setAttribute("aria-haspopup","true"),p.textContent=`${u} \u25BE`;let m=document.createElement("div");m.className="lionrapid-floating-menu",Object.assign(m.style,i);for(let g of this.languages){let h=document.createElement("button");h.type="button",h.dataset.lang=g.code,h.textContent=o(g),g.code===t&&h.classList.add("active"),h.addEventListener("click",()=>{this.handleLanguageChange(g.code),p.textContent=o(g)+" \u25BE",m.querySelectorAll("button").forEach(f=>{f.classList.toggle("active",f.dataset.lang===g.code)}),m.classList.remove("open"),p.setAttribute("aria-expanded","false")}),m.appendChild(h)}p.addEventListener("click",g=>{g.stopPropagation();let h=m.classList.contains("open");m.classList.toggle("open",!h),p.setAttribute("aria-expanded",String(!h))}),document.addEventListener("click",()=>{m.classList.remove("open"),p.setAttribute("aria-expanded","false")}),e.appendChild(p),e.appendChild(m)}renderButtonRow(e,t,n,r){let s=document.createElement("div");s.className="lionrapid-btn-row";for(let i of this.languages){let o=document.createElement("button");o.type="button",o.dataset.lang=i.code;let l=n&&i.flag||"",u=r?i.name:i.code.toUpperCase();o.textContent=`${l}${l&&u?" ":""}${u}`,i.code===t&&o.classList.add("active"),o.addEventListener("click",()=>{this.handleLanguageChange(i.code),s.querySelectorAll("button").forEach(p=>{p.classList.toggle("active",p.dataset.lang===i.code)})}),s.appendChild(o)}e.appendChild(s)}handleLanguageChange(e){this.onLanguageChange&&this.onLanguageChange(e),document.querySelectorAll(".lionrapid-btn-row button").forEach(t=>{let n=t;n.classList.toggle("active",n.dataset.lang===e)})}injectStyles(){if(this.stylesInjected)return;let e=document.createElement("style");e.textContent=dn,document.head.appendChild(e),this.stylesInjected=!0}static getLanguage(e){return tt[e]}};var Ke="lionrapid:",ee=`${Ke}version`,rt="1",te=class{constructor(e={}){d(this,"name","LocalStorageRepository");d(this,"type","memory");d(this,"config");d(this,"available");d(this,"prefix");d(this,"defaultTTL");d(this,"maxSize");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{prefix:e.options?.prefix??Ke,ttl:e.options?.ttl??1440*60*1e3,maxSize:e.options?.maxSize??500,...e.options}},this.prefix=this.config.options?.prefix??Ke,this.defaultTTL=this.config.options?.ttl??1440*60*1e3,this.maxSize=this.config.options?.maxSize??500,this.available=this.checkAvailability(),this.available&&this.migrateIfNeeded()}checkAvailability(){if(typeof window>"u")return!1;try{let e=`${this.prefix}__test__`;return window.localStorage.setItem(e,"test"),window.localStorage.removeItem(e),!0}catch{return!1}}migrateIfNeeded(){try{window.localStorage.getItem(ee)!==rt&&(this.clear(),window.localStorage.setItem(ee,rt))}catch{}}get(e){if(!this.available)return null;try{let t=this.prefix+e,n=window.localStorage.getItem(t);if(!n)return null;let r=JSON.parse(n);return r.expiry!==null&&Date.now()>r.expiry?(window.localStorage.removeItem(t),null):r.value}catch{return null}}set(e,t){if(!this.available)return;let n=this.prefix+e,r={value:t,expiry:this.defaultTTL?Date.now()+this.defaultTTL:null,timestamp:Date.now()};try{this.getEntryCount()>=this.maxSize&&this.evictOldest(),window.localStorage.setItem(n,JSON.stringify(r))}catch(s){if(this.isQuotaError(s)){this.evictOldest();try{window.localStorage.setItem(n,JSON.stringify(r))}catch{}}}}remove(e){if(this.available)try{window.localStorage.removeItem(this.prefix+e)}catch{}}clear(){if(this.available)try{let e=[];for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);n?.startsWith(this.prefix)&&n!==ee&&e.push(n)}e.forEach(t=>window.localStorage.removeItem(t))}catch{}}clearNamespace(e,t){if(!this.available)return;let n=`@${e}:${t}`,r=`${e}:${t}:`;try{let s=[];for(let i=0;i<window.localStorage.length;i++){let o=window.localStorage.key(i);if(!o?.startsWith(this.prefix))continue;let l=o.slice(this.prefix.length);(l===n||l.startsWith(r))&&s.push(o)}s.forEach(i=>window.localStorage.removeItem(i))}catch{}}getNamespace(e,t){let n=`@${e}:${t}`,r=this.get(n);if(!r)return null;try{return JSON.parse(r)}catch{return this.remove(n),null}}setNamespace(e,t,n){let r=`@${e}:${t}`;this.set(r,JSON.stringify(n))}getEntries(){let e={};if(!this.available)return e;try{for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);if(!n?.startsWith(this.prefix)||n===ee)continue;let r=n.slice(this.prefix.length),s=this.get(r);s!==null&&(e[r]=s)}}catch{}return e}getConfig(){return this.config}isAvailable(){return this.available}getEntryCount(){if(!this.available)return 0;let e=0;try{for(let t=0;t<window.localStorage.length;t++){let n=window.localStorage.key(t);n?.startsWith(this.prefix)&&n!==ee&&e++}}catch{}return e}isQuotaError(e){return e instanceof DOMException?e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED":!1}evictOldest(){if(this.available)try{let e=[];for(let n=0;n<window.localStorage.length;n++){let r=window.localStorage.key(n);if(!(!r?.startsWith(this.prefix)||r===ee))try{let s=window.localStorage.getItem(r);if(s){let i=JSON.parse(s);e.push({key:r,timestamp:i.timestamp})}}catch{window.localStorage.removeItem(r)}}e.sort((n,r)=>n.timestamp-r.timestamp);let t=Math.max(1,Math.floor(e.length*.25));for(let n=0;n<t&&n<e.length;n++)window.localStorage.removeItem(e[n].key)}catch{}}getCacheStats(){let e=this.getEntryCount(),t=this.maxSize>0?`${Math.round(e/this.maxSize*100)}%`:"0%";return{size:e,maxSize:this.maxSize,usage:t}}};var Se=Object.freeze({translations:"lionrapid-v1",offlineFloor:"lionrapid-offline-v1"}),st="https://cache.lionrapid.internal/";var at=Se.translations,it=st,j=class{constructor(e={}){d(this,"name","CacheStorageRepository");d(this,"type","storage");d(this,"config");d(this,"cacheName");d(this,"entryPrefix");d(this,"defaultTTL");d(this,"available");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{cacheName:e.options?.cacheName??at,ttl:e.options?.ttl??10080*60*1e3,...e.options}},this.cacheName=this.config.options?.cacheName??at;let t=this.config.options?.scope;this.entryPrefix=t?`${it}${encodeURIComponent(t)}/`:it,this.defaultTTL=this.config.options?.ttl??10080*60*1e3,this.available=this.checkAvailability()}checkAvailability(){return typeof caches<"u"}async get(e){if(!this.available)throw new b(e);try{let t=await caches.open(this.cacheName),n=await t.match(this.entryPrefix+e);if(!n)throw new b(e);let r=await n.json();if(r.expiry!==null&&Date.now()>r.expiry)throw await t.delete(this.entryPrefix+e),new b(e);return r.value}catch(t){throw t instanceof b?t:new b(e)}}async set(e,t){if(this.available)try{let n=await caches.open(this.cacheName),r={value:t,expiry:this.defaultTTL?Date.now()+this.defaultTTL:null,timestamp:Date.now()};await n.put(this.entryPrefix+e,new Response(JSON.stringify(r),{headers:{"Content-Type":"application/json"}}))}catch{}}async remove(e){if(this.available)try{await(await caches.open(this.cacheName)).delete(this.entryPrefix+e)}catch{}}async clear(){if(this.available)try{let e=await caches.open(this.cacheName),t=await e.keys();await Promise.all(t.filter(n=>n.url.includes(this.entryPrefix)).map(n=>e.delete(n)))}catch{}}async clearNamespace(e,t){if(!this.available)return;let n=`@${e}:${t}`,r=`${e}:${t}:`;try{let s=await caches.open(this.cacheName),i=await s.keys();await Promise.all(i.filter(o=>{let l=o.url,u=l.includes(this.entryPrefix)?l.substring(l.indexOf(this.entryPrefix)+this.entryPrefix.length):"";return u===n||u.startsWith(r)}).map(o=>s.delete(o)))}catch{}}async getNamespace(e,t){let n=`@${e}:${t}`,r=await this.get(n);try{return JSON.parse(r)}catch{throw await this.remove(n),new b(n)}}async setNamespace(e,t,n){let r=`@${e}:${t}`;await this.set(r,JSON.stringify(n))}getConfig(){return this.config}isAvailable(){return this.available}async getEntries(){let e={};if(!this.available)return e;try{let n=await(await caches.open(this.cacheName)).keys();for(let r of n){let s=r.url;if(!s.includes(this.entryPrefix))continue;let i=s.substring(s.indexOf(this.entryPrefix)+this.entryPrefix.length);try{let o=await this.get(i);e[i]=o}catch{}}}catch{}return e}async getCacheStats(){if(!this.available)return{size:0,cacheName:this.cacheName};try{return{size:(await(await caches.open(this.cacheName)).keys()).filter(r=>r.url.includes(this.entryPrefix)).length,cacheName:this.cacheName}}catch{return{size:0,cacheName:this.cacheName}}}};var ot="https://app.lionrapid.com";function lt(a){return a?M(a).slice(0,8):"none"}function mn(a){let e=a.startsWith("pk_");return{bootNetwork:e,syncMissing:{enabled:e},warnRefused:!e}}function hn(a){return{...a,apiKey:""}}function fn(a){let e=null,t=null;return{onChange:async n=>{if(a.setCookie(n),a.navigate){a.navigate(n);return}if(e){await e(n);return}t=n},attach:n=>{if(e=n,t!==null){let r=t;t=null,n(r).catch(()=>{})}}}}function ct(a){document.readyState==="loading"?document.addEventListener("DOMContentLoaded",a,{once:!0}):a()}function Ue(a){let e=a.dataset.apiKey||"",t=a.dataset.baseUrl||ot,n=a.dataset.defaultLocale||"en",r=a.dataset.namespace||"default",s=(a.dataset.languages||n).split(",").map(x=>x.trim()).filter(Boolean),i=(a.dataset.exclude||"").split(",").map(x=>x.trim()).filter(Boolean),o=a.dataset.autoDetect==="true",l=a.dataset.mode==="dynamic-only"?"dynamic-only":"full",u=a.dataset.switcher&&a.dataset.switcher!=="false"?a.dataset.switcher:void 0,p=a.dataset.switcherPosition||void 0,m=a.dataset.switcherShowFlags!=="false",g=a.dataset.switcherShowNames==="true",h=a.dataset.switcherCustomCss||void 0,f=a.dataset.editorCdn||void 0,T=a.dataset.offline!=="false";return{apiKey:e,baseUrl:t,defaultLocale:n,namespace:r,languages:s,excludeSelectors:i,autoDetect:o,mode:l,switcherStyle:u,switcherPosition:p,switcherShowFlags:m,switcherShowNames:g,switcherCustomCss:h,editorCdnUrl:f,offline:T}}function yn(a){if(typeof document>"u")return null;let e=document.cookie.match(/(?:^|;\s*)lionrapid_locale=([a-z]{2,3}(?:-[a-z0-9]{2,4})*)/i);return e&&ue([e[1]],a,"")||null}function bn(a,e){if(typeof navigator>"u")return e;let t=navigator.languages&&navigator.languages.length>0?[...navigator.languages]:[navigator.language||navigator.userLanguage||""];return ue(t,a,e)}function vn(a,e,t,n,r){let s=a.split("/"),i=s[1]??"",l=We.test(i)&&ue([i],r,"")!==""?"/"+s.slice(2).join("/"):a;return(t===n?"":"/"+t)+(l||"/")+e}function wn(a,e,t){window.location.href=vn(window.location.pathname,window.location.search,a,e,t)}function En(a){if(a.mode==="dynamic-only"){let t=typeof document<"u"?document.documentElement.lang:"";return t?Ae(t):a.defaultLocale}let e=yn(a.languages);return e||(a.autoDetect?bn(a.languages,a.defaultLocale):a.defaultLocale)}function ut(a){typeof document<"u"&&(document.documentElement.dir=de(a))}function Me(a){typeof document<"u"&&a&&(document.documentElement.lang=a),ut(a)}function Cn(){let a=document.currentScript;if(a instanceof HTMLScriptElement&&a.dataset.apiKey)return a;let e=document.querySelectorAll("script[data-api-key]");return e.length>1&&console.warn(`[LionRapid] ${e.length} script tags with data-api-key found; using the last one`),e[e.length-1]}async function De(){let a=Cn();if(!a){console.warn("[LionRapid] No script tag with data-api-key found");return}let e=Ue(a);if(window.__lionrapidConfig=hn(e),!e.apiKey){console.warn("[LionRapid] Missing data-api-key attribute");return}let t=mn(e.apiKey);t.warnRefused&&console.error("[LionRapid] data-api-key must be a publishable pk_ key \u2014 network translations are disabled. Copy the snippet from the integration hub to get the pk_ key for this project.");let n=En(e);e.mode==="dynamic-only"?ut(n):Me(n);let r=new q;r.setLanguages(e.languages),r.setInitialLocale(n),ct(()=>{if(e.mode!=="dynamic-only"&&e.switcherStyle&&!document.querySelector("[data-lionrapid-switcher]")){let l=document.createElement("div");l.dataset.lionrapidSwitcher=e.switcherStyle,e.switcherPosition&&(l.dataset.lionrapidSwitcherPosition=e.switcherPosition),e.switcherShowFlags||(l.dataset.lionrapidSwitcherShowFlags="false"),e.switcherShowNames||(l.dataset.lionrapidSwitcherShowNames="false"),e.switcherCustomCss&&(l.dataset.lionrapidSwitcherCustomCss=e.switcherCustomCss),document.body.appendChild(l)}r.initAll()});let i=fn({setCookie:l=>{document.cookie=`lionrapid_locale=${l}; path=/; max-age=31536000; SameSite=Lax`},navigate:e.mode==="dynamic-only"?l=>wn(l,e.defaultLocale,e.languages):null});r.setOnLanguageChange(i.onChange);let o=lt(e.apiKey);try{let l=W.init({defaultLocale:n,namespace:e.namespace}).use(new O({enabled:!0})).use(new te({enabled:!0,options:{prefix:`lionrapid:${o}:`}})).use(new j({enabled:!0,options:{scope:o}}));e.offline!==!1&&l.use(new j({enabled:!0,options:{ttl:Number.MAX_SAFE_INTEGER,cacheName:Se.offlineFloor,scope:o}})),t.bootNetwork&&l.use(new J({enabled:!0,options:{baseUrl:e.baseUrl,apiKey:e.apiKey,syncMissing:t.syncMissing,preloadNamespaces:[{locale:n,namespace:e.namespace,eager:!0}]}}));let u=await l.build(),p=new Z({excludeSelectors:e.excludeSelectors});p.setCore(u),p.init({namespace:e.namespace,locale:n,sourceLocale:e.defaultLocale}),r.setCore(u),i.attach(async y=>{await u.changeLanguage(y,{preloadNamespaces:[e.namespace]}),Me(y),p.updateLocale(y),p.retranslate()});let m=[2e3,8e3,3e4],g=6e4,h=!1,f=[],T=Date.now(),x=async()=>{await u.reloadNamespace(e.namespace),p.translatePage(),T=Date.now()},He=()=>{f.forEach(y=>clearTimeout(y)),f=[]};u.bus.on("sync:batch:complete",()=>{h=!0,He(),m.forEach(y=>{f.push(setTimeout(()=>x().catch(()=>{}),y))})}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&(h?(h=!1,He(),x().catch(()=>{})):Date.now()-T>g&&x().catch(()=>{}))});let dt={t:(y,ne,xe)=>u.t(y,ne||{},xe),tHtml:(y,ne,xe)=>u.tHtml(y,ne||{},xe),changeLanguage:async y=>{await u.changeLanguage(y,{preloadNamespaces:[e.namespace]}),Me(y),p.updateLocale(y),p.retranslate(),r.initAll()},getCurrentLocale:()=>u.getCurrentLocale(),on:(y,ne)=>u.bus.on(y,ne),retranslate:()=>p.retranslate(),reloadTranslations:x,autoTranslator:p,languageSwitcher:r};window.LionRapid=dt;let je=new URLSearchParams(window.location.search).get("__lr_editor");if(je&&!document.querySelector("script[data-grant], script[data-lr-editor]")){let y=document.createElement("script");y.src=e.editorCdnUrl||"https://cdn.lionrapid.com/lionrapid.editor.min.js",y.dataset.grant=je,y.dataset.locale=u.getCurrentLocale(),y.dataset.api=e.baseUrl,y.async=!0,document.body.appendChild(y)}ct(()=>{e.mode!=="dynamic-only"&&p.translatePage(),p.observe()})}catch(l){console.error("[LionRapid] Initialization failed:",l)}}De();return bt(Rn);})();
|
|
83
83
|
//# sourceMappingURL=lionrapid.auto.min.js.map
|