@lionrapid/core 0.1.4-beta.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/base/event-emitter.d.ts.map +1 -1
- package/dist/base/event-emitter.js +4 -1
- package/dist/base/event-emitter.js.map +1 -1
- package/dist/browser/lionrapid.auto.dev.js +45 -10
- package/dist/browser/lionrapid.auto.dev.js.map +3 -3
- package/dist/browser/lionrapid.auto.js +45 -10
- package/dist/browser/lionrapid.auto.js.map +3 -3
- package/dist/browser/lionrapid.auto.min.js +3 -3
- package/dist/browser/lionrapid.auto.min.js.map +4 -4
- package/dist/browser/lionrapid.editor.js +22 -1
- package/dist/browser/lionrapid.editor.js.map +3 -3
- package/dist/browser/lionrapid.editor.min.js +3 -3
- package/dist/browser/lionrapid.editor.min.js.map +4 -4
- package/dist/browser/lionrapid.esm.js +45 -10
- package/dist/browser/lionrapid.esm.js.map +3 -3
- package/dist/browser/lionrapid.esm.min.js +2 -2
- package/dist/browser/lionrapid.esm.min.js.map +4 -4
- package/dist/browser/lionrapid.iife.dev.js +45 -10
- package/dist/browser/lionrapid.iife.dev.js.map +3 -3
- package/dist/browser/lionrapid.iife.js +45 -10
- package/dist/browser/lionrapid.iife.js.map +3 -3
- package/dist/browser/lionrapid.iife.min.js +2 -2
- package/dist/browser/lionrapid.iife.min.js.map +4 -4
- package/dist/browser/lionrapid.umd.js +45 -10
- package/dist/browser/lionrapid.umd.js.map +3 -3
- package/dist/browser/lionrapid.umd.min.js +2 -2
- package/dist/browser/lionrapid.umd.min.js.map +4 -4
- package/dist/content/safe-href.d.ts +22 -0
- package/dist/content/safe-href.d.ts.map +1 -0
- package/dist/content/safe-href.js +48 -0
- package/dist/content/safe-href.js.map +1 -0
- package/dist/content/style-mapper/DefaultStyleMapper.d.ts.map +1 -1
- package/dist/content/style-mapper/DefaultStyleMapper.js +5 -1
- package/dist/content/style-mapper/DefaultStyleMapper.js.map +1 -1
- package/dist/utils/logger.d.ts.map +1 -1
- package/dist/utils/logger.js +43 -8
- package/dist/utils/logger.js.map +1 -1
- package/dist/utils/translation-flow.d.ts.map +1 -1
- package/dist/utils/translation-flow.js +7 -2
- package/dist/utils/translation-flow.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var LionRapid=(()=>{var
|
|
2
|
-
`);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?`${m[t]}${e}${m.RESET}`:e}getColors(){return m}createPackageLogger(e,t){return new d({...this.config,packageName:e,packageEmoji:t||"\u{1F4E6}"})}getLogLevelFromEnv(){switch(ce.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":return 2;case"ERROR":return 3;case"NONE":return 4;default:return 0}}shouldEnableLogging(){return ce!=="NONE"}shouldUseColors(){return le?!1:typeof window<"u"?!0:(typeof process<"u",K)}},C=()=>{},ae=()=>()=>{},i=M?{configure:C,debug:C,info:C,warn:(d,e)=>{console.warn(`\u{1F981} LionRapid Core \u26A0\uFE0F ${d}`,e||"")},error:(d,e)=>{console.error(`\u{1F981} LionRapid Core \u274C ${d}`,e||"")},time:ae,colorize:d=>d,getColors:()=>m,createPackageLogger:(d,e)=>({configure:C,debug:C,info:C,warn:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${d}`;console.warn(`${r} \u26A0\uFE0F ${t}`,n||"")},error:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${d}`;console.error(`${r} \u274C ${t}`,n||"")},time:ae,colorize:t=>t,getColors:()=>m,createPackageLogger:C})}:new B({packageName:"LionRapid Core",packageEmoji:"\u{1F981}"}),de=M?function(){return i}:B,pe=d=>{if(M){let e=`${d.packageEmoji||"\u{1F4E6}"} ${d.packageName||"LionRapid"}`;return{configure:C,debug:C,info:C,warn:(t,n)=>{console.warn(`${e} \u26A0\uFE0F ${t}`,n||"")},error:(t,n)=>{console.error(`${e} \u274C ${t}`,n||"")},time:ae,colorize:t=>t,getColors:()=>m,createPackageLogger:C}}return new B(d)},ue=d=>{if(M)return{start:C,end:C,elapsed:()=>0};let e;return{start:()=>{K&&(e=performance.now(),i.debug(`\u23F1\uFE0F ${d} - started`))},end:()=>{if(K){let t=performance.now()-e;return i.debug(`\u23F1\uFE0F ${d} - completed in ${t.toFixed(2)}ms`),t}return 0},elapsed:()=>K?performance.now()-e:0}};var U=class{constructor(){c(this,"eventListeners",new Map);c(this,"debugMode",!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,a,o)=>{this.emit("translation:missing",{context:this.createContext(e.id,[...n,"missing"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:o}})},notFound:(s,a,o)=>{this.emit("translation:not-found",{context:this.createContext(e.id,[...n,"not-found"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:o,status:404}})},locked:(s,a,o)=>{this.emit("translation:locked",{context:this.createContext(e.id,[...n,"locked"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,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,a=typeof e=="string"?e:e.cleanKey;this.emit("repo:set:success",{context:this.createContext(s,[...n,"set","success"]),payload:{key:a,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:a=>{this.emit("network:request:success",{context:this.createContext(r,[...s,"success"]),payload:{key:n,value:a,method:t||"GET"}})},error:(a,o)=>{this.emit("network:request:error",{context:this.createContext(r,[...s,"error"]),payload:{key:n,method:t||"GET",error:a,...o&&{status:o}}})},retry:(a,o,l)=>{this.emit("network:retry",{context:this.createContext(r,[...s,"retry"]),payload:{key:n,attempt:a,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}})},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:()=>{i.debug(`\u{1F9F9} Cache ${e} starting: ${t}`)},complete:()=>{i.debug(`\u2705 Cache ${e} complete: ${n?.clearedCount||0} entries`)}}:{start:()=>{},complete:()=>{}}}};var O=class{constructor(e){c(this,"asyncHandlers",[]);c(this,"syncHandlers",[]);c(this,"bus");this.bus=e}addSyncHandler(e){e.enabled&&(this.syncHandlers.push(e),this.sortHandlersIfNeeded(this.syncHandlers),i.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 i.debug(`Sync hit: ${t.name} (${n.duration}ms)`),n}catch(n){i.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&&(i.debug(`Saving to ${r.length} memory handlers`),r.forEach(s=>{try{s.save(e,t),i.debug(`Saved to memory: ${s.name}`)}catch(a){i.warn(`Failed to save to memory ${s.name}:`,a),this.bus.repo(e,s.name).error(a)}}))}saveNamespaceToMemoryHandlers(e,t){let n=this.syncHandlers.filter(r=>r.type==="memory"&&r.saveNamespace);n.length!==0&&(i.debug(`Saving namespace to ${n.length} memory handlers`),n.forEach(r=>{try{r.saveNamespace(e,t),i.debug(`Namespace saved to memory: ${r.name}`,{locale:t.locale,namespace:t.namespace})}catch(s){i.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),i.debug(`Async handler added: ${e.name}`))}async handleAsync(e){for(let t of this.asyncHandlers)try{i.debug(`Trying handler: ${t.name}`);let n=await t.lookup(e);if(n.value&&n.status===200)return i.debug(`Async hit: ${t.name} (${n.duration}ms)`),n.namespaceLoaded?(i.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);i.debug(`Handler ${t.name} returned fallback (status: ${n.status})`)}catch(n){i.warn(`Handler ${t.name} failed:`,n),this.bus.repo(e,t.name).error(n);continue}return i.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;i.debug(`Saving to ${s.length} storage handlers`);let a=s.map(async o=>{try{await o.save(e,t),i.debug(`Saved to storage: ${o.name}`)}catch(l){i.warn(`Failed to save to storage ${o.name}:`,l),this.bus.repo(e,o.name).error(l)}});await Promise.allSettled(a)}async saveNamespaceToStorageHandlers(e,t){let n=this.asyncHandlers.filter(s=>s.type==="storage"&&s.saveNamespace);if(n.length===0)return;i.debug(`Saving namespace to ${n.length} storage handlers`);let r=n.map(async s=>{try{await s.saveNamespace(e,t),i.debug(`Namespace saved to storage: ${s.name}`,{locale:t.locale,namespace:t.namespace})}catch(a){i.warn(`Failed to save namespace to storage ${s.name}:`,a),this.bus.repo(`${t.locale}:${t.namespace}`,s.name).error(a)}});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?.(),i.debug(`Handler destroyed: ${n.name}`)}catch(r){i.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,a=r.priority||Number.MAX_SAFE_INTEGER;return s-a})}async loadNamespace(e,t){for(let n of this.asyncHandlers)if(n.type==="network")try{i.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 i.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){i.warn(`Failed to load namespace: ${e}:${t} from ${n.name}`,r),this.bus.repo(`${e}:${t}`,n.name).error(r);continue}return i.debug(`No handlers found namespace: ${e}:${t}`),null}clearCache(){let e=[...this.syncHandlers,...this.asyncHandlers];for(let t of e)try{t.destroy?.(),i.debug(`Cache cleared for handler: ${t.name}`)}catch(n){i.warn(`Failed to clear cache for handler: ${t.name}`,n)}i.debug("Cache cleared for all handlers")}clearNamespace(e,t){for(let n of this.syncHandlers)try{n.clearNamespace?.(e,t)}catch(r){i.warn(`Failed to clear namespace for handler: ${n.name}`,r)}i.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){i.warn(`Failed to set cache in handler: ${r.name}`,s)}i.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){i.debug(`Error getting namespace data from ${t.name}:`,n)}return null}};function ge(d){let e=d.indexOf(":");if(e>0&&e<d.length-1){let t=d.substring(0,e),n=d.substring(e+1);return{originalKey:d,namespace:t,cleanKey:n,hasExplicitNamespace:!0}}return{originalKey:d,cleanKey:d,hasExplicitNamespace:!1}}function he(d,e,t,n){let r=d.hasExplicitNamespace?d.namespace:t;return{locale:e,namespace:r,fallbackLocale:n||e}}function E(d,e){if(!(!d||!e)){if(!e.includes(".")&&!e.includes("["))return d[e];try{let t=ie(e),n=d;for(let r of t){if(n==null){i.debug(`\u{1F50D} Nested key resolution stopped at null/undefined for: ${e}`);return}if(typeof r=="number"){if(!Array.isArray(n)){i.debug(`\u{1F50D} Expected array for index ${r} in path: ${e}`);return}n=n[r]}else{if(typeof n!="object"){i.debug(`\u{1F50D} Expected object for key '${r}' in path: ${e}`);return}n=n[r]}}return i.debug(`\u{1F50D} Nested key resolved: ${e} \u2192 ${typeof n=="object"?"[Object]":n}`),n}catch(t){i.debug(`\u{1F50D} Nested key resolution error for '${e}':`,t);return}}}function ie(d){let e=[],t="",n=!1;for(let r=0;r<d.length;r++){let s=d[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 a=parseInt(t,10);isNaN(a)?e.push(t):e.push(a),t=""}n=!1}else t+=s}return t&&e.push(t),e}function G(d,e,t){let n=[d];return e&&n.push(e),n.push(t),n.join(":")}function v(d,e){return`@${d}:${e}`}function z(d,e="",t,n){let r={};for(let[s,a]of Object.entries(d)){let o=e?`${e}.${s}`:s,l=G(t,n,o);typeof a=="object"&&a!==null&&"text"in a&&"styles"in a?r[l]=JSON.stringify(a):typeof a=="object"&&a!==null?Object.assign(r,z(a,o,t,n)):r[l]=JSON.stringify({text:String(a),styles:{}})}return r}function I(d,e,t,n,r,s){let a=performance.now(),{defaultValue:o,params:l}=$e(t,n),p=ge(d),u=he(p,e,r,s),g=G(u.locale,u.namespace,p.cleanKey),y=u.namespace?v(u.locale,u.namespace):void 0;return{id:`${g}-${a}`,originalKey:d,originalParams:t,originalDefaultValue:n,cleanKey:p.cleanKey,hasExplicitNamespace:p.hasExplicitNamespace,parsedParams:l,parsedDefaultValue:o,locale:e,namespace:u.namespace,fallbackLocale:s,individualCacheKey:g,namespaceCacheKey:y,startTime:a}}function $e(d,e){let t,n;return typeof d=="string"?(t=d,typeof e=="object"&&(n=e)):typeof d=="object"&&(n=d,typeof e=="string"&&(t=e)),{defaultValue:t,params:n}}var J=class{constructor(e,t){c(this,"name");c(this,"version","1.0.0");c(this,"priority");c(this,"type","memory");c(this,"enabled");c(this,"ttlMap",new Map);c(this,"ttl");c(this,"repository");c(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();i.debug(`Sync lookup: ${e.cleanKey}`);let n=this.bus.repo(e,this.name);n.getStart();let r=this.tryDirectLookup(e);if(r!==null)return i.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 i.debug(`Namespace hit: ${e.cleanKey}`),n.getSuccess(s.text),this.createResult(s,"memory",200,t,!0)}return i.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)),i.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=v(t.locale,t.namespace);this.setWithTTL(r,JSON.stringify(e));let s=z(e,"",t.locale,t.namespace);for(let[a,o]of Object.entries(s))this.setWithTTL(a,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=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=E(r,e.cleanKey);if(s!=null){let a;return typeof s=="object"&&s!==null&&"text"in s?a={text:String(s.text),styles:s.styles||{}}:a={text:String(s),styles:{}},this.setWithTTL(e.individualCacheKey,JSON.stringify(a)),i.debug(`Cached from namespace: ${e.cleanKey}`),a}}catch(r){i.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),i.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,a=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:a}}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 a of Object.keys(s))a.startsWith(r)&&(this.repository.remove(a),this.ttlMap.delete(a));i.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)),i.debug(`Direct cache set: ${e}`)}};var Q=class{constructor(e,t){c(this,"name");c(this,"version","1.0.0");c(this,"priority");c(this,"type","storage");c(this,"enabled");c(this,"ttlMap",new Map);c(this,"ttl");c(this,"repository");c(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();i.debug(`Async lookup: ${e.cleanKey}`);let n=this.bus.repo(e,this.name),r=await this.tryDirectLookup(e);if(r!==null)return i.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 i.debug(`Namespace hit: ${e.cleanKey}`),n.getSuccess(s.text),this.createResult(s,"storage",200,t,!0)}return i.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)),i.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;i.debug(`Saving namespace: ${t.locale}:${t.namespace} (${r} keys)`);let s=v(t.locale,t.namespace);await this.setWithTTL(s,JSON.stringify(e));let a=z(e,"",t.locale,t.namespace),o=0;for(let[l,p]of Object.entries(a))await this.setWithTTL(l,p),o++;i.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=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=E(r,e.cleanKey);if(s!=null){let a;return typeof s=="object"&&s!==null&&"text"in s?a={text:String(s.text),styles:s.styles||{}}:a={text:String(s),styles:{}},await this.setWithTTL(e.individualCacheKey,JSON.stringify(a)),i.debug(`Cached from namespace: ${e.cleanKey}`),a}}catch(r){i.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),i.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,a=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:a}}return e}async destroy(){await this.repository.clear(),this.ttlMap.clear()}getEntries(){if(this.repository.getEntries!==void 0)return this.repository.getEntries()}};var N=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)}},h=class extends N{constructor(e){super(e,404,`Translation not found: ${e}`)}},x=class extends N{constructor(t,n){super(t,423,`Translation locked: ${t}`);this.retryAfter=n}},$=class extends N{constructor(e,t){super(e,t,`Server error ${t}: ${e}`)}},R=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="NetworkError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}};function me(d){return d instanceof N}function Y(d){return d instanceof $||d instanceof R}function ye(d){return d instanceof h||d instanceof x}var X=class{constructor(e,t){c(this,"repository");c(this,"name");c(this,"priority");c(this,"version","1.0.0");c(this,"type","network");c(this,"enabled");c(this,"bus");c(this,"retryCount");c(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(),i.debug(`Network lookup: ${e.cleanKey}`);try{let s=await this.lookupContentUnitWithRetry(e.individualCacheKey);return i.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 h&&e.namespace?(i.debug(`Individual key not found, trying namespace: ${e.cleanKey}`),this.lookupFromNamespace(e,n,t,r)):s instanceof x?(i.debug(`Translation locked (423): ${e.cleanKey}`),this.handleTranslationLocked(e,n,s,t,r)):(i.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=E(s.data,e.cleanKey);if(o!=null){let l,p={};if(typeof o=="object"&&o!==null&&"text"in o){let u=o;l=String(u.text),p=u.styles||{}}else l=String(o);return i.debug(`Network namespace hit: ${e.cleanKey}, hasStyles=${Object.keys(p).length>0}`),r.success(l),this.createTranslationResult(l,"network",200,n,void 0,!1,{locale:e.locale,namespace:e.namespace,data:s.data},p)}}let a=new h(e.cleanKey);return this.handleTranslationNotFound(e,t,a,n)}catch(s){return i.debug(`Namespace load failed: ${e.cleanKey}`,s),s instanceof h?this.handleTranslationNotFound(e,t,s,n):s instanceof x?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?(i.debug(`Network namespace not modified: ${e}:${t}`),this.createNamespaceResult(null,"network",304,n)):(i.debug(`Network namespace loaded: ${e}:${t}`),this.createNamespaceResult(r,"network",200,n))}catch(r){return r instanceof x?(i.debug(`Namespace locked (423): ${e}:${t}`),this.createNamespaceResult(null,"fallback",423,n,r)):r instanceof h?(i.debug(`Network namespace not found: ${e}:${t}`),this.createNamespaceResult(null,"fallback",404,n,r)):(i.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(a){if(r<=this.retryCount&&Y(a)){let o=this.calculateBackoff(r);return s.retry(r,o,a.message),await this.delay(o),i.debug(`Retrying ${n} (${r}/${this.retryCount}) after ${o}ms`),this.withRetry(e,t,n,r+1)}throw a}}handleTranslationNotFound(e,t,n,r){return i.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,a,o,l){return{value:e,source:t,status:n,duration:Date.now()-r,...s&&{error:s},...a!==void 0&&{cached:a},...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||[]}};var S=class{constructor(){c(this,"elementToStyles",{b:"bold",strong:"bold",i:"italic",em:"italic",u:"underline",s:"strikethrough",del:"strikethrough",strike:"strikethrough",code:"code",mark:"highlight",sub:"subscript",sup:"superscript"});c(this,"styleToElement",{bold:"b",italic:"i",underline:"u",strikethrough:"s",code:"code",highlight:"mark",subscript:"sub",superscript:"sup",strong:"b",b:"b",em:"i",i:"i",u:"u",s:"s",del:"s",strike:"s",mark:"mark",sub:"sub",sup:"sup"})}mapElementToStyles(e,t){let n=[],r=e.toLowerCase(),s=this.elementToStyles[r];return s&&n.push(s),r==="a"&&t.href&&n.push(`hyperlink:${t.href}`),n}mapStylesToElement(e){for(let t of e)if(t.startsWith("hyperlink:"))return{element:"a",attrs:{href:t.slice(10)}};for(let t of e){let n=this.styleToElement[t];if(n)return{element:n,attrs:{}}}return{element:"span",attrs:{}}}};var L=class{constructor(e={}){c(this,"styleMapper");this.styleMapper=e.styleMapper??new S}parse(e){if(/<\/?[0-9]+>/.test(e))return{text:e,styles:{}};let n={},r=0,s=[],a="",o=0;for(;o<e.length;){let l=this.matchTag(e,o);if(!l){a+=e.slice(o);break}if(a+=e.slice(o,l.startIndex),l.isClosing){let p=this.findMatchingOpenTag(s,l.tag.toLowerCase());if(p!==null){a+=`</${p}>`;let u=s.findIndex(g=>g.index===p);u!==-1&&s.splice(u,1)}else a+=e.slice(l.startIndex,l.endIndex)}else if(l.isSelfClosing){r++;let p=this.styleMapper.mapElementToStyles(l.tag,l.attrs);p.length>0&&(n[String(r)]=p,a+=`<${r}/>`)}else{let p=this.styleMapper.mapElementToStyles(l.tag,l.attrs);if(p.length>0)r++,n[String(r)]=p,a+=`<${r}>`,s.push({tag:l.tag.toLowerCase(),index:r});else{let u=this.findClosingTagIndex(e,l.endIndex,l.tag);if(u!==-1){let g=e.slice(l.endIndex,u),y=this.parse(g),f=r;for(let[k,re]of Object.entries(y.styles)){let se=String(f+parseInt(k,10));n[se]=re}a+=y.text.replace(/<(\/?)\d+>/g,(k,re)=>{let se=parseInt(k.replace(/[</>]/g,""),10);return`<${re}${f+se}>`});let b=this.matchTag(e,u);o=b?b.endIndex:u;let w=Object.keys(y.styles).length>0?Math.max(...Object.keys(y.styles).map(Number)):0;r=f+w;continue}}}o=l.endIndex}for(;s.length>0;){let l=s.pop();a+=`</${l.index}>`}return{text:a,styles:n}}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*(\/?)>/,a=e.slice(n).match(r);if(!a)return n+1<e.length?this.matchTag(e,n+1):null;let[o,l,p,u,g]=a;return{tag:p,attrs:this.parseAttributes(u),isClosing:l==="/",isSelfClosing:g==="/",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,a,o,l]=r,p=a??o??l??"";t[s.toLowerCase()]=p}return t}findMatchingOpenTag(e,t){for(let n=e.length-1;n>=0;n--)if(e[n].tag===t)return e[n].index;return null}findClosingTagIndex(e,t,n){let r=n.toLowerCase(),s=1,a=t;for(;a<e.length&&s>0;){let o=this.matchTag(e,a);if(!o)break;if(o.tag.toLowerCase()===r)if(o.isClosing){if(s--,s===0)return o.startIndex}else o.isSelfClosing||s++;a=o.endIndex}return-1}};var P=class{constructor(e={}){c(this,"styleMapper");this.styleMapper=e.styleMapper??new S}serialize(e){let{text:t,styles:n}=e,r=/<(\/?)?(\d+)(\/)?>/g,s="",a=0,o;for(;(o=r.exec(t))!==null;){s+=t.slice(a,o.index);let[l,p,u,g]=o,f=n[u]||[];if(p){let b=this.styleMapper.mapStylesToElement(f);s+=`</${b.element}>`}else if(g){let b=this.styleMapper.mapStylesToElement(f),w=this.formatAttributes(b.attrs);s+=`<${b.element}${w} />`}else{let b=this.styleMapper.mapStylesToElement(f),w=this.formatAttributes(b.attrs);s+=`<${b.element}${w}>`}a=o.index+l.length}return s+=t.slice(a),s}formatAttributes(e){let t=Object.entries(e);return t.length===0?"":" "+t.map(([n,r])=>`${n}="${this.escapeAttributeValue(r)}"`).join(" ")}escapeAttributeValue(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}};var A=class{constructor(e,t,n,r){c(this,"handlerChain");c(this,"bus");c(this,"currentLocale");c(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 a=JSON.parse(s);return typeof a=="object"&&"text"in a?{value:String(a.text),styles:a.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,...a]=e.split(":"),o=a.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:a=!0}=e,o=this.currentLocale(),l=0;if(r){let[p,u]=r.split(":");p&&u&&(this.handlerChain.clearNamespace(p,u),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 p=this.handlerChain.getEntries(),u=new Set;for(let g in p){let y=p[g];if(y&&typeof y=="object"){for(let f of Object.keys(y))if(f.startsWith(`${n}:`)||f.startsWith(`@${n}:`)){let b=f.replace("@","").split(":");b[1]&&u.add(b[1])}}}for(let g of u)this.handlerChain.clearNamespace(n,g),l++}else if(s){let p=this.handlerChain.getEntries(),u=new Map;for(let g in p){let y=p[g];if(y&&typeof y=="object"){for(let f of Object.keys(y))if(s(f)){let b=f.replace("@","").split(":"),w=b[0],k=b[1];w&&k&&(u.has(w)||u.set(w,new Set),u.get(w).add(k),l++)}}}for(let[g,y]of u)for(let f of y)this.handlerChain.clearNamespace(g,f)}else this.handlerChain.clearCache(),l=-1;this.bus.emit("cache:invalidate",{payload:{filter:e,keysCleared:l,refetch:a}}),a&&await this.refetchAfterInvalidate(e)}countClearedKeys(e,t){let n=this.handlerChain.getEntries(),r=0,s=`${e}:${t}:`,a=`@${e}:${t}`;for(let o in n){let l=n[o];if(l&&typeof l=="object")for(let p of Object.keys(l))(p.startsWith(s)||p===a)&&r++}return r}async refetchAfterInvalidate(e){let{namespace:t,locale:n,key:r}=e,s=this.currentLocale();if(r){let[a,o]=r.split(":");a&&o&&await this.loadNamespaces(a,[o])}else t&&await this.loadNamespaces(n||s,[t])}};var Ie=/<\/?[0-9]+>/,Le=/<[a-z][a-z0-9]*(?:\s+[^>]*)?\/?>/i,H=class{constructor(e,t,n="en",r="en",s){c(this,"handlerChain");c(this,"currentLocale");c(this,"fallbackLocale");c(this,"defaultNamespace");c(this,"pendingTranslations",new Map);c(this,"bus");c(this,"plugins",new Map);c(this,"formatters",new Map);c(this,"processors",new Map);c(this,"eventPlugins",new Set);c(this,"markupParser",new L);c(this,"htmlSerializer",new P);c(this,"cache");this.bus=e,this.handlerChain=t,this.currentLocale=n,this.fallbackLocale=r,this.defaultNamespace=s,this.cache=new A(this.handlerChain,this.bus,()=>this.currentLocale,(a,o)=>this.loadNamespaces(a,o))}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),i.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),i.debug(`Embedded processor: ${n} from ${e.name}`)})}}t(e,...t){let[n,r]=t,s=I(e,this.currentLocale,n,r,this.defaultNamespace,this.fallbackLocale);i.debug(`Translation requested: ${s.cleanKey}`);let a=this.bus.translation(s);a.request();let o=this.handlerChain.handleSync(s);if(o&&o.status===200){let u=this.processValue(o.value,s);return i.debug(`Translation found: ${s.cleanKey} from ${o.source} (${o.duration}ms)`),a.success(u),u}this.triggerBackgroundLoad(s);let l=s.parsedDefaultValue||s.cleanKey,p=this.processValue(l,s);return i.debug(`Translation fallback: ${s.cleanKey}`),a.fallback(p),p}tHtml(e,...t){let[n,r]=t,s=I(e,this.currentLocale,n,r,this.defaultNamespace,this.fallbackLocale);i.debug(`HTML translation requested: ${s.cleanKey}`);let a=this.bus.translation(s);a.request();let o=this.handlerChain.handleSync(s);if(o&&o.status===200){let u=this.processValueAsHtml(o.value,s,o.styles);return i.debug(`HTML translation found: ${s.cleanKey} from ${o.source}`),a.success(u),u}this.triggerBackgroundLoad(s);let l=s.parsedDefaultValue||s.cleanKey,p=this.processValueAsHtml(l,s);return i.debug(`HTML translation fallback: ${s.cleanKey}`),a.fallback(p),p}processValueAsHtml(e,t,n){let r=this.processTranslationValue(e,t);if(this.containsIndexedTags(r)){let s=n||this.getStylesFromNamespace(t),a={text:r,styles:s};return this.htmlSerializer.serialize(a)}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 Ie.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=E(n,e.cleanKey);return r&&typeof r=="object"&&"styles"in r?r.styles:{}}catch(t){return i.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 i.warn(`ContentUnit processing failed for "${e}":`,n),this.processTranslationValue(e,t)}}processTranslationValue(e,t,n,r){let s,a,o;if(t&&"cleanKey"in t){let p=t;s=p.parsedParams,a=p.locale,o=p.cleanKey}else s=t,a=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,a,o)),this.processors.size>0)for(let[p,u]of this.processors.entries())try{l=u(l,s,o)}catch(g){i.warn(`Processor ${p} failed:`,g)}return l}catch(p){return i.warn(`Translation processing failed for "${e}":`,p),e}}getContentUnit(e,t,n){let r=I(e,this.currentLocale,t,n,this.defaultNamespace,this.fallbackLocale),s=this.handlerChain.handleSync(r),a=s&&s.status===200?s.value:r.parsedDefaultValue||r.cleanKey;return(!s||s.status!==200)&&this.triggerBackgroundLoad(r),this.markupParser.parse(a)}processContentText(e,t){return this.processTranslationValue(e,t,this.currentLocale)}containsHtml(e){return Le.test(e)}applyStructuralFormatters(e,t,n){let r=e,s=o=>typeof o?.count=="number",a=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){i.warn("Plural formatting failed:",l)}}if(this.formatters.has("context")&&a(t)){let o=this.formatters.get("context");try{let l=o(r,t,this.currentLocale,n);if(l!==String(r))return l}catch(l){i.warn("Context formatting failed:",l)}}return String(r)}triggerBackgroundLoad(e){i.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?i.debug(`Cached: ${e.cleanKey} = "${r.value}"`):i.debug(`Not found: ${e.cleanKey}`)}).catch(r=>{i.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=I(e,this.currentLocale,void 0,void 0,this.defaultNamespace,this.fallbackLocale);return this.handlerChain.isCached(t)}getHandlerChainInfo(){return this.handlerChain.getChainInfo()}async changeLanguage(e,t){let n=this.currentLocale;if(n===e){i.debug(`Language already set to ${e}`);return}let r=t?.clear||!1,s=this.bus.language(n,e);try{i.info(`Language change: ${n} \u2192 ${e}`),i.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(),i.info(`Language changed: ${e}`)}catch(a){throw i.error("Language change failed:",a),s.error(a),a}}async clearCache(){this.handlerChain.clearCache(),i.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&&i.debug(`Cleared ${t} pending translations for ${e}`)}async loadNamespaces(e,t){i.debug(`Preloading ${t.length} namespaces for ${e}`);let n=t.map(async r=>{try{await this.handlerChain.loadNamespace?.(e,r),i.debug(`Preloaded: ${e}:${r}`)}catch(s){i.warn(`Failed to preload ${e}:${r}:`,s)}});await Promise.allSettled(n)}async reloadNamespace(e,t){let n=t||this.currentLocale;i.debug(`Reloading namespace: ${n}:${e}`),await this.cache.invalidate({namespace:e,locale:n,refetch:!0}),i.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 fe=6e4,D=class{constructor(e,t,n){c(this,"queue",new Map);c(this,"debounceTimer",null);c(this,"repository");c(this,"config");c(this,"eventEmitter");c(this,"recentlySynced",new Map);this.repository=e,this.config=t,this.eventEmitter=n??null,t.enabled?i.debug(`MissingTranslationQueue: debounce=${t.debounceMs}ms, batchSize=${t.batchSize}`):i.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<fe){i.debug(`Skipping recently synced key: ${t}`);return}if(this.queue.set(t,e),i.debug(`Missing translation queued: ${t} (queue size: ${this.queue.size})`),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.queue.size>=this.config.batchSize){i.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>=fe&&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),i.debug(`Flushing ${n} missing translations`),this.syncBatch(t).catch(r=>{i.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(a=>({key:a.key,value:{text:a.value,styles:a.styles??{}}}));await this.repository.setBatchContentUnits(s),i.debug(`Synced ${e.length} missing translations (ContentUnit)`)}else if("setBatch"in this.repository){let s=e.map(a=>({key:a.key,value:a.value}));await this.repository.setBatch(s),i.debug(`Synced ${e.length} missing translations`)}else i.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 i.error("Batch sync failed:",t),t}}async syncIndividually(e){let t=e.map(async n=>{try{await this.repository.set(n.key,n.value),i.debug(`Synced: ${n.key}`)}catch(r){i.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(),i.debug("MissingTranslationQueue destroyed")}};var Z=class d{constructor(e){c(this,"config");c(this,"plugins",[]);c(this,"syncStorageRepos",[]);c(this,"asyncStorageRepos",[]);c(this,"networkRepos",[]);c(this,"syncQueue",null);this.config={defaultLocale:e.defaultLocale||"en",fallbackLocale:e.fallbackLocale||"en",namespace:e.namespace||"app"}}static init(e={}){return new d(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}async build(){let e=new U,t=e.builder();i.info("Builder started"),i.debug("Builder config",this.config),t.buildStart(this.config.defaultLocale,this.config.namespace);let n=new O(e);for(let o of this.syncStorageRepos){if(!o.getConfig().enabled)continue;let l=new J(e,o);t.use("sync"),n.addSyncHandler(l)}for(let o of this.asyncStorageRepos){if(!o.getConfig().enabled)continue;let l=new Q(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 X(e,o);r||(r=l),t.use("network"),n.addAsyncHandler(l);let p=o.getConfig();p.options?.syncMissing?.enabled&&(this.syncQueue=new D(o,{enabled:p.options.syncMissing.enabled,debounceMs:p.options.syncMissing.debounceMs||500,batchSize:p.options.syncMissing.batchSize||50},e),e.on("translation:not-found",u=>{this.syncQueue&&this.syncQueue.add({key:u.payload.key,fallbackValue:u.payload.fallbackValue,styles:u.payload.styles,locale:u.payload.locale,namespace:u.payload.namespace})}),i.info("Missing translation sync enabled"),i.debug("Sync queue config",p.options.syncMissing))}i.debug("Handler chain constructed");let s=new H(e,n,this.config.defaultLocale,this.config.fallbackLocale,this.config.namespace);for(let o of this.plugins)t.use("plugin"),await o.initialize({core:s,bus:e}),s.registerPlugin(o),i.info(`Plugin initialized: ${o.name}`),i.debug(`Plugin version: ${o.version}`,o.capabilities);let a=n.getChainInfo();return r&&await this.executePreloading(r,n),i.info("Builder completed"),t.buildDone(a.handlers.map(o=>o.name),this.plugins.map(o=>o.name)),s}async executePreloading(e,t){let n=e.getPreload().filter(s=>s.eager!==!1);if(!n||n.length===0)return;i.info(`Preloading ${n.length} namespaces`),i.debug("Preload targets",{namespaces:n.map(s=>`${s.locale}:${s.namespace}`)});let r=n.map(async s=>{try{let a=await e.loadNamespace(s.locale,s.namespace);if(a&&a.data&&a.status===200){let o={locale:s.locale,namespace:s.namespace,fallbackLocale:this.config.fallbackLocale};await t.saveNamespaceToHandlers(a.data,o),i.debug(`Preloaded: ${s.locale}:${s.namespace}`)}}catch(a){i.warn(`Preload failed: ${s.locale}:${s.namespace}`,a)}});await Promise.allSettled(r),i.info("Preloading completed")}};var F=class F{constructor(e={}){c(this,"name","NetworkRepository");c(this,"type","network");c(this,"config",{});c(this,"namespaceVersions",new Map);c(this,"DEFAULT_ENDPOINTS",{getTranslation:"/api/integrations/translations/:key",getNamespace:"/api/integrations/translations/:locale/:namespace",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 i.debug("API base URL is not set"),new R("API base URL is not set");let t=this.buildUrl("getTranslation",{key:e});i.debug(`API GET: ${t}`);try{let n=await this.makeRequest(t,"GET");n.ok||this.handleHttpError(n,e);let r=await n.json();i.debug("API response data:",r);let s=r.translations[r.meta?.key]||r.translations[e]||Object.values(r.translations)[0];if(i.debug(`Fetched translation for key "${e}":`,s),!s)throw new h(e);return typeof s=="object"&&"text"in s?(i.debug(`ContentUnit text: "${s.text}"`),s.text):String(s)}catch(n){this.handleCaughtError(n)}}async getContentUnit(e){if(!this.config?.options?.baseUrl)throw i.debug("API base URL is not set"),new R("API base URL is not set");let t=this.buildUrl("getTranslation",{key:e});i.debug(`API GET ContentUnit: ${t}`);try{let n=await this.makeRequest(t,"GET");n.ok||this.handleHttpError(n,e);let r=await n.json();i.debug("API response data:",r);let s=r.translations[r.meta?.key]||r.translations[e]||Object.values(r.translations)[0];if(!s)throw new h(e);return typeof s=="object"&&"text"in s?(i.debug(`ContentUnit for "${e}": text="${s.text}", styles=`,s.styles),{text:s.text,styles:s.styles||{}}):(i.debug(`Plain string for "${e}": "${s}" (no styles)`),{text:String(s),styles:{}})}catch(n){this.handleCaughtError(n)}}async getNamespace(e,t){if(!this.config?.options?.baseUrl)throw i.debug("API base URL is not set"),new R("API base URL is not set");let n=this.buildUrl("getNamespace",{locale:e,namespace:t});i.debug(`API GET Namespace: ${n}`);let r=`${e}:${t}`;try{let s={},a=this.getVersion(r);a&&(s["If-None-Match"]=`W/"${a}"`);let o=await this.makeRequest(n,"GET",void 0,s);if(o.status===304)return i.debug(`Namespace ${r}: 304 Not Modified`),null;o.ok||this.handleHttpError(o,r);let l=await o.json();if(i.debug("API response data:",l),!l.translations)throw new h(r);let p=l.meta?.version!=null?String(l.meta.version):null;return p&&this.setVersion(r,p),l.translations}catch(s){this.handleCaughtError(s)}}async set(e,t){if(!this.config?.options?.baseUrl)return i.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 i.debug(`API set failed for key "${e}":`,n),n}}async setNamespace(e,t,n){if(!this.config?.options?.baseUrl)return i.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 i.debug(`API setNamespace failed for ${e}:${t}:`,r),r}}async setBatch(e){if(!this.config?.options?.baseUrl)return i.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("setBatch");i.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}`);i.debug(`Batch sync successful: ${e.length} items`)}catch(t){throw i.debug(`API setBatch failed for ${e.length} items:`,t),t}}async getNamespaceContentUnits(e,t){if(!this.config?.options?.baseUrl)throw i.debug("API base URL is not set"),new R("API base URL is not set");let n=this.buildUrl("getNamespace",{locale:e,namespace:t});i.debug(`API GET Namespace ContentUnits: ${n}`);let r=`${e}:${t}`;try{let s={},a=this.getVersion(r);a&&(s["If-None-Match"]=`W/"${a}"`);let o=await this.makeRequest(n,"GET",void 0,s);if(o.status===304)return i.debug(`Namespace ContentUnits ${r}: 304 Not Modified`),null;o.ok||this.handleHttpError(o,r);let l=await o.json();if(i.debug("API response data:",l),!l.translations)throw new h(r);let p=l.meta?.version!=null?String(l.meta.version):null;return p&&this.setVersion(r,p),l.translations}catch(s){this.handleCaughtError(s)}}async setContentUnit(e,t){if(!this.config?.options?.baseUrl)return i.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}`);i.debug(`Saved ContentUnit for key "${e}"`)}catch(n){throw i.debug(`API setContentUnit failed for key "${e}":`,n),n}}async setBatchContentUnits(e){if(!this.config?.options?.baseUrl)return i.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("setBatch");i.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}`);i.debug(`Batch ContentUnit sync successful: ${e.length} items`)}catch(t){throw i.debug(`API setBatchContentUnits failed for ${e.length} items:`,t),t}}async remove(e){if(!this.config?.options?.baseUrl)return i.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 i.debug(`API remove failed for key "${e}":`,t),t}}async clear(){if(!this.config?.options?.baseUrl)return i.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 i.debug("API clear failed:",e),e}}getConfig(){return this.config}getVersion(e){let t=this.namespaceVersions.get(e);if(t)return t;try{let n=localStorage.getItem(F.VERSION_PREFIX+e);if(n)return this.namespaceVersions.set(e,n),n}catch{}}setVersion(e,t){this.namespaceVersions.set(e,t);try{localStorage.setItem(F.VERSION_PREFIX+e,t)}catch{}}handleHttpError(e,t){if(i.debug(`API response: ${e.status} ${e.statusText}`),e.status===404)throw new h(t);if(e.status===423){let n=e.headers.get("Retry-After");throw new x(t,n?parseInt(n,10)*1e3:void 0)}throw e.status>=500&&e.status<600?new $(t,e.status):new R(`HTTP ${e.status}: ${e.statusText}`)}handleCaughtError(e){throw e instanceof h||e instanceof x||e instanceof $||e instanceof R?e:new R("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[a,o]of Object.entries(t)){let l=new RegExp(`:${a}`,"g");s=s.replace(l,encodeURIComponent(o))}return`${n}${s}`}async makeRequest(e,t,n,r){let s=new AbortController,a=this.config.options?.timeout??1e4,o=setTimeout(()=>s.abort(),a);try{let l={"Content-Type":"application/json",...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)}}};c(F,"VERSION_PREFIX","lionrapid:v:");var q=F;var ee=class{constructor(e){c(this,"name","MemoryRepository");c(this,"type","memory");c(this,"config",{});c(this,"cache",new Map);c(this,"accessOrder",new Map);c(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 _=class{validate(e){let t=[],n=[];return this.validateTagBalance(e.text,t),this.validateStyleReferences(e.text,e.styles,t,n),this.validateICUBraces(e.text,t),{valid:t.length===0,errors:t,warnings:n}}validateTagBalance(e,t){let n=/<(\/?)?(\d+)(\/)?>/g,r=[],s;for(;(s=n.exec(e))!==null;){let[,a,o,l]=s;if(!l)if(a)if(r.length===0)t.push({code:"UNBALANCED_TAGS",message:`Closing tag </${o}> has no matching opening tag`,path:`text[${s.index}]`});else{let p=r[r.length-1];if(p.index===o)r.pop();else{let u=r.findIndex(g=>g.index===o);u>=0?(t.push({code:"UNBALANCED_TAGS",message:`Improperly nested: </${o}> should close before </${p.index}>`,path:`text[${s.index}]`}),r.splice(u,1)):t.push({code:"UNBALANCED_TAGS",message:`Closing tag </${o}> has no matching opening tag`,path:`text[${s.index}]`})}}else r.push({index:o,position:s.index})}for(let{index:a}of r)t.push({code:"UNBALANCED_TAGS",message:`Opening tag <${a}> has no matching closing tag`,path:"text"})}validateStyleReferences(e,t,n,r){let s=new Set,a=/<\/?(\d+)(?:\/)?>/g,o;for(;(o=a.exec(e))!==null;)s.add(o[1]);for(let l of s)(!t[l]||t[l].length===0)&&r.push({code:"EMPTY_STYLE",message:`Tag <${l}> has no style definition, will render as <span>`});for(let l of Object.keys(t))s.has(l)||r.push({code:"UNUSED_TAG",message:`Style for tag <${l}> is defined but tag is not used in text`})}validateICUBraces(e,t){let n=0,r=!1,s="";for(let o=0;o<e.length;o++){let l=e[o],p=o>0?e[o-1]:"";if((l==='"'||l==="'")&&p!=="\\"){r?l===s&&(r=!1,s=""):(r=!0,s=l);continue}r||(l==="{"?n++:l==="}"&&(n--,n<0&&(t.push({code:"INVALID_ICU",message:`Unbalanced ICU braces: unexpected '}' at position ${o}`,path:`text[${o}]`}),n=0)))}n>0&&t.push({code:"INVALID_ICU",message:`Unbalanced ICU braces: ${n} unclosed '{'`,path:"text"}),/\{\s*[,}]/.test(e)&&t.push({code:"INVALID_ICU",message:"ICU variable name is empty or missing",path:"text"})}};var oe="lionrapid:",j=`${oe}version`,be="1",te=class{constructor(e={}){c(this,"name","LocalStorageRepository");c(this,"type","memory");c(this,"config");c(this,"available");c(this,"prefix");c(this,"defaultTTL");c(this,"maxSize");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{prefix:e.options?.prefix??oe,ttl:e.options?.ttl??1440*60*1e3,maxSize:e.options?.maxSize??500,...e.options}},this.prefix=this.config.options?.prefix??oe,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(j)!==be&&(this.clear(),window.localStorage.setItem(j,be))}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!==j&&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 a=0;a<window.localStorage.length;a++){let o=window.localStorage.key(a);if(!o?.startsWith(this.prefix))continue;let l=o.slice(this.prefix.length);(l===n||l.startsWith(r))&&s.push(o)}s.forEach(a=>window.localStorage.removeItem(a))}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===j)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!==j&&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===j))try{let s=window.localStorage.getItem(r);if(s){let a=JSON.parse(s);e.push({key:r,timestamp:a.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 ve="lionrapid-v1",T="lionrapid:",ne=class{constructor(e={}){c(this,"name","CacheStorageRepository");c(this,"type","storage");c(this,"config");c(this,"cacheName");c(this,"defaultTTL");c(this,"available");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{cacheName:e.options?.cacheName??ve,ttl:e.options?.ttl??10080*60*1e3,...e.options}},this.cacheName=this.config.options?.cacheName??ve,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 h(e);try{let t=await caches.open(this.cacheName),n=await t.match(T+e);if(!n)throw new h(e);let r=await n.json();if(r.expiry!==null&&Date.now()>r.expiry)throw await t.delete(T+e),new h(e);return r.value}catch(t){throw t instanceof h?t:new h(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(T+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(T+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(T)).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),a=await s.keys();await Promise.all(a.filter(o=>{let l=o.url,p=l.includes(T)?l.substring(l.indexOf(T)+T.length):"";return p===n||p.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 h(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(T))continue;let a=s.substring(s.indexOf(T)+T.length);try{let o=await this.get(a);e[a]=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(T)).length,cacheName:this.cacheName}}catch{return{size:0,cacheName:this.cacheName}}}};var Pe="1.0.0";return ke(Ae);})();
|
|
1
|
+
"use strict";var LionRapid=(()=>{var G=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var Te=Object.prototype.hasOwnProperty;var Ee=(d,e,t)=>e in d?G(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t;var ke=(d,e)=>{for(var t in e)G(d,t,{get:e[t],enumerable:!0})},Se=(d,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xe(e))!Te.call(d,r)&&r!==t&&G(d,r,{get:()=>e[r],enumerable:!(n=Re(e,r))||n.enumerable});return d};var Ne=d=>Se(G({},"__esModule",{value:!0}),d);var c=(d,e,t)=>Ee(d,typeof e!="symbol"?e+"":e,t);var Oe={};ke(Oe,{CacheManager:()=>A,CacheStorageRepository:()=>re,Colors:()=>m,ContentValidator:()=>W,DefaultStyleMapper:()=>S,EventEmitter:()=>U,HTMLSerializer:()=>P,HandlerChain:()=>H,LionRapidBuilder:()=>q,LionRapidCore:()=>O,LocalStorageRepository:()=>ne,LogLevel:()=>V,Logger:()=>pe,MarkupParser:()=>L,MemoryRepository:()=>te,MissingTranslationQueue:()=>D,NetworkError:()=>w,NetworkRepository:()=>ee,ServerError:()=>$,TranslationError:()=>N,TranslationLockedError:()=>x,TranslationNotFoundError:()=>h,VERSION:()=>He,createPackageLogger:()=>ue,isClientError:()=>ye,isRetryableError:()=>X,isTranslationError:()=>fe,logger:()=>i,measure:()=>ge,parseKeyPath:()=>oe,prepareTranslationRequest:()=>I,resolveNestedKey:()=>E});var V=(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))(V||{});var M=typeof process<"u"&&process.env?process.env:{},z=M.NODE_ENV==="production",K=M.NODE_ENV==="development",ce=M.CI==="true",$e=M.LIONRAPID_DEV==="true",Ie=M.LIONRAPID_PERFORMANCE_TRACKING==="true";function Le(){try{if(typeof localStorage<"u"){let d=localStorage.getItem("LIONRAPID_LOG_LEVEL");if(d&&typeof d=="string")return d}}catch{}return null}var de=Le()||M.LOG_LEVEL||"WARN",m={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"},B=class d{constructor(e={}){c(this,"config");this.config={level:this.getLogLevelFromEnv(),enabled:this.shouldEnableLogging(),prefix:`${e.packageEmoji||"\u{1F4E6}"} ${e.packageName||"LionRapid"}`,showLineNumbers:$e&&!ce,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(!Ie||z)return()=>{};let t=K?performance.now():0;return()=>{if(K){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=V[e],s=this.getLevelEmoji(e),a=this.config.showLineNumbers?this.getCallSite():null,o=this.buildColoredMessage(e,s,r,t,a,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,a){if(!this.config.useColors){let R=s?` (${s.fileName}:${s.lineNumber})`:"",k=`${this.config.prefix} ${t} ${n} ${r}${R}`;return a!==void 0&&(k+=` ${JSON.stringify(a)}`),k}let o=this.getLevelColor(e),l=m.RESET,p=`${m.BOLD}${m.ORANGE}${this.config.prefix}${l}`,u=t,g=`${o}${m.BOLD}${n}${l}`,f=`${o}${r}${l}`,y=s?`${m.DIM}${m.BRIGHT_BLACK} (${s.fileName}:${s.lineNumber})${l}`:"",b=a!==void 0?`${m.DIM}${m.CYAN} ${JSON.stringify(a)}${l}`:"";return`${p} ${u} ${g} ${f}${y}${b}`}getLevelColor(e){switch(e){case 0:return m.BRIGHT_GREEN;case 1:return m.BRIGHT_CYAN;case 2:return m.BRIGHT_YELLOW;case 3:return m.BRIGHT_RED;default:return m.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(`
|
|
2
|
+
`);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?`${m[t]}${e}${m.RESET}`:e}getColors(){return m}createPackageLogger(e,t){return new d({...this.config,packageName:e,packageEmoji:t||"\u{1F4E6}"})}getLogLevelFromEnv(){switch(de.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 de!=="NONE"}shouldUseColors(){return ce?!1:typeof window<"u"?!0:(typeof process<"u",K)}},C=()=>{},ie=()=>()=>{},i=z?{configure:C,debug:C,info:C,warn:(d,e)=>{console.warn(`\u{1F981} LionRapid Core \u26A0\uFE0F ${d}`,e||"")},error:(d,e)=>{console.error(`\u{1F981} LionRapid Core \u274C ${d}`,e||"")},time:ie,colorize:d=>d,getColors:()=>m,createPackageLogger:(d,e)=>({configure:C,debug:C,info:C,warn:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${d}`;console.warn(`${r} \u26A0\uFE0F ${t}`,n||"")},error:(t,n)=>{let r=`${e||"\u{1F4E6}"} ${d}`;console.error(`${r} \u274C ${t}`,n||"")},time:ie,colorize:t=>t,getColors:()=>m,createPackageLogger:C})}:new B({packageName:"LionRapid Core",packageEmoji:"\u{1F981}"}),pe=z?function(){return i}:B,ue=d=>{if(z){let e=`${d.packageEmoji||"\u{1F4E6}"} ${d.packageName||"LionRapid"}`;return{configure:C,debug:C,info:C,warn:(t,n)=>{console.warn(`${e} \u26A0\uFE0F ${t}`,n||"")},error:(t,n)=>{console.error(`${e} \u274C ${t}`,n||"")},time:ie,colorize:t=>t,getColors:()=>m,createPackageLogger:C}}return new B(d)},ge=d=>{if(z)return{start:C,end:C,elapsed:()=>0};let e;return{start:()=>{K&&(e=performance.now(),i.debug(`\u23F1\uFE0F ${d} - started`))},end:()=>{if(K){let t=performance.now()-e;return i.debug(`\u23F1\uFE0F ${d} - completed in ${t.toFixed(2)}ms`),t}return 0},elapsed:()=>K?performance.now()-e:0}};var U=class{constructor(){c(this,"eventListeners",new Map);c(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,a,o)=>{this.emit("translation:missing",{context:this.createContext(e.id,[...n,"missing"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:o}})},notFound:(s,a,o)=>{this.emit("translation:not-found",{context:this.createContext(e.id,[...n,"not-found"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,namespace:o,status:404}})},locked:(s,a,o)=>{this.emit("translation:locked",{context:this.createContext(e.id,[...n,"locked"]),payload:{key:e.cleanKey,fallbackValue:s,locale:a,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,a=typeof e=="string"?e:e.cleanKey;this.emit("repo:set:success",{context:this.createContext(s,[...n,"set","success"]),payload:{key:a,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:a=>{this.emit("network:request:success",{context:this.createContext(r,[...s,"success"]),payload:{key:n,value:a,method:t||"GET"}})},error:(a,o)=>{this.emit("network:request:error",{context:this.createContext(r,[...s,"error"]),payload:{key:n,method:t||"GET",error:a,...o&&{status:o}}})},retry:(a,o,l)=>{this.emit("network:retry",{context:this.createContext(r,[...s,"retry"]),payload:{key:n,attempt:a,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}})},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:()=>{i.debug(`\u{1F9F9} Cache ${e} starting: ${t}`)},complete:()=>{i.debug(`\u2705 Cache ${e} complete: ${n?.clearedCount||0} entries`)}}:{start:()=>{},complete:()=>{}}}};var H=class{constructor(e){c(this,"asyncHandlers",[]);c(this,"syncHandlers",[]);c(this,"bus");this.bus=e}addSyncHandler(e){e.enabled&&(this.syncHandlers.push(e),this.sortHandlersIfNeeded(this.syncHandlers),i.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 i.debug(`Sync hit: ${t.name} (${n.duration}ms)`),n}catch(n){i.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&&(i.debug(`Saving to ${r.length} memory handlers`),r.forEach(s=>{try{s.save(e,t),i.debug(`Saved to memory: ${s.name}`)}catch(a){i.warn(`Failed to save to memory ${s.name}:`,a),this.bus.repo(e,s.name).error(a)}}))}saveNamespaceToMemoryHandlers(e,t){let n=this.syncHandlers.filter(r=>r.type==="memory"&&r.saveNamespace);n.length!==0&&(i.debug(`Saving namespace to ${n.length} memory handlers`),n.forEach(r=>{try{r.saveNamespace(e,t),i.debug(`Namespace saved to memory: ${r.name}`,{locale:t.locale,namespace:t.namespace})}catch(s){i.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),i.debug(`Async handler added: ${e.name}`))}async handleAsync(e){for(let t of this.asyncHandlers)try{i.debug(`Trying handler: ${t.name}`);let n=await t.lookup(e);if(n.value&&n.status===200)return i.debug(`Async hit: ${t.name} (${n.duration}ms)`),n.namespaceLoaded?(i.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);i.debug(`Handler ${t.name} returned fallback (status: ${n.status})`)}catch(n){i.warn(`Handler ${t.name} failed:`,n),this.bus.repo(e,t.name).error(n);continue}return i.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;i.debug(`Saving to ${s.length} storage handlers`);let a=s.map(async o=>{try{await o.save(e,t),i.debug(`Saved to storage: ${o.name}`)}catch(l){i.warn(`Failed to save to storage ${o.name}:`,l),this.bus.repo(e,o.name).error(l)}});await Promise.allSettled(a)}async saveNamespaceToStorageHandlers(e,t){let n=this.asyncHandlers.filter(s=>s.type==="storage"&&s.saveNamespace);if(n.length===0)return;i.debug(`Saving namespace to ${n.length} storage handlers`);let r=n.map(async s=>{try{await s.saveNamespace(e,t),i.debug(`Namespace saved to storage: ${s.name}`,{locale:t.locale,namespace:t.namespace})}catch(a){i.warn(`Failed to save namespace to storage ${s.name}:`,a),this.bus.repo(`${t.locale}:${t.namespace}`,s.name).error(a)}});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?.(),i.debug(`Handler destroyed: ${n.name}`)}catch(r){i.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,a=r.priority||Number.MAX_SAFE_INTEGER;return s-a})}async loadNamespace(e,t){for(let n of this.asyncHandlers)if(n.type==="network")try{i.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 i.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){i.warn(`Failed to load namespace: ${e}:${t} from ${n.name}`,r),this.bus.repo(`${e}:${t}`,n.name).error(r);continue}return i.debug(`No handlers found namespace: ${e}:${t}`),null}clearCache(){let e=[...this.syncHandlers,...this.asyncHandlers];for(let t of e)try{t.destroy?.(),i.debug(`Cache cleared for handler: ${t.name}`)}catch(n){i.warn(`Failed to clear cache for handler: ${t.name}`,n)}i.debug("Cache cleared for all handlers")}clearNamespace(e,t){for(let n of this.syncHandlers)try{n.clearNamespace?.(e,t)}catch(r){i.warn(`Failed to clear namespace for handler: ${n.name}`,r)}i.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){i.warn(`Failed to set cache in handler: ${r.name}`,s)}i.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){i.debug(`Error getting namespace data from ${t.name}:`,n)}return null}};function he(d){let e=d.indexOf(":");if(e>0&&e<d.length-1){let t=d.substring(0,e),n=d.substring(e+1);return{originalKey:d,namespace:t,cleanKey:n,hasExplicitNamespace:!0}}return{originalKey:d,cleanKey:d,hasExplicitNamespace:!1}}function me(d,e,t,n){let r=d.hasExplicitNamespace?d.namespace:t;return{locale:e,namespace:r,fallbackLocale:n||e}}function E(d,e){if(!(!d||!e)){if(!e.includes(".")&&!e.includes("["))return d[e];try{let t=oe(e),n=d;for(let r of t){if(n==null){i.debug(`\u{1F50D} Nested key resolution stopped at null/undefined for: ${e}`);return}if(typeof r=="number"){if(!Array.isArray(n)){i.debug(`\u{1F50D} Expected array for index ${r} in path: ${e}`);return}n=n[r]}else{if(typeof n!="object"){i.debug(`\u{1F50D} Expected object for key '${r}' in path: ${e}`);return}n=n[r]}}return i.debug(`\u{1F50D} Nested key resolved: ${e} \u2192 ${typeof n=="object"?"[Object]":n}`),n}catch(t){i.debug(`\u{1F50D} Nested key resolution error for '${e}':`,t);return}}}function oe(d){let e=[],t="",n=!1;for(let r=0;r<d.length;r++){let s=d[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 a=parseInt(t,10);isNaN(a)?e.push(t):e.push(a),t=""}n=!1}else t+=s}return t&&e.push(t),e}function J(d,e,t){let n=[d];return e&&n.push(e),n.push(t),n.join(":")}function v(d,e){return`@${d}:${e}`}function F(d,e="",t,n){let r={};for(let[s,a]of Object.entries(d)){let o=e?`${e}.${s}`:s,l=J(t,n,o);typeof a=="object"&&a!==null&&"text"in a&&"styles"in a?r[l]=JSON.stringify(a):typeof a=="object"&&a!==null?Object.assign(r,F(a,o,t,n)):r[l]=JSON.stringify({text:String(a),styles:{}})}return r}function I(d,e,t,n,r,s){let a=performance.now(),{defaultValue:o,params:l}=Pe(t,n),p=he(d),u=me(p,e,r,s),g=J(u.locale,u.namespace,p.cleanKey),f=u.namespace?v(u.locale,u.namespace):void 0;return{id:`${g}-${a}`,originalKey:d,originalParams:t,originalDefaultValue:n,cleanKey:p.cleanKey,hasExplicitNamespace:p.hasExplicitNamespace,parsedParams:l,parsedDefaultValue:o,locale:e,namespace:u.namespace,fallbackLocale:s,individualCacheKey:g,namespaceCacheKey:f,startTime:a}}function Pe(d,e){let t,n;return typeof d=="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 d=="string"?(t=d,typeof e=="object"&&(n=e)):typeof d=="object"&&(n=d,typeof e=="string"&&(t=e)),{defaultValue:t,params:n}}var Q=class{constructor(e,t){c(this,"name");c(this,"version","1.0.0");c(this,"priority");c(this,"type","memory");c(this,"enabled");c(this,"ttlMap",new Map);c(this,"ttl");c(this,"repository");c(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();i.debug(`Sync lookup: ${e.cleanKey}`);let n=this.bus.repo(e,this.name);n.getStart();let r=this.tryDirectLookup(e);if(r!==null)return i.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 i.debug(`Namespace hit: ${e.cleanKey}`),n.getSuccess(s.text),this.createResult(s,"memory",200,t,!0)}return i.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)),i.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=v(t.locale,t.namespace);this.setWithTTL(r,JSON.stringify(e));let s=F(e,"",t.locale,t.namespace);for(let[a,o]of Object.entries(s))this.setWithTTL(a,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=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=E(r,e.cleanKey);if(s!=null){let a;return typeof s=="object"&&s!==null&&"text"in s?a={text:String(s.text),styles:s.styles||{}}:a={text:String(s),styles:{}},this.setWithTTL(e.individualCacheKey,JSON.stringify(a)),i.debug(`Cached from namespace: ${e.cleanKey}`),a}}catch(r){i.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),i.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,a=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:a}}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 a of Object.keys(s))a.startsWith(r)&&(this.repository.remove(a),this.ttlMap.delete(a));i.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)),i.debug(`Direct cache set: ${e}`)}};var Y=class{constructor(e,t){c(this,"name");c(this,"version","1.0.0");c(this,"priority");c(this,"type","storage");c(this,"enabled");c(this,"ttlMap",new Map);c(this,"ttl");c(this,"repository");c(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();i.debug(`Async lookup: ${e.cleanKey}`);let n=this.bus.repo(e,this.name),r=await this.tryDirectLookup(e);if(r!==null)return i.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 i.debug(`Namespace hit: ${e.cleanKey}`),n.getSuccess(s.text),this.createResult(s,"storage",200,t,!0)}return i.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)),i.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;i.debug(`Saving namespace: ${t.locale}:${t.namespace} (${r} keys)`);let s=v(t.locale,t.namespace);await this.setWithTTL(s,JSON.stringify(e));let a=F(e,"",t.locale,t.namespace),o=0;for(let[l,p]of Object.entries(a))await this.setWithTTL(l,p),o++;i.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=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=E(r,e.cleanKey);if(s!=null){let a;return typeof s=="object"&&s!==null&&"text"in s?a={text:String(s.text),styles:s.styles||{}}:a={text:String(s),styles:{}},await this.setWithTTL(e.individualCacheKey,JSON.stringify(a)),i.debug(`Cached from namespace: ${e.cleanKey}`),a}}catch(r){i.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),i.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,a=Math.max(0,this.ttl-s);e[n]={timestamp:r,age:s,remaining:a}}return e}async destroy(){await this.repository.clear(),this.ttlMap.clear()}getEntries(){if(this.repository.getEntries!==void 0)return this.repository.getEntries()}};var N=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)}},h=class extends N{constructor(e){super(e,404,`Translation not found: ${e}`)}},x=class extends N{constructor(t,n){super(t,423,`Translation locked: ${t}`);this.retryAfter=n}},$=class extends N{constructor(e,t){super(e,t,`Server error ${t}: ${e}`)}},w=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="NetworkError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}};function fe(d){return d instanceof N}function X(d){return d instanceof $||d instanceof w}function ye(d){return d instanceof h||d instanceof x}var Z=class{constructor(e,t){c(this,"repository");c(this,"name");c(this,"priority");c(this,"version","1.0.0");c(this,"type","network");c(this,"enabled");c(this,"bus");c(this,"retryCount");c(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(),i.debug(`Network lookup: ${e.cleanKey}`);try{let s=await this.lookupContentUnitWithRetry(e.individualCacheKey);return i.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 h&&e.namespace?(i.debug(`Individual key not found, trying namespace: ${e.cleanKey}`),this.lookupFromNamespace(e,n,t,r)):s instanceof x?(i.debug(`Translation locked (423): ${e.cleanKey}`),this.handleTranslationLocked(e,n,s,t,r)):(i.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=E(s.data,e.cleanKey);if(o!=null){let l,p={};if(typeof o=="object"&&o!==null&&"text"in o){let u=o;l=String(u.text),p=u.styles||{}}else l=String(o);return i.debug(`Network namespace hit: ${e.cleanKey}, hasStyles=${Object.keys(p).length>0}`),r.success(l),this.createTranslationResult(l,"network",200,n,void 0,!1,{locale:e.locale,namespace:e.namespace,data:s.data},p)}}let a=new h(e.cleanKey);return this.handleTranslationNotFound(e,t,a,n)}catch(s){return i.debug(`Namespace load failed: ${e.cleanKey}`,s),s instanceof h?this.handleTranslationNotFound(e,t,s,n):s instanceof x?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?(i.debug(`Network namespace not modified: ${e}:${t}`),this.createNamespaceResult(null,"network",304,n)):(i.debug(`Network namespace loaded: ${e}:${t}`),this.createNamespaceResult(r,"network",200,n))}catch(r){return r instanceof x?(i.debug(`Namespace locked (423): ${e}:${t}`),this.createNamespaceResult(null,"fallback",423,n,r)):r instanceof h?(i.debug(`Network namespace not found: ${e}:${t}`),this.createNamespaceResult(null,"fallback",404,n,r)):(i.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(a){if(r<=this.retryCount&&X(a)){let o=this.calculateBackoff(r);return s.retry(r,o,a.message),await this.delay(o),i.debug(`Retrying ${n} (${r}/${this.retryCount}) after ${o}ms`),this.withRetry(e,t,n,r+1)}throw a}}handleTranslationNotFound(e,t,n,r){return i.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,a,o,l){return{value:e,source:t,status:n,duration:Date.now()-r,...s&&{error:s},...a!==void 0&&{cached:a},...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||[]}};var Ae=/^[a-z][a-z0-9+.-]*:/i,Ke=new Set(["http:","https:","mailto:","tel:","sms:"]);function be(d){if(!d)return"#";let e=d.trim();if(!e||e.startsWith("//"))return"#";if(e.startsWith("/")||e.startsWith("?")||e.startsWith("#")||e.startsWith("./")||e.startsWith("../"))return e;let t=Ae.exec(e);if(t){let n=t[0].toLowerCase();return Ke.has(n)?e:"#"}return e}var S=class{constructor(){c(this,"elementToStyles",{b:"bold",strong:"bold",i:"italic",em:"italic",u:"underline",s:"strikethrough",del:"strikethrough",strike:"strikethrough",code:"code",mark:"highlight",sub:"subscript",sup:"superscript"});c(this,"styleToElement",{bold:"b",italic:"i",underline:"u",strikethrough:"s",code:"code",highlight:"mark",subscript:"sub",superscript:"sup",strong:"b",b:"b",em:"i",i:"i",u:"u",s:"s",del:"s",strike:"s",mark:"mark",sub:"sub",sup:"sup"})}mapElementToStyles(e,t){let n=[],r=e.toLowerCase(),s=this.elementToStyles[r];return s&&n.push(s),r==="a"&&t.href&&n.push(`hyperlink:${t.href}`),n}mapStylesToElement(e){for(let t of e)if(t.startsWith("hyperlink:"))return{element:"a",attrs:{href:be(t.slice(10))}};for(let t of e){let n=this.styleToElement[t];if(n)return{element:n,attrs:{}}}return{element:"span",attrs:{}}}};var L=class{constructor(e={}){c(this,"styleMapper");this.styleMapper=e.styleMapper??new S}parse(e){if(/<\/?[0-9]+>/.test(e))return{text:e,styles:{}};let n={},r=0,s=[],a="",o=0;for(;o<e.length;){let l=this.matchTag(e,o);if(!l){a+=e.slice(o);break}if(a+=e.slice(o,l.startIndex),l.isClosing){let p=this.findMatchingOpenTag(s,l.tag.toLowerCase());if(p!==null){a+=`</${p}>`;let u=s.findIndex(g=>g.index===p);u!==-1&&s.splice(u,1)}else a+=e.slice(l.startIndex,l.endIndex)}else if(l.isSelfClosing){r++;let p=this.styleMapper.mapElementToStyles(l.tag,l.attrs);p.length>0&&(n[String(r)]=p,a+=`<${r}/>`)}else{let p=this.styleMapper.mapElementToStyles(l.tag,l.attrs);if(p.length>0)r++,n[String(r)]=p,a+=`<${r}>`,s.push({tag:l.tag.toLowerCase(),index:r});else{let u=this.findClosingTagIndex(e,l.endIndex,l.tag);if(u!==-1){let g=e.slice(l.endIndex,u),f=this.parse(g),y=r;for(let[k,se]of Object.entries(f.styles)){let ae=String(y+parseInt(k,10));n[ae]=se}a+=f.text.replace(/<(\/?)\d+>/g,(k,se)=>{let ae=parseInt(k.replace(/[</>]/g,""),10);return`<${se}${y+ae}>`});let b=this.matchTag(e,u);o=b?b.endIndex:u;let R=Object.keys(f.styles).length>0?Math.max(...Object.keys(f.styles).map(Number)):0;r=y+R;continue}}}o=l.endIndex}for(;s.length>0;){let l=s.pop();a+=`</${l.index}>`}return{text:a,styles:n}}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*(\/?)>/,a=e.slice(n).match(r);if(!a)return n+1<e.length?this.matchTag(e,n+1):null;let[o,l,p,u,g]=a;return{tag:p,attrs:this.parseAttributes(u),isClosing:l==="/",isSelfClosing:g==="/",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,a,o,l]=r,p=a??o??l??"";t[s.toLowerCase()]=p}return t}findMatchingOpenTag(e,t){for(let n=e.length-1;n>=0;n--)if(e[n].tag===t)return e[n].index;return null}findClosingTagIndex(e,t,n){let r=n.toLowerCase(),s=1,a=t;for(;a<e.length&&s>0;){let o=this.matchTag(e,a);if(!o)break;if(o.tag.toLowerCase()===r)if(o.isClosing){if(s--,s===0)return o.startIndex}else o.isSelfClosing||s++;a=o.endIndex}return-1}};var P=class{constructor(e={}){c(this,"styleMapper");this.styleMapper=e.styleMapper??new S}serialize(e){let{text:t,styles:n}=e,r=/<(\/?)?(\d+)(\/)?>/g,s="",a=0,o;for(;(o=r.exec(t))!==null;){s+=t.slice(a,o.index);let[l,p,u,g]=o,y=n[u]||[];if(p){let b=this.styleMapper.mapStylesToElement(y);s+=`</${b.element}>`}else if(g){let b=this.styleMapper.mapStylesToElement(y),R=this.formatAttributes(b.attrs);s+=`<${b.element}${R} />`}else{let b=this.styleMapper.mapStylesToElement(y),R=this.formatAttributes(b.attrs);s+=`<${b.element}${R}>`}a=o.index+l.length}return s+=t.slice(a),s}formatAttributes(e){let t=Object.entries(e);return t.length===0?"":" "+t.map(([n,r])=>`${n}="${this.escapeAttributeValue(r)}"`).join(" ")}escapeAttributeValue(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}};var A=class{constructor(e,t,n,r){c(this,"handlerChain");c(this,"bus");c(this,"currentLocale");c(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 a=JSON.parse(s);return typeof a=="object"&&"text"in a?{value:String(a.text),styles:a.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,...a]=e.split(":"),o=a.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:a=!0}=e,o=this.currentLocale(),l=0;if(r){let[p,u]=r.split(":");p&&u&&(this.handlerChain.clearNamespace(p,u),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 p=this.handlerChain.getEntries(),u=new Set;for(let g in p){let f=p[g];if(f&&typeof f=="object"){for(let y of Object.keys(f))if(y.startsWith(`${n}:`)||y.startsWith(`@${n}:`)){let b=y.replace("@","").split(":");b[1]&&u.add(b[1])}}}for(let g of u)this.handlerChain.clearNamespace(n,g),l++}else if(s){let p=this.handlerChain.getEntries(),u=new Map;for(let g in p){let f=p[g];if(f&&typeof f=="object"){for(let y of Object.keys(f))if(s(y)){let b=y.replace("@","").split(":"),R=b[0],k=b[1];R&&k&&(u.has(R)||u.set(R,new Set),u.get(R).add(k),l++)}}}for(let[g,f]of u)for(let y of f)this.handlerChain.clearNamespace(g,y)}else this.handlerChain.clearCache(),l=-1;this.bus.emit("cache:invalidate",{payload:{filter:e,keysCleared:l,refetch:a}}),a&&await this.refetchAfterInvalidate(e)}countClearedKeys(e,t){let n=this.handlerChain.getEntries(),r=0,s=`${e}:${t}:`,a=`@${e}:${t}`;for(let o in n){let l=n[o];if(l&&typeof l=="object")for(let p of Object.keys(l))(p.startsWith(s)||p===a)&&r++}return r}async refetchAfterInvalidate(e){let{namespace:t,locale:n,key:r}=e,s=this.currentLocale();if(r){let[a,o]=r.split(":");a&&o&&await this.loadNamespaces(a,[o])}else t&&await this.loadNamespaces(n||s,[t])}};var Me=/<\/?[0-9]+>/,Ue=/<[a-z][a-z0-9]*(?:\s+[^>]*)?\/?>/i,O=class{constructor(e,t,n="en",r="en",s){c(this,"handlerChain");c(this,"currentLocale");c(this,"fallbackLocale");c(this,"defaultNamespace");c(this,"pendingTranslations",new Map);c(this,"bus");c(this,"plugins",new Map);c(this,"formatters",new Map);c(this,"processors",new Map);c(this,"eventPlugins",new Set);c(this,"markupParser",new L);c(this,"htmlSerializer",new P);c(this,"cache");this.bus=e,this.handlerChain=t,this.currentLocale=n,this.fallbackLocale=r,this.defaultNamespace=s,this.cache=new A(this.handlerChain,this.bus,()=>this.currentLocale,(a,o)=>this.loadNamespaces(a,o))}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),i.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),i.debug(`Embedded processor: ${n} from ${e.name}`)})}}t(e,...t){let[n,r]=t,s=I(e,this.currentLocale,n,r,this.defaultNamespace,this.fallbackLocale);i.debug(`Translation requested: ${s.cleanKey}`);let a=this.bus.translation(s);a.request();let o=this.handlerChain.handleSync(s);if(o&&o.status===200){let u=this.processValue(o.value,s);return i.debug(`Translation found: ${s.cleanKey} from ${o.source} (${o.duration}ms)`),a.success(u),u}this.triggerBackgroundLoad(s);let l=s.parsedDefaultValue||s.cleanKey,p=this.processValue(l,s);return i.debug(`Translation fallback: ${s.cleanKey}`),a.fallback(p),p}tHtml(e,...t){let[n,r]=t,s=I(e,this.currentLocale,n,r,this.defaultNamespace,this.fallbackLocale);i.debug(`HTML translation requested: ${s.cleanKey}`);let a=this.bus.translation(s);a.request();let o=this.handlerChain.handleSync(s);if(o&&o.status===200){let u=this.processValueAsHtml(o.value,s,o.styles);return i.debug(`HTML translation found: ${s.cleanKey} from ${o.source}`),a.success(u),u}this.triggerBackgroundLoad(s);let l=s.parsedDefaultValue||s.cleanKey,p=this.processValueAsHtml(l,s);return i.debug(`HTML translation fallback: ${s.cleanKey}`),a.fallback(p),p}processValueAsHtml(e,t,n){let r=this.processTranslationValue(e,t);if(this.containsIndexedTags(r)){let s=n||this.getStylesFromNamespace(t),a={text:r,styles:s};return this.htmlSerializer.serialize(a)}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 Me.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=E(n,e.cleanKey);return r&&typeof r=="object"&&"styles"in r?r.styles:{}}catch(t){return i.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 i.warn(`ContentUnit processing failed for "${e}":`,n),this.processTranslationValue(e,t)}}processTranslationValue(e,t,n,r){let s,a,o;if(t&&"cleanKey"in t){let p=t;s=p.parsedParams,a=p.locale,o=p.cleanKey}else s=t,a=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,a,o)),this.processors.size>0)for(let[p,u]of this.processors.entries())try{l=u(l,s,o)}catch(g){i.warn(`Processor ${p} failed:`,g)}return l}catch(p){return i.warn(`Translation processing failed for "${e}":`,p),e}}getContentUnit(e,t,n){let r=I(e,this.currentLocale,t,n,this.defaultNamespace,this.fallbackLocale),s=this.handlerChain.handleSync(r),a=s&&s.status===200?s.value:r.parsedDefaultValue||r.cleanKey;return(!s||s.status!==200)&&this.triggerBackgroundLoad(r),this.markupParser.parse(a)}processContentText(e,t){return this.processTranslationValue(e,t,this.currentLocale)}containsHtml(e){return Ue.test(e)}applyStructuralFormatters(e,t,n){let r=e,s=o=>typeof o?.count=="number",a=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){i.warn("Plural formatting failed:",l)}}if(this.formatters.has("context")&&a(t)){let o=this.formatters.get("context");try{let l=o(r,t,this.currentLocale,n);if(l!==String(r))return l}catch(l){i.warn("Context formatting failed:",l)}}return String(r)}triggerBackgroundLoad(e){i.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?i.debug(`Cached: ${e.cleanKey} = "${r.value}"`):i.debug(`Not found: ${e.cleanKey}`)}).catch(r=>{i.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=I(e,this.currentLocale,void 0,void 0,this.defaultNamespace,this.fallbackLocale);return this.handlerChain.isCached(t)}getHandlerChainInfo(){return this.handlerChain.getChainInfo()}async changeLanguage(e,t){let n=this.currentLocale;if(n===e){i.debug(`Language already set to ${e}`);return}let r=t?.clear||!1,s=this.bus.language(n,e);try{i.info(`Language change: ${n} \u2192 ${e}`),i.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(),i.info(`Language changed: ${e}`)}catch(a){throw i.error("Language change failed:",a),s.error(a),a}}async clearCache(){this.handlerChain.clearCache(),i.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&&i.debug(`Cleared ${t} pending translations for ${e}`)}async loadNamespaces(e,t){i.debug(`Preloading ${t.length} namespaces for ${e}`);let n=t.map(async r=>{try{await this.handlerChain.loadNamespace?.(e,r),i.debug(`Preloaded: ${e}:${r}`)}catch(s){i.warn(`Failed to preload ${e}:${r}:`,s)}});await Promise.allSettled(n)}async reloadNamespace(e,t){let n=t||this.currentLocale;i.debug(`Reloading namespace: ${n}:${e}`),await this.cache.invalidate({namespace:e,locale:n,refetch:!0}),i.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 ve=6e4,D=class{constructor(e,t,n){c(this,"queue",new Map);c(this,"debounceTimer",null);c(this,"repository");c(this,"config");c(this,"eventEmitter");c(this,"recentlySynced",new Map);this.repository=e,this.config=t,this.eventEmitter=n??null,t.enabled?i.debug(`MissingTranslationQueue: debounce=${t.debounceMs}ms, batchSize=${t.batchSize}`):i.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<ve){i.debug(`Skipping recently synced key: ${t}`);return}if(this.queue.set(t,e),i.debug(`Missing translation queued: ${t} (queue size: ${this.queue.size})`),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.queue.size>=this.config.batchSize){i.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>=ve&&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),i.debug(`Flushing ${n} missing translations`),this.syncBatch(t).catch(r=>{i.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(a=>({key:a.key,value:{text:a.value,styles:a.styles??{}}}));await this.repository.setBatchContentUnits(s),i.debug(`Synced ${e.length} missing translations (ContentUnit)`)}else if("setBatch"in this.repository){let s=e.map(a=>({key:a.key,value:a.value}));await this.repository.setBatch(s),i.debug(`Synced ${e.length} missing translations`)}else i.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 i.error("Batch sync failed:",t),t}}async syncIndividually(e){let t=e.map(async n=>{try{await this.repository.set(n.key,n.value),i.debug(`Synced: ${n.key}`)}catch(r){i.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(),i.debug("MissingTranslationQueue destroyed")}};var q=class d{constructor(e){c(this,"config");c(this,"plugins",[]);c(this,"syncStorageRepos",[]);c(this,"asyncStorageRepos",[]);c(this,"networkRepos",[]);c(this,"syncQueue",null);this.config={defaultLocale:e.defaultLocale||"en",fallbackLocale:e.fallbackLocale||"en",namespace:e.namespace||"app"}}static init(e={}){return new d(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}async build(){let e=new U,t=e.builder();i.info("Builder started"),i.debug("Builder config",this.config),t.buildStart(this.config.defaultLocale,this.config.namespace);let n=new H(e);for(let o of this.syncStorageRepos){if(!o.getConfig().enabled)continue;let l=new Q(e,o);t.use("sync"),n.addSyncHandler(l)}for(let o of this.asyncStorageRepos){if(!o.getConfig().enabled)continue;let l=new Y(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 Z(e,o);r||(r=l),t.use("network"),n.addAsyncHandler(l);let p=o.getConfig();p.options?.syncMissing?.enabled&&(this.syncQueue=new D(o,{enabled:p.options.syncMissing.enabled,debounceMs:p.options.syncMissing.debounceMs||500,batchSize:p.options.syncMissing.batchSize||50},e),e.on("translation:not-found",u=>{this.syncQueue&&this.syncQueue.add({key:u.payload.key,fallbackValue:u.payload.fallbackValue,styles:u.payload.styles,locale:u.payload.locale,namespace:u.payload.namespace})}),i.info("Missing translation sync enabled"),i.debug("Sync queue config",p.options.syncMissing))}i.debug("Handler chain constructed");let s=new O(e,n,this.config.defaultLocale,this.config.fallbackLocale,this.config.namespace);for(let o of this.plugins)t.use("plugin"),await o.initialize({core:s,bus:e}),s.registerPlugin(o),i.info(`Plugin initialized: ${o.name}`),i.debug(`Plugin version: ${o.version}`,o.capabilities);let a=n.getChainInfo();return r&&await this.executePreloading(r,n),i.info("Builder completed"),t.buildDone(a.handlers.map(o=>o.name),this.plugins.map(o=>o.name)),s}async executePreloading(e,t){let n=e.getPreload().filter(s=>s.eager!==!1);if(!n||n.length===0)return;i.info(`Preloading ${n.length} namespaces`),i.debug("Preload targets",{namespaces:n.map(s=>`${s.locale}:${s.namespace}`)});let r=n.map(async s=>{try{let a=await e.loadNamespace(s.locale,s.namespace);if(a&&a.data&&a.status===200){let o={locale:s.locale,namespace:s.namespace,fallbackLocale:this.config.fallbackLocale};await t.saveNamespaceToHandlers(a.data,o),i.debug(`Preloaded: ${s.locale}:${s.namespace}`)}}catch(a){i.warn(`Preload failed: ${s.locale}:${s.namespace}`,a)}});await Promise.allSettled(r),i.info("Preloading completed")}};var _=class _{constructor(e={}){c(this,"name","NetworkRepository");c(this,"type","network");c(this,"config",{});c(this,"namespaceVersions",new Map);c(this,"DEFAULT_ENDPOINTS",{getTranslation:"/api/integrations/translations/:key",getNamespace:"/api/integrations/translations/:locale/:namespace",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 i.debug("API base URL is not set"),new w("API base URL is not set");let t=this.buildUrl("getTranslation",{key:e});i.debug(`API GET: ${t}`);try{let n=await this.makeRequest(t,"GET");n.ok||this.handleHttpError(n,e);let r=await n.json();i.debug("API response data:",r);let s=r.translations[r.meta?.key]||r.translations[e]||Object.values(r.translations)[0];if(i.debug(`Fetched translation for key "${e}":`,s),!s)throw new h(e);return typeof s=="object"&&"text"in s?(i.debug(`ContentUnit text: "${s.text}"`),s.text):String(s)}catch(n){this.handleCaughtError(n)}}async getContentUnit(e){if(!this.config?.options?.baseUrl)throw i.debug("API base URL is not set"),new w("API base URL is not set");let t=this.buildUrl("getTranslation",{key:e});i.debug(`API GET ContentUnit: ${t}`);try{let n=await this.makeRequest(t,"GET");n.ok||this.handleHttpError(n,e);let r=await n.json();i.debug("API response data:",r);let s=r.translations[r.meta?.key]||r.translations[e]||Object.values(r.translations)[0];if(!s)throw new h(e);return typeof s=="object"&&"text"in s?(i.debug(`ContentUnit for "${e}": text="${s.text}", styles=`,s.styles),{text:s.text,styles:s.styles||{}}):(i.debug(`Plain string for "${e}": "${s}" (no styles)`),{text:String(s),styles:{}})}catch(n){this.handleCaughtError(n)}}async getNamespace(e,t){if(!this.config?.options?.baseUrl)throw i.debug("API base URL is not set"),new w("API base URL is not set");let n=this.buildUrl("getNamespace",{locale:e,namespace:t});i.debug(`API GET Namespace: ${n}`);let r=`${e}:${t}`;try{let s={},a=this.getVersion(r);a&&(s["If-None-Match"]=`W/"${a}"`);let o=await this.makeRequest(n,"GET",void 0,s);if(o.status===304)return i.debug(`Namespace ${r}: 304 Not Modified`),null;o.ok||this.handleHttpError(o,r);let l=await o.json();if(i.debug("API response data:",l),!l.translations)throw new h(r);let p=l.meta?.version!=null?String(l.meta.version):null;return p&&this.setVersion(r,p),l.translations}catch(s){this.handleCaughtError(s)}}async set(e,t){if(!this.config?.options?.baseUrl)return i.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 i.debug(`API set failed for key "${e}":`,n),n}}async setNamespace(e,t,n){if(!this.config?.options?.baseUrl)return i.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 i.debug(`API setNamespace failed for ${e}:${t}:`,r),r}}async setBatch(e){if(!this.config?.options?.baseUrl)return i.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("setBatch");i.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}`);i.debug(`Batch sync successful: ${e.length} items`)}catch(t){throw i.debug(`API setBatch failed for ${e.length} items:`,t),t}}async getNamespaceContentUnits(e,t){if(!this.config?.options?.baseUrl)throw i.debug("API base URL is not set"),new w("API base URL is not set");let n=this.buildUrl("getNamespace",{locale:e,namespace:t});i.debug(`API GET Namespace ContentUnits: ${n}`);let r=`${e}:${t}`;try{let s={},a=this.getVersion(r);a&&(s["If-None-Match"]=`W/"${a}"`);let o=await this.makeRequest(n,"GET",void 0,s);if(o.status===304)return i.debug(`Namespace ContentUnits ${r}: 304 Not Modified`),null;o.ok||this.handleHttpError(o,r);let l=await o.json();if(i.debug("API response data:",l),!l.translations)throw new h(r);let p=l.meta?.version!=null?String(l.meta.version):null;return p&&this.setVersion(r,p),l.translations}catch(s){this.handleCaughtError(s)}}async setContentUnit(e,t){if(!this.config?.options?.baseUrl)return i.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}`);i.debug(`Saved ContentUnit for key "${e}"`)}catch(n){throw i.debug(`API setContentUnit failed for key "${e}":`,n),n}}async setBatchContentUnits(e){if(!this.config?.options?.baseUrl)return i.debug("API base URL is not set"),Promise.reject(new Error("API base URL is not set"));try{let t=this.buildUrl("setBatch");i.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}`);i.debug(`Batch ContentUnit sync successful: ${e.length} items`)}catch(t){throw i.debug(`API setBatchContentUnits failed for ${e.length} items:`,t),t}}async remove(e){if(!this.config?.options?.baseUrl)return i.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 i.debug(`API remove failed for key "${e}":`,t),t}}async clear(){if(!this.config?.options?.baseUrl)return i.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 i.debug("API clear failed:",e),e}}getConfig(){return this.config}getVersion(e){let t=this.namespaceVersions.get(e);if(t)return t;try{let n=localStorage.getItem(_.VERSION_PREFIX+e);if(n)return this.namespaceVersions.set(e,n),n}catch{}}setVersion(e,t){this.namespaceVersions.set(e,t);try{localStorage.setItem(_.VERSION_PREFIX+e,t)}catch{}}handleHttpError(e,t){if(i.debug(`API response: ${e.status} ${e.statusText}`),e.status===404)throw new h(t);if(e.status===423){let n=e.headers.get("Retry-After");throw new x(t,n?parseInt(n,10)*1e3:void 0)}throw e.status>=500&&e.status<600?new $(t,e.status):new w(`HTTP ${e.status}: ${e.statusText}`)}handleCaughtError(e){throw e instanceof h||e instanceof x||e instanceof $||e instanceof w?e:new w("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[a,o]of Object.entries(t)){let l=new RegExp(`:${a}`,"g");s=s.replace(l,encodeURIComponent(o))}return`${n}${s}`}async makeRequest(e,t,n,r){let s=new AbortController,a=this.config.options?.timeout??1e4,o=setTimeout(()=>s.abort(),a);try{let l={"Content-Type":"application/json",...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)}}};c(_,"VERSION_PREFIX","lionrapid:v:");var ee=_;var te=class{constructor(e){c(this,"name","MemoryRepository");c(this,"type","memory");c(this,"config",{});c(this,"cache",new Map);c(this,"accessOrder",new Map);c(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 W=class{validate(e){let t=[],n=[];return this.validateTagBalance(e.text,t),this.validateStyleReferences(e.text,e.styles,t,n),this.validateICUBraces(e.text,t),{valid:t.length===0,errors:t,warnings:n}}validateTagBalance(e,t){let n=/<(\/?)?(\d+)(\/)?>/g,r=[],s;for(;(s=n.exec(e))!==null;){let[,a,o,l]=s;if(!l)if(a)if(r.length===0)t.push({code:"UNBALANCED_TAGS",message:`Closing tag </${o}> has no matching opening tag`,path:`text[${s.index}]`});else{let p=r[r.length-1];if(p.index===o)r.pop();else{let u=r.findIndex(g=>g.index===o);u>=0?(t.push({code:"UNBALANCED_TAGS",message:`Improperly nested: </${o}> should close before </${p.index}>`,path:`text[${s.index}]`}),r.splice(u,1)):t.push({code:"UNBALANCED_TAGS",message:`Closing tag </${o}> has no matching opening tag`,path:`text[${s.index}]`})}}else r.push({index:o,position:s.index})}for(let{index:a}of r)t.push({code:"UNBALANCED_TAGS",message:`Opening tag <${a}> has no matching closing tag`,path:"text"})}validateStyleReferences(e,t,n,r){let s=new Set,a=/<\/?(\d+)(?:\/)?>/g,o;for(;(o=a.exec(e))!==null;)s.add(o[1]);for(let l of s)(!t[l]||t[l].length===0)&&r.push({code:"EMPTY_STYLE",message:`Tag <${l}> has no style definition, will render as <span>`});for(let l of Object.keys(t))s.has(l)||r.push({code:"UNUSED_TAG",message:`Style for tag <${l}> is defined but tag is not used in text`})}validateICUBraces(e,t){let n=0,r=!1,s="";for(let o=0;o<e.length;o++){let l=e[o],p=o>0?e[o-1]:"";if((l==='"'||l==="'")&&p!=="\\"){r?l===s&&(r=!1,s=""):(r=!0,s=l);continue}r||(l==="{"?n++:l==="}"&&(n--,n<0&&(t.push({code:"INVALID_ICU",message:`Unbalanced ICU braces: unexpected '}' at position ${o}`,path:`text[${o}]`}),n=0)))}n>0&&t.push({code:"INVALID_ICU",message:`Unbalanced ICU braces: ${n} unclosed '{'`,path:"text"}),/\{\s*[,}]/.test(e)&&t.push({code:"INVALID_ICU",message:"ICU variable name is empty or missing",path:"text"})}};var le="lionrapid:",j=`${le}version`,Ce="1",ne=class{constructor(e={}){c(this,"name","LocalStorageRepository");c(this,"type","memory");c(this,"config");c(this,"available");c(this,"prefix");c(this,"defaultTTL");c(this,"maxSize");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{prefix:e.options?.prefix??le,ttl:e.options?.ttl??1440*60*1e3,maxSize:e.options?.maxSize??500,...e.options}},this.prefix=this.config.options?.prefix??le,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(j)!==Ce&&(this.clear(),window.localStorage.setItem(j,Ce))}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!==j&&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 a=0;a<window.localStorage.length;a++){let o=window.localStorage.key(a);if(!o?.startsWith(this.prefix))continue;let l=o.slice(this.prefix.length);(l===n||l.startsWith(r))&&s.push(o)}s.forEach(a=>window.localStorage.removeItem(a))}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===j)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!==j&&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===j))try{let s=window.localStorage.getItem(r);if(s){let a=JSON.parse(s);e.push({key:r,timestamp:a.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 we="lionrapid-v1",T="lionrapid:",re=class{constructor(e={}){c(this,"name","CacheStorageRepository");c(this,"type","storage");c(this,"config");c(this,"cacheName");c(this,"defaultTTL");c(this,"available");this.config={enabled:e.enabled??!0,priority:e.priority??0,options:{cacheName:e.options?.cacheName??we,ttl:e.options?.ttl??10080*60*1e3,...e.options}},this.cacheName=this.config.options?.cacheName??we,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 h(e);try{let t=await caches.open(this.cacheName),n=await t.match(T+e);if(!n)throw new h(e);let r=await n.json();if(r.expiry!==null&&Date.now()>r.expiry)throw await t.delete(T+e),new h(e);return r.value}catch(t){throw t instanceof h?t:new h(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(T+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(T+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(T)).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),a=await s.keys();await Promise.all(a.filter(o=>{let l=o.url,p=l.includes(T)?l.substring(l.indexOf(T)+T.length):"";return p===n||p.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 h(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(T))continue;let a=s.substring(s.indexOf(T)+T.length);try{let o=await this.get(a);e[a]=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(T)).length,cacheName:this.cacheName}}catch{return{size:0,cacheName:this.cacheName}}}};var He="1.0.0";return Ne(Oe);})();
|
|
3
3
|
//# sourceMappingURL=lionrapid.iife.min.js.map
|