@rimori/playwright-testing 0.3.28-next.1 → 0.3.28-next.2
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/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare___mf_0_rimori_mf_1_client__loadShare__.mjs.js +5 -8
- package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare___mf_0_rimori_mf_1_react_mf_2_client__loadShare__.mjs.js +51 -69
- package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs.js +1 -1
- package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react_mf_1_jsx_mf_2_dev_mf_2_runtime__loadShare__.mjs.js +1 -9
- package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs.js +9 -25
- package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__zod__loadShare__.mjs.js +1 -1
- package/dist/harness/dist.js +4 -0
- package/dist/harness/hostInit.js +1 -1
- package/dist/harness/index.html +1 -0
- package/dist/harness/index.js +1 -1
- package/dist/harness/localSharedImportMap.js +1 -1
- package/dist/harness/preload-helper.js +1 -1
- package/dist/harness/remoteEntry.js +2 -7
- package/dist/harness/rolldown-runtime.js +1 -0
- package/dist/harness/virtualExposes.js +1 -1
- package/package.json +3 -3
- package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react__loadShare__.mjs.js +0 -9
- package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react__loadShare__.mjs_commonjs-proxy.js +0 -1
- package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs.js +0 -9
- package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react_mf_2_dom__loadShare__.mjs.js +0 -9
- package/dist/harness/__mfe_internal__rimori_mf_2_scenario_mf_2_host__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy.js +0 -1
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
function ze(r,e){for(var t=0;t<e.length;t++){const s=e[t];if(typeof s!="string"&&!Array.isArray(s)){for(const i in s)if(i!=="default"&&!(i in r)){const n=Object.getOwnPropertyDescriptor(s,i);n&&Object.defineProperty(r,i,n.get?n:{enumerable:!0,get:()=>s[i]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}class L{listeners=new Map;responseResolvers=new Map;static instance=null;debugEnabled=!1;evName="";generatedIds=new Map;cleanupInterval=null;constructor(){this.startIdCleanup()}static create(e){const t=new L;return e&&(t.evName=e),t}static getInstance(e){return L.instance||(L.instance=new L,L.instance.on("global.system.requestDebug",()=>{L.instance.debugEnabled=!0,console.log(`[${L.instance.evName}] Debug mode enabled. Make sure debugging messages are enabled in the browser console.`)})),e&&L.instance.evName===""&&(L.instance.evName=e),L.instance}startIdCleanup(){this.cleanupInterval=setInterval(()=>{const t=Date.now()-6e4;for(const[s,i]of this.generatedIds.entries())i<t&&this.generatedIds.delete(s)},1e4)}generateUniqueId(){const e=Date.now(),t=e-6e4,s=Math.floor(Math.random()*1e10),i=this.generatedIds.get(s);return i&&i>t?this.generateUniqueId():(this.generatedIds.set(s,e),s)}createEvent(e,t,s,i,n){return{eventId:i||this.generateUniqueId(),timestamp:new Date().toISOString(),sender:e,topic:t,data:s,debug:this.debugEnabled,ai_session_token:n}}emit(e,t,s,i,n){this.emitInternal(e,t,s||{},i,!1,n)}emitInternal(e,t,s,i,n=!1,o){if(!this.validateTopic(t)){this.logAndThrowError(!1,"Invalid topic: "+t);return}const a=this.createEvent(e,t,s,i,o),l=this.getMatchingHandlers(a.topic);l.forEach(c=>{c.ignoreSender&&c.ignoreSender.includes(e)||c.handler(a)}),this.logIfDebug("Emitting event to "+t,a),l.size===0&&this.logAndThrowError(!1,"No handlers found for topic: "+t),i&&this.responseResolvers.has(i)&&!n&&(this.responseResolvers.get(i)(a),this.responseResolvers.delete(i))}on(e,t,s=[]){const i=this.toArray(e).map(n=>{this.logIfDebug("Subscribing to "+n,{ignoreSender:s}),this.validateTopic(n)||this.logAndThrowError(!0,"Invalid topic: "+n),this.listeners.has(n)||this.listeners.set(n,new Set);const o=this.generateUniqueId(),a=[],l=c=>{if(!a.some(h=>h.eventId===c.eventId&&h.sender===c.sender))return a.push({eventId:c.eventId,sender:c.sender}),a.length>100&&a.shift(),t(c)};return this.listeners.get(n).add({id:o,handler:l,ignoreSender:s}),this.logIfDebug("Subscribed to "+n,{listenerId:o,ignoreSender:s}),btoa(JSON.stringify({topic:n,id:o}))});return{off:()=>this.off(i)}}respond(e,t,s){const n=(Array.isArray(t)?t:[t]).map(o=>{const a=[],l=o.startsWith("self.")?[]:[e],c=this.on(o,async h=>{if(a.includes(h.eventId))return;a.push(h.eventId),a.length>100&&a.shift();const u=typeof s=="function"?await s(h):s;this.emit(e,o,u,h.eventId)},l);return this.logIfDebug("Added respond listener "+e+" to topic "+o,{listener:c,sender:e}),{off:()=>c.off()}});return{off:()=>n.forEach(o=>o.off())}}once(e,t){if(!this.validateTopic(e)){this.logAndThrowError(!1,"Invalid topic: "+e);return}let s;const i=n=>{t(n),s?.off()};s=this.on(e,i),this.logIfDebug("Added once listener "+e,{listener:s,topic:e})}off(e){this.toArray(e).forEach(t=>{const{topic:s,id:i}=JSON.parse(atob(t)),n=this.listeners.get(s)||new Set;n.forEach(o=>{o.id===Number(i)&&(n.delete(o),this.logIfDebug("Removed listener "+t,{topic:s,listenerId:i}))})})}toArray(e){return Array.isArray(e)?e:[e]}async request(e,t,s,i){this.validateTopic(t)||this.logAndThrowError(!0,"Invalid topic: "+t);const n=this.createEvent(e,t,s||{},void 0,i);return this.logIfDebug("Requesting data from "+t,{event:n}),new Promise(o=>{this.responseResolvers.set(n.eventId,a=>o(a)),this.emitInternal(e,t,s||{},n.eventId,!0,i)})}getMatchingHandlers(e){const t=this.listeners.get(e)||new Set,s=[...this.listeners.entries()].filter(([i])=>i.endsWith("*")&&e.startsWith(i.slice(0,-1))).flatMap(([i,n])=>[...n]);return new Set([...t,...s])}validateTopic(e){const t=e.split("."),[s,i,n]=t;if(t.length!==3)return t.length===1&&s==="*"||t.length===2&&s!=="*"&&i==="*"?!0:(this.logAndThrowError(!1,"Event type must have 3 parts separated by dots. Received: "+e),!1);if(n==="*")return!0;const o=["request","create","update","delete","trigger"];return o.some(a=>n.startsWith(a))?!0:(this.logAndThrowError(!1,"Invalid event topic name. The action: "+n+". Must be or start with one of: "+o.join(", ")),!1)}logIfDebug(...e){this.debugEnabled&&console.debug(`[${this.evName}] `+e[0],...e.slice(1))}destroy(){this.listeners.clear(),this.responseResolvers.clear(),this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.generatedIds.clear()}logAndThrowError(e,...t){const s=`[${this.evName}] `+t[0];if(console.error(s,...t.slice(1)),e)throw new Error(s)}}const P=L.getInstance();class Ve{supabase;rimoriClient;constructor(e,t){this.supabase=e,this.rimoriClient=t}async getNew(e){const t=await this.rimoriClient.runtime.fetchBackend("/shared-content/generate",{method:"POST",body:JSON.stringify({tableName:e.table,skillType:e.skillType,placeholders:e.placeholders,filter:e.filter,customFields:e.customFields,tool:e.tool,options:{skipDbSave:e.skipDbSave,isPrivate:e.isPrivate,ignoreSkillLevel:e.ignoreSkillLevel}})});if(!t.ok)throw new Error(`Failed to generate shared content: ${t.statusText}`);return await t.json()}async searchByTopic(e,t,s=10){const i=await this.rimoriClient.runtime.fetchBackend("/shared-content/get-by-topic",{method:"POST",body:JSON.stringify({tableName:e,limit:s,filter:{title:{filterType:"rag",value:t}}})});if(!i.ok)throw new Error(`Failed to search shared content: ${i.statusText}`);return await i.json()}async getBookmarked(e,t=30){const s=this.getTableName(e),i=this.getCompletedTableName(e),{data:n,error:o}=await this.supabase.from(s).select(`*, completed:${i}!inner(*)`).eq("completed.bookmarked",!0).limit(t);if(o)throw console.error("Error fetching bookmarked content:",o),new Error("Error fetching bookmarked content");return n||[]}async getOngoing(e,t=30){const s=this.getTableName(e),i=this.getCompletedTableName(e),{data:n,error:o}=await this.supabase.from(s).select(`*, completed:${i}!inner(*)`).eq("completed.state","ongoing").limit(t);if(o)throw console.error("Error fetching ongoing content:",o),new Error("Error fetching ongoing content");return n||[]}async getCompleted(e,t=30){const s=this.getTableName(e),i=this.getCompletedTableName(e),{data:n,error:o}=await this.supabase.from(s).select(`*, completed:${i}!inner(*)`).eq("completed.state","completed").limit(t);if(o)throw console.error("Error fetching completed content:",o),new Error("Error fetching completed content");return n||[]}async complete(e,t){const s=this.getCompletedTableName(e),{error:i}=await this.supabase.from(s).upsert({content_id:t,state:"completed"},{onConflict:"content_id,user_id"});if(i)throw console.error("Error completing shared content:",i),new Error("Error completing shared content")}async updateState(e,t,s){const i=this.getCompletedTableName(e),{error:n}=await this.supabase.from(i).upsert({content_id:t,state:s},{onConflict:"content_id,user_id"});if(n)throw console.error("Error updating content state:",n),new Error("Error updating content state")}async bookmark(e,t,s){const i=this.getCompletedTableName(e),{error:n}=await this.supabase.from(i).upsert({content_id:t,bookmarked:s},{onConflict:"content_id,user_id"});if(n)throw console.error("Error bookmarking content:",n),new Error("Error bookmarking content")}async react(e,t,s){const i=this.getCompletedTableName(e),{error:n}=await this.supabase.from(i).upsert({content_id:t,reaction:s},{onConflict:"content_id,user_id"});if(n)throw console.error("Error reacting to content:",n),new Error("Error reacting to content")}async get(e,t){const s=this.getTableName(e),{data:i,error:n}=await this.supabase.from(s).select("*").eq("id",t).single();if(n)throw console.error("Error fetching shared content:",n),new Error("Error fetching shared content");return i}async getAll(e,t=100){const s=this.getTableName(e),{data:i,error:n}=await this.supabase.from(s).select("*").limit(t);if(n)throw console.error("Error fetching all shared content:",n),new Error("Error fetching all shared content");return i||[]}async create(e,t){const s=this.getTableName(e),{data:i,error:n}=await this.supabase.from(s).insert(t).select().single();if(n)throw console.error("Error creating shared content:",n),new Error("Error creating shared content");return i}async update(e,t,s){const i=await this.rimoriClient.runtime.fetchBackend("/shared-content/update",{method:"POST",body:JSON.stringify({tableName:e,contentId:t,updates:s})});if(!i.ok)throw console.error("Error updating shared content:",i.statusText),new Error(`Failed to update shared content: ${i.statusText}`);return await i.json()}async validate(e,t){const s=await this.rimoriClient.runtime.fetchBackend("/shared-content/validate",{method:"POST",body:JSON.stringify({tableName:e,contentId:t})});if(!s.ok)throw console.error("Error validating shared content:",s.statusText),new Error(`Failed to validate shared content: ${s.statusText}`);return await s.json()}async remove(e,t){const s=this.getTableName(e),{error:i}=await this.supabase.from(s).delete().eq("id",t);if(i)throw console.error("Error deleting shared content:",i),new Error("Error deleting shared content")}getCompletedTableName(e){return this.getTableName(e)+"_completed"}getTableName(e){return`${this.rimoriClient.plugin.pluginId}_sc_${e}`}}var Je=class extends Error{constructor(r){super(r.message),this.name="PostgrestError",this.details=r.details,this.hint=r.hint,this.code=r.code}},We=class{constructor(r){var e,t,s;this.shouldThrowOnError=!1,this.method=r.method,this.url=r.url,this.headers=new Headers(r.headers),this.schema=r.schema,this.body=r.body,this.shouldThrowOnError=(e=r.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=r.signal,this.isMaybeSingle=(t=r.isMaybeSingle)!==null&&t!==void 0?t:!1,this.urlLengthLimit=(s=r.urlLengthLimit)!==null&&s!==void 0?s:8e3,r.fetch?this.fetch=r.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(r,e){return this.headers=new Headers(this.headers),this.headers.set(r,e),this}then(r,e){var t=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const s=this.fetch;let i=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let o=null,a=null,l=null,c=n.status,h=n.statusText;if(n.ok){var u,g;if(t.method!=="HEAD"){var d;const m=await n.text();m===""||(t.headers.get("Accept")==="text/csv"||t.headers.get("Accept")&&(!((d=t.headers.get("Accept"))===null||d===void 0)&&d.includes("application/vnd.pgrst.plan+text"))?a=m:a=JSON.parse(m))}const f=(u=t.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),y=(g=n.headers.get("content-range"))===null||g===void 0?void 0:g.split("/");f&&y&&y.length>1&&(l=parseInt(y[1])),t.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(o={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,c=406,h="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{const f=await n.text();try{o=JSON.parse(f),Array.isArray(o)&&n.status===404&&(a=[],o=null,c=200,h="OK")}catch{n.status===404&&f===""?(c=204,h="No Content"):o={message:f}}if(o&&t.shouldThrowOnError)throw new Je(o)}return{error:o,data:a,count:l,status:c,statusText:h}});return this.shouldThrowOnError||(i=i.catch(n=>{var o;let a="",l="",c="";const h=n?.cause;if(h){var u,g,d,f;const w=(u=h?.message)!==null&&u!==void 0?u:"",b=(g=h?.code)!==null&&g!==void 0?g:"";a=`${(d=n?.name)!==null&&d!==void 0?d:"FetchError"}: ${n?.message}`,a+=`
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
${h.stack}`)}else{var y;a=(y=n?.stack)!==null&&y!==void 0?y:""}const m=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(c="",l="Request was aborted (timeout or manual cancellation)",m>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${m} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(h?.name==="HeadersOverflowError"||h?.code==="UND_ERR_HEADERS_OVERFLOW")&&(c="",l="HTTP headers exceeded server limits (typically 16KB)",m>this.urlLengthLimit&&(l+=`. Your request URL is ${m} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(o=n?.name)!==null&&o!==void 0?o:"FetchError"}: ${n?.message}`,details:a,hint:l,code:c},data:null,count:null,status:0,statusText:""}})),i.then(r,e)}returns(){return this}overrideTypes(){return this}},Ge=class extends We{select(r){let e=!1;const t=(r??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",t),this.headers.append("Prefer","return=representation"),this}order(r,{ascending:e=!0,nullsFirst:t,foreignTable:s,referencedTable:i=s}={}){const n=i?`${i}.order`:"order",o=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${o?`${o},`:""}${r}.${e?"asc":"desc"}${t===void 0?"":t?".nullsfirst":".nullslast"}`),this}limit(r,{foreignTable:e,referencedTable:t=e}={}){const s=typeof t>"u"?"limit":`${t}.limit`;return this.url.searchParams.set(s,`${r}`),this}range(r,e,{foreignTable:t,referencedTable:s=t}={}){const i=typeof s>"u"?"offset":`${s}.offset`,n=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${r}`),this.url.searchParams.set(n,`${e-r+1}`),this}abortSignal(r){return this.signal=r,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:r=!1,verbose:e=!1,settings:t=!1,buffers:s=!1,wal:i=!1,format:n="text"}={}){var o;const a=[r?"analyze":null,e?"verbose":null,t?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${l}"; options=${a};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(r){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${r}`),this}};const ye=new RegExp("[,()]");var H=class extends Ge{eq(r,e){return this.url.searchParams.append(r,`eq.${e}`),this}neq(r,e){return this.url.searchParams.append(r,`neq.${e}`),this}gt(r,e){return this.url.searchParams.append(r,`gt.${e}`),this}gte(r,e){return this.url.searchParams.append(r,`gte.${e}`),this}lt(r,e){return this.url.searchParams.append(r,`lt.${e}`),this}lte(r,e){return this.url.searchParams.append(r,`lte.${e}`),this}like(r,e){return this.url.searchParams.append(r,`like.${e}`),this}likeAllOf(r,e){return this.url.searchParams.append(r,`like(all).{${e.join(",")}}`),this}likeAnyOf(r,e){return this.url.searchParams.append(r,`like(any).{${e.join(",")}}`),this}ilike(r,e){return this.url.searchParams.append(r,`ilike.${e}`),this}ilikeAllOf(r,e){return this.url.searchParams.append(r,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(r,e){return this.url.searchParams.append(r,`ilike(any).{${e.join(",")}}`),this}regexMatch(r,e){return this.url.searchParams.append(r,`match.${e}`),this}regexIMatch(r,e){return this.url.searchParams.append(r,`imatch.${e}`),this}is(r,e){return this.url.searchParams.append(r,`is.${e}`),this}isDistinct(r,e){return this.url.searchParams.append(r,`isdistinct.${e}`),this}in(r,e){const t=Array.from(new Set(e)).map(s=>typeof s=="string"&&ye.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(r,`in.(${t})`),this}notIn(r,e){const t=Array.from(new Set(e)).map(s=>typeof s=="string"&&ye.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(r,`not.in.(${t})`),this}contains(r,e){return typeof e=="string"?this.url.searchParams.append(r,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(r,`cs.{${e.join(",")}}`):this.url.searchParams.append(r,`cs.${JSON.stringify(e)}`),this}containedBy(r,e){return typeof e=="string"?this.url.searchParams.append(r,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(r,`cd.{${e.join(",")}}`):this.url.searchParams.append(r,`cd.${JSON.stringify(e)}`),this}rangeGt(r,e){return this.url.searchParams.append(r,`sr.${e}`),this}rangeGte(r,e){return this.url.searchParams.append(r,`nxl.${e}`),this}rangeLt(r,e){return this.url.searchParams.append(r,`sl.${e}`),this}rangeLte(r,e){return this.url.searchParams.append(r,`nxr.${e}`),this}rangeAdjacent(r,e){return this.url.searchParams.append(r,`adj.${e}`),this}overlaps(r,e){return typeof e=="string"?this.url.searchParams.append(r,`ov.${e}`):this.url.searchParams.append(r,`ov.{${e.join(",")}}`),this}textSearch(r,e,{config:t,type:s}={}){let i="";s==="plain"?i="pl":s==="phrase"?i="ph":s==="websearch"&&(i="w");const n=t===void 0?"":`(${t})`;return this.url.searchParams.append(r,`${i}fts${n}.${e}`),this}match(r){return Object.entries(r).filter(([e,t])=>t!==void 0).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(r,e,t){return this.url.searchParams.append(r,`not.${e}.${t}`),this}or(r,{foreignTable:e,referencedTable:t=e}={}){const s=t?`${t}.or`:"or";return this.url.searchParams.append(s,`(${r})`),this}filter(r,e,t){return this.url.searchParams.append(r,`${e}.${t}`),this}},Qe=class{constructor(r,{headers:e={},schema:t,fetch:s,urlLengthLimit:i=8e3}){this.url=r,this.headers=new Headers(e),this.schema=t,this.fetch=s,this.urlLengthLimit=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(r,e){const{head:t=!1,count:s}=e??{},i=t?"HEAD":"GET";let n=!1;const o=(r??"*").split("").map(c=>/\s/.test(c)&&!n?"":(c==='"'&&(n=!n),c)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),s&&l.append("Prefer",`count=${s}`),new H({method:i,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(r,{count:e,defaultToNull:t=!0}={}){var s;const i="POST",{url:n,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),t||o.append("Prefer","missing=default"),Array.isArray(r)){const a=r.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(a.length>0){const l=[...new Set(a)].map(c=>`"${c}"`);n.searchParams.set("columns",l.join(","))}}return new H({method:i,url:n,headers:o,schema:this.schema,body:r,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(r,{onConflict:e,ignoreDuplicates:t=!1,count:s,defaultToNull:i=!0}={}){var n;const o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${t?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),s&&l.append("Prefer",`count=${s}`),i||l.append("Prefer","missing=default"),Array.isArray(r)){const c=r.reduce((h,u)=>h.concat(Object.keys(u)),[]);if(c.length>0){const h=[...new Set(c)].map(u=>`"${u}"`);a.searchParams.set("columns",h.join(","))}}return new H({method:o,url:a,headers:l,schema:this.schema,body:r,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(r,{count:e}={}){var t;const s="PATCH",{url:i,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new H({method:s,url:i,headers:n,schema:this.schema,body:r,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:r}={}){var e;const t="DELETE",{url:s,headers:i}=this.cloneRequestState();return r&&i.append("Prefer",`count=${r}`),new H({method:t,url:s,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function Y(r){"@babel/helpers - typeof";return Y=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Y(r)}function Ye(r,e){if(Y(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(Y(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function Ze(r){var e=Ye(r,"string");return Y(e)=="symbol"?e:e+""}function Xe(r,e,t){return(e=Ze(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function be(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,s)}return t}function ee(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?be(Object(t),!0).forEach(function(s){Xe(r,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):be(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s))})}return r}var Re=class Ne{constructor(e,{headers:t={},schema:s,fetch:i,timeout:n,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new Headers(t),this.schemaName=s,this.urlLengthLimit=o;const a=i??globalThis.fetch;n!==void 0&&n>0?this.fetch=(l,c)=>{const h=new AbortController,u=setTimeout(()=>h.abort(),n),g=c?.signal;if(g){if(g.aborted)return clearTimeout(u),a(l,c);const d=()=>{clearTimeout(u),h.abort()};return g.addEventListener("abort",d,{once:!0}),a(l,ee(ee({},c),{},{signal:h.signal})).finally(()=>{clearTimeout(u),g.removeEventListener("abort",d)})}return a(l,ee(ee({},c),{},{signal:h.signal})).finally(()=>clearTimeout(u))}:this.fetch=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Qe(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Ne(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,t={},{head:s=!1,get:i=!1,count:n}={}){var o;let a;const l=new URL(`${this.url}/rpc/${e}`);let c;const h=d=>d!==null&&typeof d=="object"&&(!Array.isArray(d)||d.some(h)),u=s&&Object.values(t).some(h);u?(a="POST",c=t):s||i?(a=s?"HEAD":"GET",Object.entries(t).filter(([d,f])=>f!==void 0).map(([d,f])=>[d,Array.isArray(f)?`{${f.join(",")}}`:`${f}`]).forEach(([d,f])=>{l.searchParams.append(d,f)})):(a="POST",c=t);const g=new Headers(this.headers);return u?g.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&g.set("Prefer",`count=${n}`),new H({method:a,url:l,headers:g,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};class de{pluginId;port=null;queryParams={};supabase=null;rimoriInfo=null;isMessageChannelReady=!1;pendingRequests=[];updateCallbacks=new Set;constructor(e,t){this.pluginId=e,this.getClient=this.getClient.bind(this),!t&&this.initMessageChannel(typeof WorkerGlobalScope<"u")}initMessageChannel(e=!1){const t=s=>{const{type:i,pluginId:n,queryParams:o,rimoriInfo:a}=s.data||{},[l]=s.ports||[];i!=="rimori:init"||!l||n!==this.pluginId||(this.queryParams=o||{},this.port=l,a&&(this.rimoriInfo=a,this.supabase=this.getSupabase(a.url,a.key,a.token)),this.port.onmessage=({data:c})=>{const{event:h,type:u,eventId:g,response:d,error:f}=c||{};if(u==="response"&&g)P.emit(this.pluginId,d.topic,d.data,g);else if(u==="error"&&g)P.emit(this.pluginId,"error",{error:f},g);else if(h){const{topic:y,sender:m,data:w,eventId:b,ai_session_token:$}=h;m!==this.pluginId&&P.emit(m,y,w,b,$)}},P.on("*",c=>{c.sender===this.pluginId&&!c.topic.startsWith("self.")&&this.port?.postMessage({event:c})}),P.on(`${this.pluginId}.supabase.triggerUpdate`,c=>{this.handleRimoriInfoUpdate(c.data)}),this.isMessageChannelReady=!0,this.pendingRequests.forEach(c=>c()),this.pendingRequests=[])};e?self.onmessage=t:window.addEventListener("message",t),this.sendHello(e),P.on("self.rimori.triggerInitFinished",()=>{this.sendFinishedInit(e)})}sendHello(e=!1){try{const t={type:"rimori:hello",pluginId:this.pluginId};e?self.postMessage(t):window.parent.postMessage(t,"*")}catch(t){console.error("[PluginController] Error sending hello:",t)}}sendFinishedInit(e=!1){try{const t={type:"rimori:acknowledged",pluginId:this.pluginId};e?self.postMessage(t):window.parent.postMessage(t,"*")}catch(t){console.error("[PluginController] Error sending finished init:",t)}}getQueryParam(e){return this.queryParams[e]||null}getSupabase(e,t,s){return new Re(`${e}/rest/v1`,{schema:this.rimoriInfo?.dbSchema,headers:{apikey:t,Authorization:`Bearer ${s}`,"plugin-id":this.pluginId}})}async getClient(){if(this.supabase&&this.rimoriInfo&&this.rimoriInfo.expiration>new Date)return{supabase:this.supabase,info:this.rimoriInfo};if(!this.isMessageChannelReady)return new Promise(e=>{this.pendingRequests.push(async()=>{const t=await this.getClient();e(t)})});if(this.rimoriInfo&&this.supabase)return{supabase:this.supabase,info:this.rimoriInfo};if(!this.rimoriInfo)if(typeof WorkerGlobalScope<"u"){const e=Math.floor(Math.random()*1e9),t={event:{timestamp:new Date().toISOString(),eventId:e,sender:this.pluginId,topic:"global.supabase.requestAccess",data:{},debug:!1}};return new Promise(s=>{const i=self.onmessage;self.onmessage=n=>{n.data?.topic==="global.supabase.requestAccess"&&n.data?.eventId===e?(this.rimoriInfo=n.data.data,this.supabase=this.getSupabase(this.rimoriInfo.url,this.rimoriInfo.key,this.rimoriInfo.token),self.onmessage=i,s({supabase:this.supabase,info:this.rimoriInfo})):i&&i.call(self,n)},self.postMessage(t)})}else{const{data:e}=await P.request(this.pluginId,"global.supabase.requestAccess");this.rimoriInfo=e,this.supabase=this.getSupabase(this.rimoriInfo.url,this.rimoriInfo.key,this.rimoriInfo.token)}return{supabase:this.supabase,info:this.rimoriInfo}}handleRimoriInfoUpdate(e){JSON.stringify(this.rimoriInfo)!==JSON.stringify(e)&&(this.rimoriInfo=e,this.supabase=this.getSupabase(e.url,e.key,e.token),this.updateCallbacks.forEach(t=>{try{t(e)}catch(s){console.error("[RimoriCommunicationHandler] Error in update callback:",s)}}))}onUpdate(e){return this.updateCallbacks.add(e),()=>{this.updateCallbacks.delete(e)}}fetchBackend(e,t={}){if(!this.rimoriInfo)throw new Error(`[CommunicationHandler:${this.pluginId}] fetchBackend called before rimoriInfo was initialized`);const{token:s,backendUrl:i}=this.rimoriInfo,n={};typeof t.body=="string"&&(n["Content-Type"]="application/json");const o={...n,...t.headers,Authorization:`Bearer ${s}`,"plugin-id":this.pluginId};return fetch(i+e,{...t,headers:o})}}let et=class W{static instance;isProduction;logs=[];logIdCounter=0;originalConsole;constructor(e,t){this.isProduction=this.validateIsProduction(t),this.originalConsole={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug},this.overrideConsoleMethods(),this.exposeToDevTools(),this.setupNavigationClearing(),e.event.respond("logging.requestPluginLogs",async()=>{this.addLogEntry(await this.createLogEntry("info","Log capture"));const s={logs:this.logs,pluginId:e.plugin.pluginId,timestamp:new Date().toISOString()};return this.logs=[],this.logIdCounter=0,s})}static getInstance(e,t){return W.instance||(W.instance=new W(e,t)),W.instance}validateIsProduction(e){return e!==void 0?e:typeof window<"u"&&window.location.href?!window.location.href.includes("localhost"):!0}exposeToDevTools(){typeof window<"u"&&(window.getRimoriLogs=()=>this.logs)}setupNavigationClearing(){if(typeof window>"u"||typeof history>"u")return;window.addEventListener("popstate",()=>this.logs=[]);const e=history.pushState,t=history.replaceState;history.pushState=(...n)=>{e.apply(history,n),this.logs=[]},history.replaceState=(...n)=>{t.apply(history,n),this.logs=[]};let s=window.location.href;setInterval(()=>{window.location.href!==s&&(s=window.location.href,this.logs=[])},100),window.addEventListener("hashchange",()=>this.logs=[])}overrideConsoleMethods(){console.log=(...e)=>{const{location:t,style:s}=this.getCallerLocation();this.originalConsole.log(t,s,...e),this.handleConsoleCall("info",e)},console.info=(...e)=>{const{location:t,style:s}=this.getCallerLocation();this.originalConsole.info(t,s,...e),this.handleConsoleCall("info",e)},console.warn=(...e)=>{const{location:t,style:s}=this.getCallerLocation();this.originalConsole.warn(t,s,...e),this.handleConsoleCall("warn",e)},console.error=(...e)=>{const{location:t,style:s}=this.getCallerLocation();this.originalConsole.error(t,s,...e),this.handleConsoleCall("error",e)},console.debug=(...e)=>{const{location:t,style:s}=this.getCallerLocation();this.originalConsole.debug(t,s,...e),this.handleConsoleCall("debug",e)}}getCallerLocation(){const e={location:"",style:""},t="color: #0063A2; font-weight: bold;";if(this.isProduction)return e;try{const s=new Error().stack;if(!s)return e;const n=s.split(`
|
|
5
|
-
`)[3];if(!n)return e;const o=n.match(/(?:at\s+.*?\s+\()?([^/\\(]+\.(?:ts|tsx|js|jsx)):(\d+):(\d+)\)?/);if(o){const[,l,c]=o;return{style:t,location:`%c[${l}:${c}]`}}const a=n.match(/([^/\\]+\.(?:ts|tsx|js|jsx))/);return a?{style:t,location:`%c[${a[1]}]`}:e}catch{return e}}async handleConsoleCall(e,t){if(this.isProduction&&(e==="debug"||e==="info"))return;const s=t.map(o=>{if(typeof o!="object")return o;try{return JSON.stringify(o)}catch(a){return"Error adding object to log: "+a.message+" "+String(o)}}).join(" "),i=t.length>1?t.slice(1):void 0,n=await this.createLogEntry(e,s,i);this.addLogEntry(n)}getBrowserInfo(){return{userAgent:navigator.userAgent,language:navigator.language,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine,screenResolution:`${screen.width}x${screen.height}`,windowSize:`${window.innerWidth}x${window.innerHeight}`,timestamp:new Date().toISOString()}}async createLogEntry(e,t,s){const i={};return typeof window>"u"||typeof document>"u"?{id:`log_${++this.logIdCounter}_${Date.now()}`,timestamp:new Date().toISOString(),level:e,message:t,data:s}:(i.url=window.location.href,i.browserInfo=this.getBrowserInfo(),i.userAgent=i.browserInfo.userAgent,{id:`log_${++this.logIdCounter}_${Date.now()}`,timestamp:new Date().toISOString(),level:e,message:t,data:s,context:i})}addLogEntry(e){this.logs.push(e),this.logs.length>1e3&&(this.logs=this.logs.slice(-1e3))}};var le={};const p=r=>typeof r=="string",J=()=>{let r,e;const t=new Promise((s,i)=>{r=s,e=i});return t.resolve=r,t.reject=e,t},we=r=>r==null?"":""+r,tt=(r,e,t)=>{r.forEach(s=>{e[s]&&(t[s]=e[s])})},st=/###/g,ve=r=>r&&r.indexOf("###")>-1?r.replace(st,"."):r,Se=r=>!r||p(r),G=(r,e,t)=>{const s=p(e)?e.split("."):e;let i=0;for(;i<s.length-1;){if(Se(r))return{};const n=ve(s[i]);!r[n]&&t&&(r[n]=new t),Object.prototype.hasOwnProperty.call(r,n)?r=r[n]:r={},++i}return Se(r)?{}:{obj:r,k:ve(s[i])}},xe=(r,e,t)=>{const{obj:s,k:i}=G(r,e,Object);if(s!==void 0||e.length===1){s[i]=t;return}let n=e[e.length-1],o=e.slice(0,e.length-1),a=G(r,o,Object);for(;a.obj===void 0&&o.length;)n=`${o[o.length-1]}.${n}`,o=o.slice(0,o.length-1),a=G(r,o,Object),a?.obj&&typeof a.obj[`${a.k}.${n}`]<"u"&&(a.obj=void 0);a.obj[`${a.k}.${n}`]=t},it=(r,e,t,s)=>{const{obj:i,k:n}=G(r,e,Object);i[n]=i[n]||[],i[n].push(t)},se=(r,e)=>{const{obj:t,k:s}=G(r,e);if(t&&Object.prototype.hasOwnProperty.call(t,s))return t[s]},nt=(r,e,t)=>{const s=se(r,t);return s!==void 0?s:se(e,t)},Ae=(r,e,t)=>{for(const s in e)s!=="__proto__"&&s!=="constructor"&&(s in r?p(r[s])||r[s]instanceof String||p(e[s])||e[s]instanceof String?t&&(r[s]=e[s]):Ae(r[s],e[s],t):r[s]=e[s]);return r},B=r=>r.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var rt={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const ot=r=>p(r)?r.replace(/[&<>"'\/]/g,e=>rt[e]):r;class at{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const t=this.regExpMap.get(e);if(t!==void 0)return t;const s=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,s),this.regExpQueue.push(e),s}}const lt=[" ",",","?","!",";"],ct=new at(20),ht=(r,e,t)=>{e=e||"",t=t||"";const s=lt.filter(o=>e.indexOf(o)<0&&t.indexOf(o)<0);if(s.length===0)return!0;const i=ct.getRegExp(`(${s.map(o=>o==="?"?"\\?":o).join("|")})`);let n=!i.test(r);if(!n){const o=r.indexOf(t);o>0&&!i.test(r.substring(0,o))&&(n=!0)}return n},fe=(r,e,t=".")=>{if(!r)return;if(r[e])return Object.prototype.hasOwnProperty.call(r,e)?r[e]:void 0;const s=e.split(t);let i=r;for(let n=0;n<s.length;){if(!i||typeof i!="object")return;let o,a="";for(let l=n;l<s.length;++l)if(l!==n&&(a+=t),a+=s[l],o=i[a],o!==void 0){if(["string","number","boolean"].indexOf(typeof o)>-1&&l<s.length-1)continue;n+=l-n+1;break}i=o}return i},Z=r=>r?.replace(/_/g,"-"),ut={type:"logger",log(r){this.output("log",r)},warn(r){this.output("warn",r)},error(r){this.output("error",r)},output(r,e){console?.[r]?.apply?.(console,e)}};class ie{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||"i18next:",this.logger=e||ut,this.options=t,this.debug=t.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,t,s,i){return i&&!this.debug?null:(p(e[0])&&(e[0]=`${s}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new ie(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new ie(this.logger,e)}}var N=new ie;class re{constructor(){this.observers={}}on(e,t){return e.split(" ").forEach(s=>{this.observers[s]||(this.observers[s]=new Map);const i=this.observers[s].get(t)||0;this.observers[s].set(t,i+1)}),this}off(e,t){if(this.observers[e]){if(!t){delete this.observers[e];return}this.observers[e].delete(t)}}emit(e,...t){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([i,n])=>{for(let o=0;o<n;o++)i(...t)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([i,n])=>{for(let o=0;o<n;o++)i.apply(i,[e,...t])})}}class Pe extends re{constructor(e,t={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}getResource(e,t,s,i={}){const n=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,o=i.ignoreJSONStructure!==void 0?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;e.indexOf(".")>-1?a=e.split("."):(a=[e,t],s&&(Array.isArray(s)?a.push(...s):p(s)&&n?a.push(...s.split(n)):a.push(s)));const l=se(this.data,a);return!l&&!t&&!s&&e.indexOf(".")>-1&&(e=a[0],t=a[1],s=a.slice(2).join(".")),l||!o||!p(s)?l:fe(this.data?.[e]?.[t],s,n)}addResource(e,t,s,i,n={silent:!1}){const o=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let a=[e,t];s&&(a=a.concat(o?s.split(o):s)),e.indexOf(".")>-1&&(a=e.split("."),i=t,t=a[1]),this.addNamespaces(t),xe(this.data,a,i),n.silent||this.emit("added",e,t,s,i)}addResources(e,t,s,i={silent:!1}){for(const n in s)(p(s[n])||Array.isArray(s[n]))&&this.addResource(e,t,n,s[n],{silent:!0});i.silent||this.emit("added",e,t,s)}addResourceBundle(e,t,s,i,n,o={silent:!1,skipCopy:!1}){let a=[e,t];e.indexOf(".")>-1&&(a=e.split("."),i=s,s=t,t=a[1]),this.addNamespaces(t);let l=se(this.data,a)||{};o.skipCopy||(s=JSON.parse(JSON.stringify(s))),i?Ae(l,s,n):l={...l,...s},xe(this.data,a,l),o.silent||this.emit("added",e,t,s)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}hasResourceBundle(e,t){return this.getResource(e,t)!==void 0}getResourceBundle(e,t){return t||(t=this.options.defaultNS),this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(i=>t[i]&&Object.keys(t[i]).length>0)}toJSON(){return this.data}}var je={processors:{},addPostProcessor(r){this.processors[r.name]=r},handle(r,e,t,s,i){return r.forEach(n=>{e=this.processors[n]?.process(e,t,s,i)??e}),e}};const De=Symbol("i18next/PATH_KEY");function dt(){const r=[],e=Object.create(null);let t;return e.get=(s,i)=>(t?.revoke?.(),i===De?r:(r.push(i),t=Proxy.revocable(s,e),t.proxy)),Proxy.revocable(Object.create(null),e).proxy}function K(r,e){const{[De]:t}=r(dt()),s=e?.keySeparator??".",i=e?.nsSeparator??":";if(t.length>1&&i){const n=e?.ns,o=Array.isArray(n)?n:null;if(o&&o.length>1&&o.slice(1).includes(t[0]))return`${t[0]}${i}${t.slice(1).join(s)}`}return t.join(s)}const Oe={},ce=r=>!p(r)&&typeof r!="boolean"&&typeof r!="number";let Le=class Me extends re{constructor(e,t={}){super(),tt(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=N.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){const s={...t};if(e==null)return!1;const i=this.resolve(e,s);if(i?.res===void 0)return!1;const n=ce(i.res);return!(s.returnObjects===!1&&n)}extractFromKey(e,t){let s=t.nsSeparator!==void 0?t.nsSeparator:this.options.nsSeparator;s===void 0&&(s=":");const i=t.keySeparator!==void 0?t.keySeparator:this.options.keySeparator;let n=t.ns||this.options.defaultNS||[];const o=s&&e.indexOf(s)>-1,a=!this.options.userDefinedKeySeparator&&!t.keySeparator&&!this.options.userDefinedNsSeparator&&!t.nsSeparator&&!ht(e,s,i);if(o&&!a){const l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:p(n)?[n]:n};const c=e.split(s);(s!==i||s===i&&this.options.ns.indexOf(c[0])>-1)&&(n=c.shift()),e=c.join(i)}return{key:e,namespaces:p(n)?[n]:n}}translate(e,t,s){let i=typeof t=="object"?{...t}:t;if(typeof i!="object"&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i=="object"&&(i={...i}),i||(i={}),e==null)return"";typeof e=="function"&&(e=K(e,{...this.options,...i})),Array.isArray(e)||(e=[String(e)]),e=e.map(x=>typeof x=="function"?K(x,{...this.options,...i}):String(x));const n=i.returnDetails!==void 0?i.returnDetails:this.options.returnDetails,o=i.keySeparator!==void 0?i.keySeparator:this.options.keySeparator,{key:a,namespaces:l}=this.extractFromKey(e[e.length-1],i),c=l[l.length-1];let h=i.nsSeparator!==void 0?i.nsSeparator:this.options.nsSeparator;h===void 0&&(h=":");const u=i.lng||this.language,g=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(u?.toLowerCase()==="cimode")return g?n?{res:`${c}${h}${a}`,usedKey:a,exactUsedKey:a,usedLng:u,usedNS:c,usedParams:this.getUsedParamsDetails(i)}:`${c}${h}${a}`:n?{res:a,usedKey:a,exactUsedKey:a,usedLng:u,usedNS:c,usedParams:this.getUsedParamsDetails(i)}:a;const d=this.resolve(e,i);let f=d?.res;const y=d?.usedKey||a,m=d?.exactUsedKey||a,w=["[object Number]","[object Function]","[object RegExp]"],b=i.joinArrays!==void 0?i.joinArrays:this.options.joinArrays,$=!this.i18nFormat||this.i18nFormat.handleAsObject,O=i.count!==void 0&&!p(i.count),_=Me.hasDefaultValue(i),v=O?this.pluralResolver.getSuffix(u,i.count,i):"",E=i.ordinal&&O?this.pluralResolver.getSuffix(u,i.count,{ordinal:!1}):"",M=O&&!i.ordinal&&i.count===0,S=M&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${v}`]||i[`defaultValue${E}`]||i.defaultValue;let I=f;$&&!f&&_&&(I=S);const ae=ce(I),F=Object.prototype.toString.apply(I);if($&&I&&ae&&w.indexOf(F)<0&&!(p(b)&&Array.isArray(I))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const x=this.options.returnedObjectHandler?this.options.returnedObjectHandler(y,I,{...i,ns:l}):`key '${a} (${this.language})' returned an object instead of string.`;return n?(d.res=x,d.usedParams=this.getUsedParamsDetails(i),d):x}if(o){const x=Array.isArray(I),T=x?[]:{},ge=x?m:y;for(const R in I)if(Object.prototype.hasOwnProperty.call(I,R)){const A=`${ge}${o}${R}`;_&&!f?T[R]=this.translate(A,{...i,defaultValue:ce(S)?S[R]:void 0,joinArrays:!1,ns:l}):T[R]=this.translate(A,{...i,joinArrays:!1,ns:l}),T[R]===A&&(T[R]=I[R])}f=T}}else if($&&p(b)&&Array.isArray(f))f=f.join(b),f&&(f=this.extendTranslation(f,e,i,s));else{let x=!1,T=!1;!this.isValidLookup(f)&&_&&(x=!0,f=S),this.isValidLookup(f)||(T=!0,f=a);const R=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&T?void 0:f,A=_&&S!==f&&this.options.updateMissing;if(T||x||A){if(this.logger.log(A?"updateKey":"missingKey",u,c,a,A?S:f),o){const C=this.resolve(a,{...i,keySeparator:!1});C&&C.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let z=[];const X=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo==="fallback"&&X&&X[0])for(let C=0;C<X.length;C++)z.push(X[C]);else this.options.saveMissingTo==="all"?z=this.languageUtils.toResolveHierarchy(i.lng||this.language):z.push(i.lng||this.language);const pe=(C,U,V)=>{const me=_&&V!==f?V:R;this.options.missingKeyHandler?this.options.missingKeyHandler(C,c,U,me,A,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(C,c,U,me,A,i),this.emit("missingKey",C,c,U,f)};this.options.saveMissing&&(this.options.saveMissingPlurals&&O?z.forEach(C=>{const U=this.pluralResolver.getSuffixes(C,i);M&&i[`defaultValue${this.options.pluralSeparator}zero`]&&U.indexOf(`${this.options.pluralSeparator}zero`)<0&&U.push(`${this.options.pluralSeparator}zero`),U.forEach(V=>{pe([C],a+V,i[`defaultValue${V}`]||S)})}):pe(z,a,S))}f=this.extendTranslation(f,e,i,d,s),T&&f===a&&this.options.appendNamespaceToMissingKey&&(f=`${c}${h}${a}`),(T||x)&&this.options.parseMissingKeyHandler&&(f=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${h}${a}`:a,x?f:void 0,i))}return n?(d.res=f,d.usedParams=this.getUsedParamsDetails(i),d):f}extendTranslation(e,t,s,i,n){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...s},s.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!s.skipInterpolation){s.interpolation&&this.interpolator.init({...s,interpolation:{...this.options.interpolation,...s.interpolation}});const l=p(e)&&(s?.interpolation?.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let c;if(l){const u=e.match(this.interpolator.nestingRegexp);c=u&&u.length}let h=s.replace&&!p(s.replace)?s.replace:s;if(this.options.interpolation.defaultVariables&&(h={...this.options.interpolation.defaultVariables,...h}),e=this.interpolator.interpolate(e,h,s.lng||this.language||i.usedLng,s),l){const u=e.match(this.interpolator.nestingRegexp),g=u&&u.length;c<g&&(s.nest=!1)}!s.lng&&i&&i.res&&(s.lng=this.language||i.usedLng),s.nest!==!1&&(e=this.interpolator.nest(e,(...u)=>n?.[0]===u[0]&&!s.context?(this.logger.warn(`It seems you are nesting recursively key: ${u[0]} in key: ${t[0]}`),null):this.translate(...u,t),s)),s.interpolation&&this.interpolator.reset()}const o=s.postProcess||this.options.postProcess,a=p(o)?[o]:o;return e!=null&&a?.length&&s.applyPostProcessor!==!1&&(e=je.handle(a,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(s)},...s}:s,this)),e}resolve(e,t={}){let s,i,n,o,a;return p(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(l=>typeof l=="function"?K(l,{...this.options,...t}):l)),e.forEach(l=>{if(this.isValidLookup(s))return;const c=this.extractFromKey(l,t),h=c.key;i=h;let u=c.namespaces;this.options.fallbackNS&&(u=u.concat(this.options.fallbackNS));const g=t.count!==void 0&&!p(t.count),d=g&&!t.ordinal&&t.count===0,f=t.context!==void 0&&(p(t.context)||typeof t.context=="number")&&t.context!=="",y=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);u.forEach(m=>{this.isValidLookup(s)||(a=m,!Oe[`${y[0]}-${m}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(a)&&(Oe[`${y[0]}-${m}`]=!0,this.logger.warn(`key "${i}" for languages "${y.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),y.forEach(w=>{if(this.isValidLookup(s))return;o=w;const b=[h];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(b,h,w,m,t);else{let O;g&&(O=this.pluralResolver.getSuffix(w,t.count,t));const _=`${this.options.pluralSeparator}zero`,v=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(g&&(t.ordinal&&O.indexOf(v)===0&&b.push(h+O.replace(v,this.options.pluralSeparator)),b.push(h+O),d&&b.push(h+_)),f){const E=`${h}${this.options.contextSeparator||"_"}${t.context}`;b.push(E),g&&(t.ordinal&&O.indexOf(v)===0&&b.push(E+O.replace(v,this.options.pluralSeparator)),b.push(E+O),d&&b.push(E+_))}}let $;for(;$=b.pop();)this.isValidLookup(s)||(n=$,s=this.getResource(w,m,$,t))}))})}),{res:s,usedKey:i,exactUsedKey:n,usedLng:o,usedNS:a}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,t,s,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,s,i):this.resourceStore.getResource(e,t,s,i)}getUsedParamsDetails(e={}){const t=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],s=e.replace&&!p(e.replace);let i=s?e.replace:e;if(s&&typeof e.count<"u"&&(i.count=e.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!s){i={...i};for(const n of t)delete i[n]}return i}static hasDefaultValue(e){const t="defaultValue";for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t===s.substring(0,t.length)&&e[s]!==void 0)return!0;return!1}};class Ie{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=N.create("languageUtils")}getScriptPartFromCode(e){if(e=Z(e),!e||e.indexOf("-")<0)return null;const t=e.split("-");return t.length===2||(t.pop(),t[t.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(t.join("-"))}getLanguagePartFromCode(e){if(e=Z(e),!e||e.indexOf("-")<0)return e;const t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(p(e)&&e.indexOf("-")>-1){let t;try{t=Intl.getCanonicalLocales(e)[0]}catch{}return t&&this.options.lowerCaseLng&&(t=t.toLowerCase()),t||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach(s=>{if(t)return;const i=this.formatLanguageCode(s);(!this.options.supportedLngs||this.isSupportedCode(i))&&(t=i)}),!t&&this.options.supportedLngs&&e.forEach(s=>{if(t)return;const i=this.getScriptPartFromCode(s);if(this.isSupportedCode(i))return t=i;const n=this.getLanguagePartFromCode(s);if(this.isSupportedCode(n))return t=n;t=this.options.supportedLngs.find(o=>{if(o===n)return o;if(!(o.indexOf("-")<0&&n.indexOf("-")<0)&&(o.indexOf("-")>0&&n.indexOf("-")<0&&o.substring(0,o.indexOf("-"))===n||o.indexOf(n)===0&&n.length>1))return o})}),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t}getFallbackCodes(e,t){if(!e)return[];if(typeof e=="function"&&(e=e(t)),p(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let s=e[t];return s||(s=e[this.getScriptPartFromCode(t)]),s||(s=e[this.formatLanguageCode(t)]),s||(s=e[this.getLanguagePartFromCode(t)]),s||(s=e.default),s||[]}toResolveHierarchy(e,t){const s=this.getFallbackCodes((t===!1?[]:t)||this.options.fallbackLng||[],e),i=[],n=o=>{o&&(this.isSupportedCode(o)?i.push(o):this.logger.warn(`rejecting language code not found in supportedLngs: ${o}`))};return p(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&n(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&n(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&n(this.getLanguagePartFromCode(e))):p(e)&&n(this.formatLanguageCode(e)),s.forEach(o=>{i.indexOf(o)<0&&n(this.formatLanguageCode(o))}),i}}const ke={zero:0,one:1,two:2,few:3,many:4,other:5},Ce={select:r=>r===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class ft{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=N.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){const s=Z(e==="dev"?"en":e),i=t.ordinal?"ordinal":"cardinal",n=JSON.stringify({cleanedCode:s,type:i});if(n in this.pluralRulesCache)return this.pluralRulesCache[n];let o;try{o=new Intl.PluralRules(s,{type:i})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Ce;if(!e.match(/-|_/))return Ce;const l=this.languageUtils.getLanguagePartFromCode(e);o=this.getRule(l,t)}return this.pluralRulesCache[n]=o,o}needsPlural(e,t={}){let s=this.getRule(e,t);return s||(s=this.getRule("dev",t)),s?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,t,s={}){return this.getSuffixes(e,s).map(i=>`${t}${i}`)}getSuffixes(e,t={}){let s=this.getRule(e,t);return s||(s=this.getRule("dev",t)),s?s.resolvedOptions().pluralCategories.sort((i,n)=>ke[i]-ke[n]).map(i=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${i}`):[]}getSuffix(e,t,s={}){const i=this.getRule(e,s);return i?`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${i.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",t,s))}}const Ee=(r,e,t,s=".",i=!0)=>{let n=nt(r,e,t);return!n&&i&&p(t)&&(n=fe(r,t,s),n===void 0&&(n=fe(e,t,s))),n},he=r=>r.replace(/\$/g,"$$$$");class Te{constructor(e={}){this.logger=N.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(t=>t),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:t,escapeValue:s,useRawValueToEscape:i,prefix:n,prefixEscaped:o,suffix:a,suffixEscaped:l,formatSeparator:c,unescapeSuffix:h,unescapePrefix:u,nestingPrefix:g,nestingPrefixEscaped:d,nestingSuffix:f,nestingSuffixEscaped:y,nestingOptionsSeparator:m,maxReplaces:w,alwaysFormat:b}=e.interpolation;this.escape=t!==void 0?t:ot,this.escapeValue=s!==void 0?s:!0,this.useRawValueToEscape=i!==void 0?i:!1,this.prefix=n?B(n):o||"{{",this.suffix=a?B(a):l||"}}",this.formatSeparator=c||",",this.unescapePrefix=h?"":u||"-",this.unescapeSuffix=this.unescapePrefix?"":h||"",this.nestingPrefix=g?B(g):d||B("$t("),this.nestingSuffix=f?B(f):y||B(")"),this.nestingOptionsSeparator=m||",",this.maxReplaces=w||1e3,this.alwaysFormat=b!==void 0?b:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(t,s)=>t?.source===s?(t.lastIndex=0,t):new RegExp(s,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,t,s,i){let n,o,a;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=d=>{if(d.indexOf(this.formatSeparator)<0){const w=Ee(t,l,d,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(w,void 0,s,{...i,...t,interpolationkey:d}):w}const f=d.split(this.formatSeparator),y=f.shift().trim(),m=f.join(this.formatSeparator).trim();return this.format(Ee(t,l,y,this.options.keySeparator,this.options.ignoreJSONStructure),m,s,{...i,...t,interpolationkey:y})};this.resetRegExp();const h=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,u=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:d=>he(d)},{regex:this.regexp,safeValue:d=>this.escapeValue?he(this.escape(d)):he(d)}].forEach(d=>{for(a=0;n=d.regex.exec(e);){const f=n[1].trim();if(o=c(f),o===void 0)if(typeof h=="function"){const m=h(e,n,i);o=p(m)?m:""}else if(i&&Object.prototype.hasOwnProperty.call(i,f))o="";else if(u){o=n[0];continue}else this.logger.warn(`missed to pass in variable ${f} for interpolating ${e}`),o="";else!p(o)&&!this.useRawValueToEscape&&(o=we(o));const y=d.safeValue(o);if(e=e.replace(n[0],y),u?(d.regex.lastIndex+=o.length,d.regex.lastIndex-=n[0].length):d.regex.lastIndex=0,a++,a>=this.maxReplaces)break}}),e}nest(e,t,s={}){let i,n,o;const a=(l,c)=>{const h=this.nestingOptionsSeparator;if(l.indexOf(h)<0)return l;const u=l.split(new RegExp(`${B(h)}[ ]*{`));let g=`{${u[1]}`;l=u[0],g=this.interpolate(g,o);const d=g.match(/'/g),f=g.match(/"/g);((d?.length??0)%2===0&&!f||(f?.length??0)%2!==0)&&(g=g.replace(/'/g,'"'));try{o=JSON.parse(g),c&&(o={...c,...o})}catch(y){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,y),`${l}${h}${g}`}return o.defaultValue&&o.defaultValue.indexOf(this.prefix)>-1&&delete o.defaultValue,l};for(;i=this.nestingRegexp.exec(e);){let l=[];o={...s},o=o.replace&&!p(o.replace)?o.replace:o,o.applyPostProcessor=!1,delete o.defaultValue;const c=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(c!==-1&&(l=i[1].slice(c).split(this.formatSeparator).map(h=>h.trim()).filter(Boolean),i[1]=i[1].slice(0,c)),n=t(a.call(this,i[1].trim(),o),o),n&&i[0]===e&&!p(n))return n;p(n)||(n=we(n)),n||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${e}`),n=""),l.length&&(n=l.reduce((h,u)=>this.format(h,u,s.lng,{...s,interpolationkey:i[1].trim()}),n.trim())),e=e.replace(i[0],n),this.regexp.lastIndex=0}return e}}const gt=r=>{let e=r.toLowerCase().trim();const t={};if(r.indexOf("(")>-1){const s=r.split("(");e=s[0].toLowerCase().trim();const i=s[1].substring(0,s[1].length-1);e==="currency"&&i.indexOf(":")<0?t.currency||(t.currency=i.trim()):e==="relativetime"&&i.indexOf(":")<0?t.range||(t.range=i.trim()):i.split(";").forEach(o=>{if(o){const[a,...l]=o.split(":"),c=l.join(":").trim().replace(/^'+|'+$/g,""),h=a.trim();t[h]||(t[h]=c),c==="false"&&(t[h]=!1),c==="true"&&(t[h]=!0),isNaN(c)||(t[h]=parseInt(c,10))}})}return{formatName:e,formatOptions:t}},$e=r=>{const e={};return(t,s,i)=>{let n=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(n={...n,[i.interpolationkey]:void 0});const o=s+JSON.stringify(n);let a=e[o];return a||(a=r(Z(s),i),e[o]=a),a(t)}},pt=r=>(e,t,s)=>r(Z(t),s)(e);class mt{constructor(e={}){this.logger=N.create("formatter"),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||",";const s=t.cacheInBuiltFormats?$e:pt;this.formats={number:s((i,n)=>{const o=new Intl.NumberFormat(i,{...n});return a=>o.format(a)}),currency:s((i,n)=>{const o=new Intl.NumberFormat(i,{...n,style:"currency"});return a=>o.format(a)}),datetime:s((i,n)=>{const o=new Intl.DateTimeFormat(i,{...n});return a=>o.format(a)}),relativetime:s((i,n)=>{const o=new Intl.RelativeTimeFormat(i,{...n});return a=>o.format(a,n.range||"day")}),list:s((i,n)=>{const o=new Intl.ListFormat(i,{...n});return a=>o.format(a)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=$e(t)}format(e,t,s,i={}){const n=t.split(this.formatSeparator);if(n.length>1&&n[0].indexOf("(")>1&&n[0].indexOf(")")<0&&n.find(a=>a.indexOf(")")>-1)){const a=n.findIndex(l=>l.indexOf(")")>-1);n[0]=[n[0],...n.splice(1,a)].join(this.formatSeparator)}return n.reduce((a,l)=>{const{formatName:c,formatOptions:h}=gt(l);if(this.formats[c]){let u=a;try{const g=i?.formatParams?.[i.interpolationkey]||{},d=g.locale||g.lng||i.locale||i.lng||s;u=this.formats[c](a,d,{...h,...i,...g})}catch(g){this.logger.warn(g)}return u}else this.logger.warn(`there was no format function for ${c}`);return a},e)}}const yt=(r,e)=>{r.pending[e]!==void 0&&(delete r.pending[e],r.pendingCount--)};class bt extends re{constructor(e,t,s,i={}){super(),this.backend=e,this.store=t,this.services=s,this.languageUtils=s.languageUtils,this.options=i,this.logger=N.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(s,i.backend,i)}queueLoad(e,t,s,i){const n={},o={},a={},l={};return e.forEach(c=>{let h=!0;t.forEach(u=>{const g=`${c}|${u}`;!s.reload&&this.store.hasResourceBundle(c,u)?this.state[g]=2:this.state[g]<0||(this.state[g]===1?o[g]===void 0&&(o[g]=!0):(this.state[g]=1,h=!1,o[g]===void 0&&(o[g]=!0),n[g]===void 0&&(n[g]=!0),l[u]===void 0&&(l[u]=!0)))}),h||(a[c]=!0)}),(Object.keys(n).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(n),pending:Object.keys(o),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(l)}}loaded(e,t,s){const i=e.split("|"),n=i[0],o=i[1];t&&this.emit("failedLoading",n,o,t),!t&&s&&this.store.addResourceBundle(n,o,s,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&s&&(this.state[e]=0);const a={};this.queue.forEach(l=>{it(l.loaded,[n],o),yt(l,e),t&&l.errors.push(t),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(c=>{a[c]||(a[c]={});const h=l.loaded[c];h.length&&h.forEach(u=>{a[c][u]===void 0&&(a[c][u]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",a),this.queue=this.queue.filter(l=>!l.done)}read(e,t,s,i=0,n=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:t,fcName:s,tried:i,wait:n,callback:o});return}this.readingCalls++;const a=(c,h)=>{if(this.readingCalls--,this.waitingReads.length>0){const u=this.waitingReads.shift();this.read(u.lng,u.ns,u.fcName,u.tried,u.wait,u.callback)}if(c&&h&&i<this.maxRetries){setTimeout(()=>{this.read.call(this,e,t,s,i+1,n*2,o)},n);return}o(c,h)},l=this.backend[s].bind(this.backend);if(l.length===2){try{const c=l(e,t);c&&typeof c.then=="function"?c.then(h=>a(null,h)).catch(a):a(null,c)}catch(c){a(c)}return}return l(e,t,a)}prepareLoading(e,t,s={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();p(e)&&(e=this.languageUtils.toResolveHierarchy(e)),p(t)&&(t=[t]);const n=this.queueLoad(e,t,s,i);if(!n.toLoad.length)return n.pending.length||i(),null;n.toLoad.forEach(o=>{this.loadOne(o)})}load(e,t,s){this.prepareLoading(e,t,{},s)}reload(e,t,s){this.prepareLoading(e,t,{reload:!0},s)}loadOne(e,t=""){const s=e.split("|"),i=s[0],n=s[1];this.read(i,n,"read",void 0,void 0,(o,a)=>{o&&this.logger.warn(`${t}loading namespace ${n} for language ${i} failed`,o),!o&&a&&this.logger.log(`${t}loaded namespace ${n} for language ${i}`,a),this.loaded(e,o,a)})}saveMissing(e,t,s,i,n,o={},a=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(t)){this.logger.warn(`did not save key "${s}" as the namespace "${t}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(s==null||s==="")){if(this.backend?.create){const l={...o,isUpdate:n},c=this.backend.create.bind(this.backend);if(c.length<6)try{let h;c.length===5?h=c(e,t,s,i,l):h=c(e,t,s,i),h&&typeof h.then=="function"?h.then(u=>a(null,u)).catch(a):a(null,h)}catch(h){a(h)}else c(e,t,s,i,a,l)}!e||!e[0]||this.store.addResource(e[0],t,s,i)}}}const ue=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:r=>{let e={};if(typeof r[1]=="object"&&(e=r[1]),p(r[1])&&(e.defaultValue=r[1]),p(r[2])&&(e.tDescription=r[2]),typeof r[2]=="object"||typeof r[3]=="object"){const t=r[3]||r[2];Object.keys(t).forEach(s=>{e[s]=t[s]})}return e},interpolation:{escapeValue:!0,format:r=>r,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),_e=r=>(p(r.ns)&&(r.ns=[r.ns]),p(r.fallbackLng)&&(r.fallbackLng=[r.fallbackLng]),p(r.fallbackNS)&&(r.fallbackNS=[r.fallbackNS]),r.supportedLngs?.indexOf?.("cimode")<0&&(r.supportedLngs=r.supportedLngs.concat(["cimode"])),typeof r.initImmediate=="boolean"&&(r.initAsync=r.initImmediate),r),te=()=>{},wt=r=>{Object.getOwnPropertyNames(Object.getPrototypeOf(r)).forEach(t=>{typeof r[t]=="function"&&(r[t]=r[t].bind(r))})},Fe="__i18next_supportNoticeShown",vt=()=>!!(typeof globalThis<"u"&&globalThis[Fe]||typeof process<"u"&&le&&le.I18NEXT_NO_SUPPORT_NOTICE||typeof process<"u"&&le),St=()=>{typeof globalThis<"u"&&(globalThis[Fe]=!0)},xt=r=>!!(r?.modules?.backend?.name?.indexOf("Locize")>0||r?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||r?.options?.backend?.backends&&r.options.backend.backends.some(e=>e?.name?.indexOf("Locize")>0||e?.constructor?.name?.indexOf("Locize")>0)||r?.options?.backend?.projectId||r?.options?.backend?.backendOptions&&r.options.backend.backendOptions.some(e=>e?.projectId));class Q extends re{constructor(e={},t){if(super(),this.options=_e(e),this.services={},this.logger=N,this.modules={external:[]},wt(this),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(e={},t){this.isInitializing=!0,typeof e=="function"&&(t=e,e={}),e.defaultNS==null&&e.ns&&(p(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const s=ue();this.options={...s,...this.options,..._e(e)},this.options.interpolation={...s.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=s.overloadTranslationOptionHandler),this.options.showSupportNotice!==!1&&!xt(this)&&!vt()&&(typeof console<"u"&&typeof console.info<"u"&&console.info("🌐 i18next is made possible by our own product, Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙"),St());const i=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){this.modules.logger?N.init(i(this.modules.logger),this.options):N.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:c=mt;const h=new Ie(this.options);this.store=new Pe(this.options.resources,this.options);const u=this.services;u.logger=N,u.resourceStore=this.store,u.languageUtils=h,u.pluralResolver=new ft(h,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==s.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),c&&(!this.options.interpolation.format||this.options.interpolation.format===s.interpolation.format)&&(u.formatter=i(c),u.formatter.init&&u.formatter.init(u,this.options),this.options.interpolation.format=u.formatter.format.bind(u.formatter)),u.interpolator=new Te(this.options),u.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},u.backendConnector=new bt(i(this.modules.backend),u.resourceStore,u,this.options),u.backendConnector.on("*",(d,...f)=>{this.emit(d,...f)}),this.modules.languageDetector&&(u.languageDetector=i(this.modules.languageDetector),u.languageDetector.init&&u.languageDetector.init(u,this.options.detection,this.options)),this.modules.i18nFormat&&(u.i18nFormat=i(this.modules.i18nFormat),u.i18nFormat.init&&u.i18nFormat.init(this)),this.translator=new Le(this.services,this.options),this.translator.on("*",(d,...f)=>{this.emit(d,...f)}),this.modules.external.forEach(d=>{d.init&&d.init(this)})}if(this.format=this.options.interpolation.format,t||(t=te),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=(...h)=>this.store[c](...h)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=(...h)=>(this.store[c](...h),this)});const a=J(),l=()=>{const c=(h,u)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(u),t(h,u)};if(this.languages&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),a}loadResources(e,t=te){let s=t;const i=p(e)?e:this.language;if(typeof e=="function"&&(s=e),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return s();const n=[],o=a=>{if(!a||a==="cimode")return;this.services.languageUtils.toResolveHierarchy(a).forEach(c=>{c!=="cimode"&&n.indexOf(c)<0&&n.push(c)})};i?o(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(l=>o(l)),this.options.preload?.forEach?.(a=>o(a)),this.services.backendConnector.load(n,this.options.ns,a=>{!a&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),s(a)})}else s(null)}reloadResources(e,t,s){const i=J();return typeof e=="function"&&(s=e,e=void 0),typeof t=="function"&&(s=t,t=void 0),e||(e=this.languages),t||(t=this.options.ns),s||(s=te),this.services.backendConnector.reload(e,t,n=>{i.resolve(),s(n)}),i}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&je.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!(["cimode","dev"].indexOf(e)>-1)){for(let t=0;t<this.languages.length;t++){const s=this.languages[t];if(!(["cimode","dev"].indexOf(s)>-1)&&this.store.hasLanguageSomeTranslations(s)){this.resolvedLanguage=s;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,t){this.isLanguageChangingTo=e;const s=J();this.emit("languageChanging",e);const i=a=>{this.language=a,this.languages=this.services.languageUtils.toResolveHierarchy(a),this.resolvedLanguage=void 0,this.setResolvedLanguage(a)},n=(a,l)=>{l?this.isLanguageChangingTo===e&&(i(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,s.resolve((...c)=>this.t(...c)),t&&t(a,(...c)=>this.t(...c))},o=a=>{!e&&!a&&this.services.languageDetector&&(a=[]);const l=p(a)?a:a&&a[0],c=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(p(a)?[a]:a);c&&(this.language||i(c),this.translator.language||this.translator.changeLanguage(c),this.services.languageDetector?.cacheUserLanguage?.(c)),this.loadResources(c,h=>{n(h,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?o(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(e),s}getFixedT(e,t,s){const i=(n,o,...a)=>{let l;typeof o!="object"?l=this.options.overloadTranslationOptionHandler([n,o].concat(a)):l={...o},l.lng=l.lng||i.lng,l.lngs=l.lngs||i.lngs,l.ns=l.ns||i.ns,l.keyPrefix!==""&&(l.keyPrefix=l.keyPrefix||s||i.keyPrefix);const c={...this.options,...l};typeof l.keyPrefix=="function"&&(l.keyPrefix=K(l.keyPrefix,c));const h=this.options.keySeparator||".";let u;return l.keyPrefix&&Array.isArray(n)?u=n.map(g=>(typeof g=="function"&&(g=K(g,c)),`${l.keyPrefix}${h}${g}`)):(typeof n=="function"&&(n=K(n,c)),u=l.keyPrefix?`${l.keyPrefix}${h}${n}`:n),this.t(u,l)};return p(e)?i.lng=e:i.lngs=e,i.ns=t,i.keyPrefix=s,i}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const s=t.lng||this.resolvedLanguage||this.languages[0],i=this.options?this.options.fallbackLng:!1,n=this.languages[this.languages.length-1];if(s.toLowerCase()==="cimode")return!0;const o=(a,l)=>{const c=this.services.backendConnector.state[`${a}|${l}`];return c===-1||c===0||c===2};if(t.precheck){const a=t.precheck(this,o);if(a!==void 0)return a}return!!(this.hasResourceBundle(s,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(s,e)&&(!i||o(n,e)))}loadNamespaces(e,t){const s=J();return this.options.ns?(p(e)&&(e=[e]),e.forEach(i=>{this.options.ns.indexOf(i)<0&&this.options.ns.push(i)}),this.loadResources(i=>{s.resolve(),t&&t(i)}),s):(t&&t(),Promise.resolve())}loadLanguages(e,t){const s=J();p(e)&&(e=[e]);const i=this.options.preload||[],n=e.filter(o=>i.indexOf(o)<0&&this.services.languageUtils.isSupportedCode(o));return n.length?(this.options.preload=i.concat(n),this.loadResources(o=>{s.resolve(),t&&t(o)}),s):(t&&t(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const i=new Intl.Locale(e);if(i&&i.getTextInfo){const n=i.getTextInfo();if(n&&n.direction)return n.direction}}catch{}const t=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],s=this.services?.languageUtils||new Ie(ue());return e.toLowerCase().indexOf("-latn")>1?"ltr":t.indexOf(s.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},t){const s=new Q(e,t);return s.createInstance=Q.createInstance,s}cloneInstance(e={},t=te){const s=e.forkResourceStore;s&&delete e.forkResourceStore;const i={...this.options,...e,isClone:!0},n=new Q(i);if((e.debug!==void 0||e.prefix!==void 0)&&(n.logger=n.logger.clone(e)),["store","services","language"].forEach(a=>{n[a]=this[a]}),n.services={...this.services},n.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},s){const a=Object.keys(this.store.data).reduce((l,c)=>(l[c]={...this.store.data[c]},l[c]=Object.keys(l[c]).reduce((h,u)=>(h[u]={...l[c][u]},h),l[c]),l),{});n.store=new Pe(a,i),n.services.resourceStore=n.store}if(e.interpolation){const l={...ue().interpolation,...this.options.interpolation,...e.interpolation},c={...i,interpolation:l};n.services.interpolator=new Te(c)}return n.translator=new Le(n.services,i),n.translator.on("*",(a,...l)=>{n.emit(a,...l)}),n.init(i,t),n.translator.options=i,n.translator.backendConnector.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},n}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const k=Q.createInstance(),Pt=k.createInstance;k.dir;k.init;k.loadResources;k.reloadResources;k.use;k.changeLanguage;k.getFixedT;k.t;k.exists;k.setDefaultNamespace;k.hasLoadedNamespace;k.loadNamespaces;k.loadLanguages;class Ue{currentLanguage;initializationState;initializationPromise;i18n;translationUrl;ai;aiTranslationCache=new Map;aiTranslationPending=new Map;constructor(e,t,s){this.currentLanguage=e,this.initializationState="not-inited",this.initializationPromise=null,this.translationUrl=t,this.ai=s}async initialize(){if(this.initializationState!=="finished")return this.initializationState==="initing"&&this.initializationPromise?this.initializationPromise:(this.initializationState="initing",this.initializationPromise=(async()=>{try{const e=await this.fetchTranslations(this.currentLanguage),t=Pt({lng:this.currentLanguage,resources:{[this.currentLanguage]:{translation:e}},debug:!1,showSupportNotice:!1,parseMissingKeyHandler:(s,i)=>s.trim()?this.isTranslationKey(s)?(console.warn(`Translation key not found: ${s}`),i??""):(this.fetchTranslation(s).then(n=>{this.i18n?.addResource(this.currentLanguage,"translation",s,n),this.i18n?.emit("languageChanged")}),s):""});await t.init(),this.i18n=t,this.initializationState="finished"}catch(e){throw this.initializationState="not-inited",this.initializationPromise=null,e}})(),this.initializationPromise)}getTranslationUrl(e){return`${(this.translationUrl||window.location.origin).replace(/\/+$/,"")}/locales/${e}.json`}usePlugin(e){if(!this.i18n)throw new Error("Translator is not initialized");this.i18n.use(e)}onLanguageChanged(e){if(!this.i18n)throw new Error("Translator is not initialized");this.i18n.on("languageChanged",e)}async fetchTranslations(e,t=0){try{const s=await fetch(this.getTranslationUrl(e));if(!s.ok)throw new Error(`Failed to fetch translations for ${e}: ${s.status}`);const i=await s.json();return Object.keys(i).length===0&&t===0?(await new Promise(n=>setTimeout(n,300)),this.fetchTranslations(e,1)):i}catch(s){return t===0?(await new Promise(i=>setTimeout(i,300)),this.fetchTranslations(e,1)):(console.warn(`Fetching of ${e} translation not possible. Falling back to english. Error details: `+s.message),e==="en"?{}:this.fetchTranslations("en").catch(i=>(console.error("Failed to fetch fallback translations:",i),{})))}}t(e,t){if(!this.i18n)throw new Error("Translator is not initialized");return this.i18n.t(e,t)}getCurrentLanguage(){return this.currentLanguage}isReady(){return this.initializationState==="finished"}isTranslationKey(e){return/^[^\s.]+(\.[^\s.]+)+$/.test(e)}async fetchTranslation(e,t){const s=this.aiTranslationCache.get(e);if(s)return s;const i=this.aiTranslationPending.get(e);if(i)return i;if(!this.ai||this.currentLanguage==="en")return e;const n=(async()=>{try{const a=(await this.ai.getObject({prompt:"global.translator.translate",variables:{additionalInstructions:t??"",language:this.currentLanguage,text:e},cache:!0}))?.translation;if(a)return this.aiTranslationCache.set(e,a),a}catch(o){console.warn("Failed to translate freeform text:",{text:e,error:o})}finally{this.aiTranslationPending.delete(e)}return e})();return this.aiTranslationPending.set(e,n),n}}class Ot{pluginId;rimoriInfo;translator;supabase;communicationHandler;releaseChannel;applicationMode;theme;ttsEnabled=!0;constructor(e,t,s,i){this.rimoriInfo=s,this.supabase=e,this.pluginId=s.pluginId,this.releaseChannel=s.releaseChannel,this.communicationHandler=t;const n=s.installedPlugins.find(o=>o.id===s.pluginId);this.translator=new Ue(s.interfaceLanguage,n?.endpoint||"",i),this.ttsEnabled=s.ttsEnabled??!0,this.communicationHandler.onUpdate(o=>{this.rimoriInfo=o,this.ttsEnabled=o.ttsEnabled??!0}),this.applicationMode=this.communicationHandler.getQueryParam("applicationMode"),this.theme=this.communicationHandler.getQueryParam("rm_theme")||"light"}async fetchSettings(){const e=!this.rimoriInfo.guild.allowUserPluginSettings,{data:t}=await this.supabase.schema("public").from("plugin_settings").select("*").eq("plugin_id",this.pluginId).eq("guild_id",this.rimoriInfo.guild.id).eq("is_guild_setting",e).maybeSingle();return t?.settings??null}async setSettings(e){const t=!this.rimoriInfo.guild.allowUserPluginSettings,s={plugin_id:this.pluginId,settings:e,guild_id:this.rimoriInfo.guild.id,is_guild_setting:t};t&&(s.user_id=null);const i=this.supabase.schema("public").from("plugin_settings").update({settings:e}).eq("plugin_id",this.pluginId).eq("guild_id",this.rimoriInfo.guild.id).eq("is_guild_setting",t),{data:n,error:o}=await(t?i.is("user_id",null).select():i.select());if(o&&(o.code==="42501"||o.message?.includes("policy")))throw new Error(`Cannot set ${t?"guild":"user"} settings: Permission denied.`);if(n&&n.length>0)return;const{error:a}=await this.supabase.schema("public").from("plugin_settings").insert(s);if(a){if(a.code==="23505"){const l=this.supabase.schema("public").from("plugin_settings").update({settings:e}).eq("plugin_id",this.pluginId).eq("guild_id",this.rimoriInfo.guild.id).eq("is_guild_setting",t),{error:c}=await(t?l.is("user_id",null):l);if(!c)return}throw a}}async getSettings(e){const t=await this.fetchSettings();if(!t)return await this.setSettings(e),e;const s=Object.keys(t),i=Object.keys(e);if(s.length!==i.length){const n=Object.fromEntries(Object.entries(t).filter(([a])=>i.includes(a))),o={...e,...n};return await this.setSettings(o),o}return t}getUserInfo(){return this.rimoriInfo.profile}getGuildInfo(){return{id:this.rimoriInfo.guild.id,name:this.rimoriInfo.guild.name,description:this.rimoriInfo.guild.description,isShadowGuild:this.rimoriInfo.guild.isShadowGuild}}onRimoriInfoUpdate(e){return this.communicationHandler.onUpdate(e)}getPluginInfo(){return{installedPlugins:this.rimoriInfo.installedPlugins,mainPanelPlugin:this.rimoriInfo.mainPanelPlugin,sidePanelPlugin:this.rimoriInfo.sidePanelPlugin}}async getTranslator(){return await this.translator.initialize(),this.translator}}const Lt=["anonymous","free","standard","premium","early_access"],It=["user","plugin_moderator","lang_moderator","admin"];class kt{supabase;communicationHandler;tablePrefix;schema;constructor(e,t,s){this.supabase=e,this.communicationHandler=t,this.tablePrefix=s.tablePrefix,this.schema=s.dbSchema,t.onUpdate(i=>{this.tablePrefix=i.tablePrefix,this.schema=i.dbSchema})}from(e){const t=this.getTableName(e);return e.startsWith("global_")?this.supabase.schema("public").from(t):this.supabase.schema(this.schema).from(t)}getTableName(e){if(/[A-Z]/.test(e))throw new Error("Table name cannot include uppercase letters. Please use snake_case for table names.");return e.startsWith("global_")?e.replace("global_",""):this.tablePrefix+"_"+e}async setPublicity(e,t,s){const i=this.getTableName(e);await this.communicationHandler.fetchBackend("/db-entry/publicity",{method:"POST",body:JSON.stringify({table_name:i,schema:this.schema,entry_id:t,publicity:s})})}async vectorSearch(e){const t=await this.communicationHandler.fetchBackend("/plugin-search/vector-search",{method:"POST",body:JSON.stringify(e)});if(!t.ok)throw new Error(`Vector search failed: ${t.statusText}`);return await t.json()}}const Ct=["reading","listening","speaking","writing","learning","community"];class Et{pluginId;eventBus;constructor(e,t){this.pluginId=e,this.eventBus=t??P}emitAccomplishment(e){const t={...e,type:"durationMinutes"in e?"macro":"micro"};if(!this.validateAccomplishment(t))return;const s=this.sanitizeAccomplishment(t),i="global.accomplishment.trigger"+(t.type==="macro"?"Macro":"Micro");this.eventBus.emit(this.pluginId,i,s)}validateAccomplishment(e){if(!Ct.includes(e.skillCategory))throw new Error(`Invalid skill category: ${e.skillCategory}`);if(!/^[0-9a-z_.-]+$/.test(e.accomplishmentKeyword))throw new Error(`The accomplishment keyword: ${e.accomplishmentKeyword} is invalid. Only lowercase letters, minuses, underscores and periods are allowed`);if(e.description.length<10)throw new Error("Description is too short");if(!["micro","macro"].includes(e.type))throw new Error("Invalid accomplishment type "+e.type);if(e.type==="macro"&&(e.errorRatio<0||e.errorRatio>1))throw new Error("The error ratio must be between 0 and 1");return!0}sanitizeAccomplishment(e){return e.description=e.description.replace(/[^\x20-\x7E]/g,""),e.meta?.forEach(t=>{t.description=t.description.replace(/[^\x20-\x7E]/g,"")}),e.meta?.forEach(t=>{t.key=t.key.replace(/([A-Z])/g,"_$1").toLowerCase()}),e}getDecoupledTopic(e){const[t,s,i]=e.split(".");return{plugin:t||"*",skillCategory:s||"*",accomplishmentKeyword:i||"*"}}subscribe(e="*",t){typeof e=="string"&&(e=[e]),e.forEach(s=>{const i=s.split(".").length;if(i===1)s+=".*.*";else if(i===2)s+=".*";else if(i!==3)throw new Error("Invalid accomplishment topic pattern. The pattern must be plugin.skillCategory.accomplishmentKeyword or an * as wildcard for any plugin, skill category or accomplishment keyword");this.eventBus.on(["global.accomplishment.triggerMicro","global.accomplishment.triggerMacro"],n=>{const{plugin:o,skillCategory:a,accomplishmentKeyword:l}=this.getDecoupledTopic(s);o!=="*"&&n.sender!==o||a!=="*"&&n.data.skillCategory!==a||l!=="*"&&n.data.accomplishmentKeyword!==l||t(n)},[this.pluginId])})}}class Tt{pluginId;accomplishmentController;aiModule;eventBus;constructor(e,t,s){this.pluginId=e,this.aiModule=t,this.eventBus=s??P,this.accomplishmentController=new Et(e,this.eventBus),this.eventBus.on(["global.session.triggerUpdate"],i=>{i.data.session_token?this.aiModule.session.set(i.data.session_token):this.aiModule.session.clear()})}getGlobalEventTopic(e){if(e.startsWith("global.")||e.startsWith("self."))return e;const t=e.split(".");if(t.length===3){if(!t[0].startsWith("pl")&&t[0]!=="global")throw new Error(`Invalid event topic '${e}'. The topic must start with the plugin id, 'self' or 'global'.`);return e}else if(t.length>3)throw new Error(`The event topic must consist of 3 parts. <pluginId>.<topic area>.<action>. Received: ${e}`);return`${this.pluginId??"global"}.${e}`}emit(e,t,s){const i=this.getGlobalEventTopic(e);this.eventBus.emit(this.pluginId,i,t,s)}async request(e,t){const s=this.getGlobalEventTopic(e),i=this.aiModule.session.get()??void 0;return this.eventBus.request(this.pluginId,s,t,i)}on(e,t){const s=Array.isArray(e)?e:[e];return this.eventBus.on(s.map(i=>this.getGlobalEventTopic(i)),i=>{i.ai_session_token&&!this.aiModule.session.get()&&this.aiModule.session.set(i.ai_session_token),t(i)})}once(e,t){this.eventBus.once(this.getGlobalEventTopic(e),t)}respond(e,t){const s=Array.isArray(e)?e:[e];let i=t;typeof t=="function"&&(i=async n=>{const o=this.aiModule.session.get();n.ai_session_token&&this.aiModule.session.set(n.ai_session_token);try{return await t(n)}finally{n.ai_session_token&&(o?this.aiModule.session.set(o):this.aiModule.session.clear())}}),this.eventBus.respond(this.pluginId,s.map(n=>this.getGlobalEventTopic(n)),i)}async emitAccomplishment(e){this.accomplishmentController.emitAccomplishment(e)}onAccomplishment(e,t){this.accomplishmentController.subscribe(e,t)}emitSidebarAction(e,t,s,i){this.emit("global.sidebar.triggerAction",{plugin_id:e,action_key:t,text:s,args:i})}emitMainPanelAction(e,t,s){this.emit("global.mainPanel.triggerAction",{plugin_id:e,action_key:t,...s})}onMainPanelAction(e,t=[]){const s=Array.isArray(t)?t:[t],i=this.on("action.requestMain",({data:n})=>{(s.length===0||s.includes(n.action_key))&&e(n)});return this.emit("action.requestMain"),i}onSidePanelAction(e,t=[]){const s=Array.isArray(t)?t:[t],i=this.on("action.requestSidebar",({data:n})=>{(s.length===0||s.includes(n.action))&&e(n)});return this.emit("action.requestSidebar"),this.eventBus.emit(this.pluginId,"global.session.requestCurrent",{}),i}}class $t{controller;sessionTokenId=null;onRateLimitedCb;constructor(e){this.controller=e}resolvePromptName(e){return e.startsWith("global.")?e:e.split(".").length===2&&this.controller.pluginId?`${this.controller.pluginId}.${e}`:e}session={get:()=>this.sessionTokenId,set:e=>{this.sessionTokenId=e},clear:()=>{this.sessionTokenId=null}};setOnRateLimited(e){this.onRateLimitedCb=e}async getText(e){const{messages:t,tools:s,cache:i=!1,prompt:n,variables:o}=e,{result:a}=await this.streamObject({cache:i,tools:s,messages:t,prompt:n,variables:o});return a}async getStreamedText(e){const{messages:t,onMessage:s,tools:i,cache:n=!1,prompt:o,variables:a}=e,l=Math.random().toString(36).substring(3),{result:c}=await this.streamObject({cache:n,tools:i,messages:t,prompt:o,variables:a,onResult:({result:h})=>s(l,h,!1)});return s(l,c,!0),c}async getVoice(e,t="alloy",s=1,i,n=!1,o){return e.trim().length?await this.controller.fetchBackend("/voice/tts",{method:"POST",body:JSON.stringify({input:e,voice:t,speed:s,language:i,cache:n,instructions:o,session_token_id:this.sessionTokenId??void 0})}).then(a=>a.blob()):(console.warn("[rimori-client] getVoice called with empty text — skipping TTS request and returning empty Blob."),new Blob([],{type:"audio/mpeg"}))}async getTextFromVoice(e,t){const s=new FormData;return s.append("file",e),t&&s.append("language",t.code),this.sessionTokenId&&s.append("session_token_id",this.sessionTokenId),await this.controller.fetchBackend("/voice/stt",{method:"POST",body:s}).then(i=>i.json()).then(i=>i.text)}async getObject(e){const{cache:t=!1,tools:s=[],prompt:i,variables:n}=e;return await this.streamObject({messages:[],cache:t,tools:s,prompt:i,variables:n})}async getStreamedObject(e){const{onResult:t,cache:s=!1,tools:i=[],prompt:n,variables:o}=e;return await this.streamObject({messages:[],onResult:t,cache:s,tools:i,prompt:n,variables:o})}async streamObject(e){const{messages:t,onResult:s=()=>null,cache:i=!1,tools:n=[],prompt:o,variables:a}=e,l=t.map((m,w)=>({...m,id:`${w+1}`})),c={cache:i,tools:n,stream:!0,messages:l,session_token_id:this.sessionTokenId??void 0};o&&(c.prompt={name:this.resolvePromptName(o),variables:a??{}});const h=await this.controller.fetchBackend("/ai/llm",{method:"POST",body:JSON.stringify(c)});if(!h.ok){if(h.status===429){const m=await h.json().catch(()=>({})),w=m.exercises_remaining??0;throw this.onRateLimitedCb?.(w),new Error(`Rate limit exceeded: ${m.error??"Daily exercise limit reached"}. exercises_remaining: ${w}`)}throw new Error(`Failed to stream object: ${h.status} ${h.statusText}`)}if(!h.body)throw new Error("No response body.");const u=h.body.getReader(),g=new TextDecoder("utf-8");let d={},f="",y=!0;for(;y;){await new Promise(v=>setTimeout(v,30));const{value:m,done:w}=await u.read();if(w)return y=!1,s(d,!1),d;if(!m)continue;const b=g.decode(m,{stream:!0}),O=(f+b).split(`
|
|
6
|
-
`);f=O.pop()??"";const _=O.filter(v=>v.trim());for(const v of _){if(v.startsWith("token:")){try{const S=JSON.parse(v.slice(6).trim());S.token_id&&(this.sessionTokenId=S.token_id)}catch{console.error("Failed to parse token: line",v)}continue}if(v.startsWith("debug:")){try{const S=JSON.parse(v.slice(6).trim());console.group(`[Rimori Prompt] ${S.promptName}`),console.log(`System prompt:
|
|
7
|
-
`,S.system),console.log(`User prompt:
|
|
8
|
-
`,S.user),console.log("Variables:",S.variables),console.groupEnd()}catch{}continue}const E=v.substring(0,5),M=v.substring(5).trim();if(M==="[DONE]")return y=!1,s(d,!1),d;if(E==="data:")d=JSON.parse(M),s(d,!0);else if(E==="tool:"){const{toolCallId:S,toolName:I,args:ae}=JSON.parse(M),F=n.find(x=>x.name===I);if(F&&F.execute){const x=await F.execute(ae);await this.sendToolResult(S,x)}else F&&!F.execute?console.error("Tool found but has no execute function:",I):console.error("Tool not found:",I)}else E==="error"?console.error("Error:",M.substring(1)):E==="info:"||console.error("Unknown stream data:",v)}}return d}async sendToolResult(e,t){await this.controller.fetchBackend("/ai/llm/tool_result",{method:"POST",body:JSON.stringify({toolCallId:e,result:t??"[DONE]"})})}}class _t{supabase;communicationHandler;eventModule;constructor(e,t,s,i){this.supabase=e,this.communicationHandler=t,this.eventModule=i}async view(){const{data:e,error:t}=await this.supabase.schema("public").from("weekly_exercises").select("*");if(t)throw new Error(`Failed to fetch weekly exercises: ${t.message}`);return e||[]}async add(e){const t=Array.isArray(e)?e:[e],s=await this.communicationHandler.fetchBackend("/exercises",{method:"POST",body:JSON.stringify({exercises:t})});if(!s.ok){const n=await s.text();throw new Error(`Failed to create exercises: ${n}`)}const i=await s.json();return this.eventModule.emit("global.exercises.triggerChange"),i}async start(e){return new Promise((t,s)=>{const i=setTimeout(()=>{n.off(),s(new Error("Exercise start timed out: rimori-main did not respond within 5s"))},5e3),n=this.eventModule.on("global.session.triggerUpdate",({data:o})=>{o.session_token&&(clearTimeout(i),n.off(),t())});this.eventModule.emit("global.exercise.triggerStart",e)})}async delete(e){const t=await this.communicationHandler.fetchBackend(`/exercises/${e}`,{method:"DELETE"});if(!t.ok){const s=await t.text();throw new Error(`Failed to delete exercise: ${s}`)}return this.eventModule.emit("global.exercises.triggerChange"),await t.json()}}class Be{controller;constructor(e){this.controller=e}async uploadImage(e){const t=new FormData;t.append("file",e,"image.png");try{const s=await this.controller.fetchBackend("/plugin-images/upload",{method:"POST",body:t});if(!s.ok){const n=await s.json().catch(()=>({}));return{error:new Error(n.message??`Upload failed (${s.status})`)}}return{data:await s.json()}}catch(s){return{error:s instanceof Error?s:new Error(String(s))}}}}class D{static instance;controller;sharedContent;db;event;plugin;ai;exercise;storage;eventBus;constructor(e,t,s,i){this.controller=e,this.eventBus=i??P,this.sharedContent=new Ve(t,this),this.ai=new $t(e),this.ai.setOnRateLimited(n=>{this.eventBus.emit(s.pluginId,"global.quota.triggerExceeded",{exercises_remaining:n})}),this.event=new Tt(s.pluginId,this.ai,this.eventBus),this.db=new kt(t,e,s),this.plugin=new Ot(t,e,s,this.ai),this.exercise=new _t(t,e,s,this.event),this.storage=new Be(e),this.plugin.applicationMode!=="sidebar"&&et.getInstance(this)}static createWithInfo(e){const t=L.create("Plugin EventBus "+e.pluginId),s=new de(e.pluginId,!0);s.handleRimoriInfoUpdate(e);const i=new Re(`${e.url}/rest/v1`,{schema:e.dbSchema,headers:{apikey:e.key,Authorization:`Bearer ${e.token}`,"plugin-id":e.pluginId}}),n=new D(s,i,e,t);return t.on(`${e.pluginId}.supabase.triggerUpdate`,o=>{console.log("[RimoriClient] Federated triggerUpdate received for",e.pluginId,"| ttsEnabled:",o.data?.ttsEnabled),s.handleRimoriInfoUpdate(o.data)}),n}static async getInstance(e){if(!D.instance){if(!e)throw new Error("Plugin ID is required");const t=new de(e,!1),s=await t.getClient();D.instance=new D(t,s.supabase,s.info)}return D.instance}navigation={toDashboard:()=>{this.event.emit("global.navigation.triggerToDashboard")}};runtime={fetchBackend:(e,t={})=>this.controller.fetchBackend(e,t)}}const Rt="https://pheptqdoqsdnadgoihvr.supabase.co",Nt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InBoZXB0cWRvcXNkbmFkZ29paHZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzE2OTY2ODcsImV4cCI6MjA0NzI3MjY4N30.4GPFAXTF8685FaXISdAPNCIM-H3RGLo8GbyhQpu1mP0";class q{static instance;config;supabase;constructor(e){throw new Error("Authentication is disabled until new developer platform is released.")}static async getInstance(){if(!q.instance){const e=await fetch("https://app.rimori.se/config.json").then(t=>t.json()).catch(t=>{console.warn("Error fetching config.json, using default values",t)});q.instance=new q({url:e?.SUPABASE_URL||Rt,key:e?.SUPABASE_ANON_KEY||Nt,backendUrl:e?.BACKEND_URL||"https://api.rimori.se"})}return q.instance}async getClient(){return this.supabase}async needsLogin(){const{error:e}=await this.supabase.auth.getUser();return e!==null}async login(e,t){const{error:s}=await this.supabase.auth.signInWithPassword({email:e,password:t});return s?(console.error("Login failed:",s),!1):(console.log("Successfully logged in"),!0)}static async initListeners(e){console.warn("The plugin seams to not be running inside the Rimori platform. Switching to development standalone mode.");const{supabase:t,config:s}=await q.getInstance();P.respond("standalone","global.supabase.requestAccess",async()=>{const i=await t.auth.getSession();console.log("session",i);let n=null;try{const{data:{user:l}}=await t.auth.getUser();if(l){const{data:c}=await t.from("profiles").select("current_guild_id").eq("user_id",l.id).maybeSingle();n=c?.current_guild_id||null}}catch{n=null}const o=await fetch(`${s.backendUrl}/plugin/token`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.data.session?.access_token}`},body:JSON.stringify({pluginId:e,guildId:n})});if(!o.ok){const l=await o.text();throw new Error(`Failed to get plugin token. ${o.status}: ${l}`)}return{token:(await o.json()).token,pluginId:e,url:s.url,key:s.key,backendUrl:s.backendUrl,tablePrefix:e,expiration:new Date(Date.now()+1e3*60*60*1.5)}}),P.on("*",async i=>{console.log("[standalone] would send event to parent",i)},["standalone"])}}class At{audioContext;chunkQueue=[];isPlaying=!1;analyser;dataArray;shouldMonitorLoudness=!0;isMonitoring=!1;handle=0;volume=1;loudnessCallback=()=>{};currentIndex=0;startedPlaying=!1;onEndOfSpeech=()=>{};backgroundNoiseLevel=30;currentSource=null;stopped=!1;constructor(){this.init()}init(){this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256;const e=this.analyser.frequencyBinCount;this.dataArray=new Uint8Array(e)}setOnLoudnessChange(e){this.loudnessCallback=e}setVolume(e){this.volume=e}async addChunk(e,t){this.stopped||(console.log("Adding chunk",t,e),this.chunkQueue[t]=e,t===0&&!this.startedPlaying&&(this.startedPlaying=!0,this.playChunks()))}playChunks(){if(!(this.isPlaying||this.stopped)){if(!this.chunkQueue[this.currentIndex]){setTimeout(()=>this.playChunks(),10);return}this.isPlaying=!0,this.playChunk(this.chunkQueue[this.currentIndex]).then(()=>{this.isPlaying=!1,!this.stopped&&(this.currentIndex++,this.chunkQueue[this.currentIndex]?(this.shouldMonitorLoudness=!0,this.playChunks()):setTimeout(()=>{this.stopped||(this.chunkQueue.length>this.currentIndex?this.playChunks():(this.startedPlaying=!1,this.shouldMonitorLoudness=!1))},1e3))})}}stopPlayback(){if(this.stopped=!0,this.currentSource){try{this.currentSource.stop()}catch{}this.currentSource=null}this.isPlaying=!1,this.chunkQueue=[],this.startedPlaying=!1,this.shouldMonitorLoudness=!1,cancelAnimationFrame(this.handle),this.loudnessCallback(0)}cleanup(){this.stopPlayback(),this.audioContext&&this.audioContext.state!=="closed"&&this.audioContext.close().catch(e=>{console.warn("Error closing AudioContext:",e)})}playChunk(e){return!e||this.stopped?Promise.resolve():new Promise(t=>{const s=this.audioContext.createBufferSource();this.currentSource=s,this.audioContext.decodeAudioData(e.slice(0)).then(i=>{if(this.stopped){t();return}s.buffer=i;const n=this.audioContext.createGain();n.gain.value=this.volume,s.connect(n),n.connect(this.analyser),this.analyser.connect(this.audioContext.destination),s.start(0),n.gain.value=this.volume,s.onended=()=>{this.currentSource===s&&(this.currentSource=null),t()},this.isMonitoring||(this.isMonitoring=!0,this.shouldMonitorLoudness=!0,this.monitorLoudness())})})}async playAgain(){console.log("Playing again"),this.chunkQueue.length>0&&!this.isPlaying&&this.playChunks()}monitorLoudness(){if(!this.shouldMonitorLoudness){cancelAnimationFrame(this.handle),this.loudnessCallback(0),this.onEndOfSpeech();return}this.analyser.getByteTimeDomainData(this.dataArray);let e=0;for(let s=0;s<this.dataArray.length;s++){const i=this.dataArray[s]/128-1;e+=i*i}const t=Math.sqrt(e/this.dataArray.length);if(t!==0){let s=20*Math.log10(t);const i=-57,n=-15;s<i&&(s=i),s>n&&(s=n);let o=(s-i)/(n-i)*100;o<this.backgroundNoiseLevel?o=0:o=(o-this.backgroundNoiseLevel)/(100-this.backgroundNoiseLevel)*100,this.loudnessCallback(Math.round(o))}this.handle=requestAnimationFrame(()=>this.monitorLoudness())}reset(){this.stopPlayback(),this.stopped=!1,this.currentIndex=0,this.shouldMonitorLoudness=!0,this.isMonitoring=!1,this.isPlaying=!1,this.init()}setOnEndOfSpeech(e){this.onEndOfSpeech=e}}class jt{player=new At;fetchedSentences=new Set;lastLoading=!1;voice;voiceBackend;cache;voiceSpeed=1;instructions;constructor(e,t,s=!1){if(t?.split("_").length!==2)throw new Error("Invalid voice id format '"+t+"'. Voice id needs to look like <provider>_<voice_id>");this.voiceBackend=e,this.voice=t,this.cache=s}getCompletedSentences(e,t){const s=/(.+?[.?!]|.+?:\s+|.+?\n+)/g,i=[];let n;for(;(n=s.exec(e))!==null;){const o=n[0].trim();o.length>0&&i.push(o)}if(!t){const o=i[i.length-1],a=e.lastIndexOf(o)+o.length;a<e.length&&i.push(e.slice(a).trim())}return i}async handleNewText(e,t){if(!this.lastLoading&&t&&this.reset(),this.lastLoading=t,!e)return;const s=this.getCompletedSentences(e,t);for(let i=0;i<s.length;i++){const n=s[i];if(!this.fetchedSentences.has(n)){this.fetchedSentences.add(n);const o=await this.generateSpeech(n);await this.player.addChunk(o,i)}}}setInstructions(e){this.instructions=e}async generateSpeech(e){return await(await this.voiceBackend(e,this.voice,this.voiceSpeed,void 0,this.cache,this.instructions)).arrayBuffer()}play(){this.player.playAgain()}stop(){this.player.stopPlayback()}cleanup(){this.player.cleanup()}reset(){this.stop(),this.fetchedSentences.clear(),this.player.reset()}setVolume(e){this.player.setVolume(e)}setOnLoudnessChange(e){this.player.setOnLoudnessChange(t=>{e(t)})}setOnEndOfSpeech(e){this.player.setOnEndOfSpeech(e)}setVoiceSpeed(e){this.voiceSpeed=e}}const qe=["Pre-A1","A1","A2","B1","B2","C1","C2","Post-C2"];function ne(r){return qe.indexOf(r)+1}function He(r){return qe[r]}function Dt(r,e){return He(ne(r)+e-1)}function Mt(r,e){return ne(r)-ne(e)}async function Ft(r,e){Object.assign(globalThis,{window:{isWorker:!0,location:{},parent:{postMessage:()=>{}},addEventListener:()=>{}}}),L.getInstance("Worker "+r+" EventBus");const s=await D.getInstance(r);console.debug("[Worker] RimoriClient initialized.");const i=new Error("[Worker "+r+"] Worker setup must complete within 5s. Use init event (e.g. onboarding.triggerInitPlugin) or run work async."),n=Promise.resolve(e(s)),o=new Promise((a,l)=>setTimeout(()=>l(i),5e3));await Promise.race([n,o]),console.debug("[Worker] Worker initialized."),s.event.emit("self.rimori.triggerInitFinished")}class Ut{pluginId;constructor(e){this.pluginId=e}async startRecording(){P.emit(this.pluginId,"global.microphone.triggerStartRecording")}async stopRecording(){return(await P.request(this.pluginId,"global.microphone.triggerStopRecording")).data}async pauseRecording(){return(await P.request(this.pluginId,"global.microphone.triggerPauseRecording")).data}async resumeRecording(){return(await P.request(this.pluginId,"global.microphone.triggerResumeRecording")).data}async getCurrentStatus(){return(await P.request(this.pluginId,"global.microphone.triggerGetCurrentStatus")).data}}const Bt=Object.freeze(Object.defineProperty({__proto__:null,AudioController:Ut,EventBus:P,EventBusHandler:L,MessageSender:jt,ROLE_ORDER:It,RimoriClient:D,RimoriCommunicationHandler:de,StandaloneClient:q,StorageModule:Be,TIER_ORDER:Lt,Translator:Ue,compareLanguageLevels:Mt,getDifficultyLabel:He,getDifficultyLevel:ne,getNeighborDifficultyLevel:Dt,setupWorker:Ft},Symbol.toStringTag,{value:"Module"})),oe="__mf_module_cache__";globalThis[oe]||={share:{},remote:{}};globalThis[oe].share||={};globalThis[oe].remote||={};const Ke=globalThis[oe];let j=Ke.share["@rimori/client"];j===void 0&&(j=Bt,Ke.share["@rimori/client"]=j);const qt=j,Ht=j.__esModule?j.default:j.default??j,{setupWorker:Kt,AudioController:zt,Translator:Vt,TIER_ORDER:Jt,ROLE_ORDER:Wt,StorageModule:Gt,EventBusHandler:Qt,EventBus:Yt,RimoriClient:Zt,StandaloneClient:Xt,MessageSender:es,getDifficultyLevel:ts,getDifficultyLabel:ss,getNeighborDifficultyLevel:is,compareLanguageLevels:ns,RimoriCommunicationHandler:rs}=j,os=ze({__proto__:null,AudioController:zt,EventBus:Yt,EventBusHandler:Qt,MessageSender:es,ROLE_ORDER:Wt,RimoriClient:Zt,RimoriCommunicationHandler:rs,StandaloneClient:Xt,StorageModule:Gt,TIER_ORDER:Jt,Translator:Vt,compareLanguageLevels:ns,default:Ht,getDifficultyLabel:ss,getDifficultyLevel:ts,getNeighborDifficultyLevel:is,setupWorker:Kt},[qt]);export{os as _,Xt as a,Zt as b,Qt as c,Yt as d,zt as e,es as f,Bt as g};
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";var t=class e{listeners=new Map;responseResolvers=new Map;static instance=null;debugEnabled=!1;evName=``;generatedIds=new Map;cleanupInterval=null;constructor(){this.startIdCleanup()}static create(t){let n=new e;return t&&(n.evName=t),n}static getInstance(t){return e.instance||(e.instance=new e,e.instance.on(`global.system.requestDebug`,()=>{e.instance.debugEnabled=!0,console.log(`[${e.instance.evName}] Debug mode enabled. Make sure debugging messages are enabled in the browser console.`)})),t&&e.instance.evName===``&&(e.instance.evName=t),e.instance}startIdCleanup(){this.cleanupInterval=setInterval(()=>{let e=Date.now()-6e4;for(let[t,n]of this.generatedIds.entries())n<e&&this.generatedIds.delete(t)},1e4)}generateUniqueId(){let e=Date.now(),t=e-6e4,n=Math.floor(Math.random()*1e10),r=this.generatedIds.get(n);return r&&r>t?this.generateUniqueId():(this.generatedIds.set(n,e),n)}createEvent(e,t,n,r,i){return{eventId:r||this.generateUniqueId(),timestamp:new Date().toISOString(),sender:e,topic:t,data:n,debug:this.debugEnabled,ai_session_token:i}}emit(e,t,n,r,i){this.emitInternal(e,t,n||{},r,!1,i)}emitInternal(e,t,n,r,i=!1,a){if(!this.validateTopic(t)){this.logAndThrowError(!1,`Invalid topic: `+t);return}let o=this.createEvent(e,t,n,r,a),s=this.getMatchingHandlers(o.topic);s.forEach(t=>{t.ignoreSender&&t.ignoreSender.includes(e)||t.handler(o)}),this.logIfDebug(`Emitting event to `+t,o),s.size===0&&this.logAndThrowError(!1,`No handlers found for topic: `+t),r&&this.responseResolvers.has(r)&&!i&&(this.responseResolvers.get(r)(o),this.responseResolvers.delete(r))}on(e,t,n=[]){let r=this.toArray(e).map(e=>{this.logIfDebug(`Subscribing to `+e,{ignoreSender:n}),this.validateTopic(e)||this.logAndThrowError(!0,`Invalid topic: `+e),this.listeners.has(e)||this.listeners.set(e,new Set);let r=this.generateUniqueId(),i=[];return this.listeners.get(e).add({id:r,handler:e=>{if(!i.some(t=>t.eventId===e.eventId&&t.sender===e.sender))return i.push({eventId:e.eventId,sender:e.sender}),i.length>100&&i.shift(),t(e)},ignoreSender:n}),this.logIfDebug(`Subscribed to `+e,{listenerId:r,ignoreSender:n}),btoa(JSON.stringify({topic:e,id:r}))});return{off:()=>this.off(r)}}respond(e,t,n){let r=(Array.isArray(t)?t:[t]).map(t=>{let r=[],i=t.startsWith(`self.`)?[]:[e],a=this.on(t,async i=>{if(r.includes(i.eventId))return;r.push(i.eventId),r.length>100&&r.shift();let a=typeof n==`function`?await n(i):n;this.emit(e,t,a,i.eventId)},i);return this.logIfDebug(`Added respond listener `+e+` to topic `+t,{listener:a,sender:e}),{off:()=>a.off()}});return{off:()=>r.forEach(e=>e.off())}}once(e,t){if(!this.validateTopic(e)){this.logAndThrowError(!1,`Invalid topic: `+e);return}let n;n=this.on(e,e=>{t(e),n?.off()}),this.logIfDebug(`Added once listener `+e,{listener:n,topic:e})}off(e){this.toArray(e).forEach(e=>{let{topic:t,id:n}=JSON.parse(atob(e)),r=this.listeners.get(t)||new Set;r.forEach(i=>{i.id===Number(n)&&(r.delete(i),this.logIfDebug(`Removed listener `+e,{topic:t,listenerId:n}))})})}toArray(e){return Array.isArray(e)?e:[e]}async request(e,t,n,r){this.validateTopic(t)||this.logAndThrowError(!0,`Invalid topic: `+t);let i=this.createEvent(e,t,n||{},void 0,r);return this.logIfDebug(`Requesting data from `+t,{event:i}),new Promise(a=>{this.responseResolvers.set(i.eventId,e=>a(e)),this.emitInternal(e,t,n||{},i.eventId,!0,r)})}getMatchingHandlers(e){let t=this.listeners.get(e)||new Set,n=[...this.listeners.entries()].filter(([t])=>t.endsWith(`*`)&&e.startsWith(t.slice(0,-1))).flatMap(([e,t])=>[...t]);return new Set([...t,...n])}validateTopic(e){let t=e.split(`.`),[n,r,i]=t;if(t.length!==3)return t.length===1&&n===`*`||t.length===2&&n!==`*`&&r===`*`?!0:(this.logAndThrowError(!1,`Event type must have 3 parts separated by dots. Received: `+e),!1);if(i===`*`)return!0;let a=[`request`,`create`,`update`,`delete`,`trigger`];return a.some(e=>i.startsWith(e))?!0:(this.logAndThrowError(!1,`Invalid event topic name. The action: `+i+`. Must be or start with one of: `+a.join(`, `)),!1)}logIfDebug(...e){this.debugEnabled&&console.debug(`[${this.evName}] `+e[0],...e.slice(1))}destroy(){this.listeners.clear(),this.responseResolvers.clear(),this.cleanupInterval&&=(clearInterval(this.cleanupInterval),null),this.generatedIds.clear()}logAndThrowError(e,...t){let n=`[${this.evName}] `+t[0];if(console.error(n,...t.slice(1)),e)throw Error(n)}},n=t.getInstance(),r=class{supabase;rimoriClient;constructor(e,t){this.supabase=e,this.rimoriClient=t}async getNew(e){let t=await this.rimoriClient.runtime.fetchBackend(`/shared-content/generate`,{method:`POST`,body:JSON.stringify({tableName:e.table,skillType:e.skillType,placeholders:e.placeholders,filter:e.filter,customFields:e.customFields,tool:e.tool,options:{skipDbSave:e.skipDbSave,isPrivate:e.isPrivate,ignoreSkillLevel:e.ignoreSkillLevel}})});if(!t.ok)throw Error(`Failed to generate shared content: ${t.statusText}`);return await t.json()}async searchByTopic(e,t,n=10){let r=await this.rimoriClient.runtime.fetchBackend(`/shared-content/get-by-topic`,{method:`POST`,body:JSON.stringify({tableName:e,limit:n,filter:{title:{filterType:`rag`,value:t}}})});if(!r.ok)throw Error(`Failed to search shared content: ${r.statusText}`);return await r.json()}async getBookmarked(e,t=30){let n=this.getTableName(e),r=this.getCompletedTableName(e),{data:i,error:a}=await this.supabase.from(n).select(`*, completed:${r}!inner(*)`).eq(`completed.bookmarked`,!0).limit(t);if(a)throw console.error(`Error fetching bookmarked content:`,a),Error(`Error fetching bookmarked content`);return i||[]}async getOngoing(e,t=30){let n=this.getTableName(e),r=this.getCompletedTableName(e),{data:i,error:a}=await this.supabase.from(n).select(`*, completed:${r}!inner(*)`).eq(`completed.state`,`ongoing`).limit(t);if(a)throw console.error(`Error fetching ongoing content:`,a),Error(`Error fetching ongoing content`);return i||[]}async getCompleted(e,t=30){let n=this.getTableName(e),r=this.getCompletedTableName(e),{data:i,error:a}=await this.supabase.from(n).select(`*, completed:${r}!inner(*)`).eq(`completed.state`,`completed`).limit(t);if(a)throw console.error(`Error fetching completed content:`,a),Error(`Error fetching completed content`);return i||[]}async complete(e,t){let n=this.getCompletedTableName(e),{error:r}=await this.supabase.from(n).upsert({content_id:t,state:`completed`},{onConflict:`content_id,user_id`});if(r)throw console.error(`Error completing shared content:`,r),Error(`Error completing shared content`)}async updateState(e,t,n){let r=this.getCompletedTableName(e),{error:i}=await this.supabase.from(r).upsert({content_id:t,state:n},{onConflict:`content_id,user_id`});if(i)throw console.error(`Error updating content state:`,i),Error(`Error updating content state`)}async bookmark(e,t,n){let r=this.getCompletedTableName(e),{error:i}=await this.supabase.from(r).upsert({content_id:t,bookmarked:n},{onConflict:`content_id,user_id`});if(i)throw console.error(`Error bookmarking content:`,i),Error(`Error bookmarking content`)}async react(e,t,n){let r=this.getCompletedTableName(e),{error:i}=await this.supabase.from(r).upsert({content_id:t,reaction:n},{onConflict:`content_id,user_id`});if(i)throw console.error(`Error reacting to content:`,i),Error(`Error reacting to content`)}async get(e,t){let n=this.getTableName(e),{data:r,error:i}=await this.supabase.from(n).select(`*`).eq(`id`,t).single();if(i)throw console.error(`Error fetching shared content:`,i),Error(`Error fetching shared content`);return r}async getAll(e,t=100){let n=this.getTableName(e),{data:r,error:i}=await this.supabase.from(n).select(`*`).limit(t);if(i)throw console.error(`Error fetching all shared content:`,i),Error(`Error fetching all shared content`);return r||[]}async create(e,t){let n=this.getTableName(e),{data:r,error:i}=await this.supabase.from(n).insert(t).select().single();if(i)throw console.error(`Error creating shared content:`,i),Error(`Error creating shared content`);return r}async update(e,t,n){let r=await this.rimoriClient.runtime.fetchBackend(`/shared-content/update`,{method:`POST`,body:JSON.stringify({tableName:e,contentId:t,updates:n})});if(!r.ok)throw console.error(`Error updating shared content:`,r.statusText),Error(`Failed to update shared content: ${r.statusText}`);return await r.json()}async validate(e,t){let n=await this.rimoriClient.runtime.fetchBackend(`/shared-content/validate`,{method:`POST`,body:JSON.stringify({tableName:e,contentId:t})});if(!n.ok)throw console.error(`Error validating shared content:`,n.statusText),Error(`Failed to validate shared content: ${n.statusText}`);return await n.json()}async remove(e,t){let n=this.getTableName(e),{error:r}=await this.supabase.from(n).delete().eq(`id`,t);if(r)throw console.error(`Error deleting shared content:`,r),Error(`Error deleting shared content`)}getCompletedTableName(e){return this.getTableName(e)+`_completed`}getTableName(e){return`${this.rimoriClient.plugin.pluginId}_sc_${e}`}},i=class extends Error{constructor(e){super(e.message),this.name=`PostgrestError`,this.details=e.details,this.hint=e.hint,this.code=e.code}},a=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError??!1,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle??!1,this.urlLengthLimit=e.urlLengthLimit??8e3,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var n=this;this.schema===void 0||([`GET`,`HEAD`].includes(this.method)?this.headers.set(`Accept-Profile`,this.schema):this.headers.set(`Content-Profile`,this.schema)),this.method!==`GET`&&this.method!==`HEAD`&&this.headers.set(`Content-Type`,`application/json`);let r=this.fetch,a=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{let t=null,r=null,a=null,o=e.status,s=e.statusText;if(e.ok){if(n.method!==`HEAD`){let t=await e.text();t===``||(r=n.headers.get(`Accept`)===`text/csv`||n.headers.get(`Accept`)&&n.headers.get(`Accept`)?.includes(`application/vnd.pgrst.plan+text`)?t:JSON.parse(t))}let i=n.headers.get(`Prefer`)?.match(/count=(exact|planned|estimated)/),c=e.headers.get(`content-range`)?.split(`/`);i&&c&&c.length>1&&(a=parseInt(c[1])),n.isMaybeSingle&&Array.isArray(r)&&(r.length>1?(t={code:`PGRST116`,details:`Results contain ${r.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:`JSON object requested, multiple (or no) rows returned`},r=null,a=null,o=406,s=`Not Acceptable`):r=r.length===1?r[0]:null)}else{let a=await e.text();try{t=JSON.parse(a),Array.isArray(t)&&e.status===404&&(r=[],t=null,o=200,s=`OK`)}catch{e.status===404&&a===``?(o=204,s=`No Content`):t={message:a}}if(t&&n.shouldThrowOnError)throw new i(t)}return{error:t,data:r,count:a,status:o,statusText:s}});return this.shouldThrowOnError||(a=a.catch(e=>{let t=``,n=``,r=``,i=e?.cause;if(i){let n=i?.message??``,r=i?.code??``;t=`${e?.name??`FetchError`}: ${e?.message}`,t+=`\n\nCaused by: ${i?.name??`Error`}: ${n}`,r&&(t+=` (${r})`),i?.stack&&(t+=`\n${i.stack}`)}else t=e?.stack??``;let a=this.url.toString().length;return e?.name===`AbortError`||e?.code===`ABORT_ERR`?(r=``,n=`Request was aborted (timeout or manual cancellation)`,a>this.urlLengthLimit&&(n+=`. Note: Your request URL is ${a} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(i?.name===`HeadersOverflowError`||i?.code===`UND_ERR_HEADERS_OVERFLOW`)&&(r=``,n=`HTTP headers exceeded server limits (typically 16KB)`,a>this.urlLengthLimit&&(n+=`. Your request URL is ${a} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${e?.name??`FetchError`}: ${e?.message}`,details:t,hint:n,code:r},data:null,count:null,status:0,statusText:``}})),a.then(e,t)}returns(){return this}overrideTypes(){return this}},o=class extends a{select(e){let t=!1,n=(e??`*`).split(``).map(e=>/\s/.test(e)&&!t?``:(e===`"`&&(t=!t),e)).join(``);return this.url.searchParams.set(`select`,n),this.headers.append(`Prefer`,`return=representation`),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:i=r}={}){let a=i?`${i}.order`:`order`,o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:``}${e}.${t?`asc`:`desc`}${n===void 0?``:n?`.nullsfirst`:`.nullslast`}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){let r=n===void 0?`limit`:`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){let i=r===void 0?`offset`:`${r}.offset`,a=r===void 0?`limit`:`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set(`Accept`,`application/vnd.pgrst.object+json`),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set(`Accept`,`text/csv`),this}geojson(){return this.headers.set(`Accept`,`application/geo+json`),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:r=!1,wal:i=!1,format:a=`text`}={}){let o=[e?`analyze`:null,t?`verbose`:null,n?`settings`:null,r?`buffers`:null,i?`wal`:null].filter(Boolean).join(`|`),s=this.headers.get(`Accept`)??`application/json`;return this.headers.set(`Accept`,`application/vnd.pgrst.plan+${a}; for="${s}"; options=${o};`),this}rollback(){return this.headers.append(`Prefer`,`tx=rollback`),this}returns(){return this}maxAffected(e){return this.headers.append(`Prefer`,`handling=strict`),this.headers.append(`Prefer`,`max-affected=${e}`),this}},s=RegExp(`[,()]`),c=class extends o{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(`,`)}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(`,`)}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(`,`)}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(`,`)}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&s.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`in.(${n})`),this}notIn(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&s.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`not.in.(${n})`),this}contains(e,t){return typeof t==`string`?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(`,`)}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t==`string`?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(`,`)}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t==`string`?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(`,`)}}`),this}textSearch(e,t,{config:n,type:r}={}){let i=``;r===`plain`?i=`pl`:r===`phrase`?i=`ph`:r===`websearch`&&(i=`w`);let a=n===void 0?``:`(${n})`;return this.url.searchParams.append(e,`${i}fts${a}.${t}`),this}match(e){return Object.entries(e).filter(([e,t])=>t!==void 0).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){let r=n?`${n}.or`:`or`;return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}},l=class{constructor(e,{headers:t={},schema:n,fetch:r,urlLengthLimit:i=8e3}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r,this.urlLengthLimit=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:n=!1,count:r}=t??{},i=n?`HEAD`:`GET`,a=!1,o=(e??`*`).split(``).map(e=>/\s/.test(e)&&!a?``:(e===`"`&&(a=!a),e)).join(``),{url:s,headers:l}=this.cloneRequestState();return s.searchParams.set(`select`,o),r&&l.append(`Prefer`,`count=${r}`),new c({method:i,url:s,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(e,{count:t,defaultToNull:n=!0}={}){let{url:r,headers:i}=this.cloneRequestState();if(t&&i.append(`Prefer`,`count=${t}`),n||i.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);r.searchParams.set(`columns`,e.join(`,`))}}return new c({method:`POST`,url:r,headers:i,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:r,defaultToNull:i=!0}={}){let{url:a,headers:o}=this.cloneRequestState();if(o.append(`Prefer`,`resolution=${n?`ignore`:`merge`}-duplicates`),t!==void 0&&a.searchParams.set(`on_conflict`,t),r&&o.append(`Prefer`,`count=${r}`),i||o.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set(`columns`,e.join(`,`))}}return new c({method:`POST`,url:a,headers:o,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}update(e,{count:t}={}){let{url:n,headers:r}=this.cloneRequestState();return t&&r.append(`Prefer`,`count=${t}`),new c({method:`PATCH`,url:n,headers:r,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:e}={}){let{url:t,headers:n}=this.cloneRequestState();return e&&n.append(`Prefer`,`count=${e}`),new c({method:`DELETE`,url:t,headers:n,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}};function u(e){"@babel/helpers - typeof";return u=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},u(e)}function d(e,t){if(u(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(u(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function f(e){var t=d(e,`string`);return u(t)==`symbol`?t:t+``}function p(e,t,n){return(t=f(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function m(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function h(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?m(Object(n),!0).forEach(function(t){p(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):m(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var g=class e{constructor(e,{headers:t={},schema:n,fetch:r,timeout:i,urlLengthLimit:a=8e3}={}){this.url=e,this.headers=new Headers(t),this.schemaName=n,this.urlLengthLimit=a;let o=r??globalThis.fetch;i!==void 0&&i>0?this.fetch=(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),i),a=t?.signal;if(a){if(a.aborted)return clearTimeout(r),o(e,t);let i=()=>{clearTimeout(r),n.abort()};return a.addEventListener(`abort`,i,{once:!0}),o(e,h(h({},t),{},{signal:n.signal})).finally(()=>{clearTimeout(r),a.removeEventListener(`abort`,i)})}return o(e,h(h({},t),{},{signal:n.signal})).finally(()=>clearTimeout(r))}:this.fetch=o}from(e){if(!e||typeof e!=`string`||e.trim()===``)throw Error(`Invalid relation name: relation must be a non-empty string.`);return new l(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,t={},{head:n=!1,get:r=!1,count:i}={}){let a,o=new URL(`${this.url}/rpc/${e}`),s,l=e=>typeof e==`object`&&!!e&&(!Array.isArray(e)||e.some(l)),u=n&&Object.values(t).some(l);u?(a=`POST`,s=t):n||r?(a=n?`HEAD`:`GET`,Object.entries(t).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(`,`)}}`:`${t}`]).forEach(([e,t])=>{o.searchParams.append(e,t)})):(a=`POST`,s=t);let d=new Headers(this.headers);return u?d.set(`Prefer`,i?`count=${i},return=minimal`:`return=minimal`):i&&d.set(`Prefer`,`count=${i}`),new c({method:a,url:o,headers:d,schema:this.schemaName,body:s,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}},_=class{pluginId;port=null;queryParams={};supabase=null;rimoriInfo=null;isMessageChannelReady=!1;pendingRequests=[];updateCallbacks=new Set;constructor(e,t){this.pluginId=e,this.getClient=this.getClient.bind(this),!t&&this.initMessageChannel(typeof WorkerGlobalScope<`u`)}initMessageChannel(e=!1){let t=e=>{let{type:t,pluginId:r,queryParams:i,rimoriInfo:a}=e.data||{},[o]=e.ports||[];t!==`rimori:init`||!o||r!==this.pluginId||(this.queryParams=i||{},this.port=o,a&&(this.rimoriInfo=a,this.supabase=this.getSupabase(a.url,a.key,a.token)),this.port.onmessage=({data:e})=>{let{event:t,type:r,eventId:i,response:a,error:o}=e||{};if(r===`response`&&i)n.emit(this.pluginId,a.topic,a.data,i);else if(r===`error`&&i)n.emit(this.pluginId,`error`,{error:o},i);else if(t){let{topic:e,sender:r,data:i,eventId:a,ai_session_token:o}=t;r!==this.pluginId&&n.emit(r,e,i,a,o)}},n.on(`*`,e=>{e.sender===this.pluginId&&!e.topic.startsWith(`self.`)&&this.port?.postMessage({event:e})}),n.on(`${this.pluginId}.supabase.triggerUpdate`,e=>{this.handleRimoriInfoUpdate(e.data)}),this.isMessageChannelReady=!0,this.pendingRequests.forEach(e=>e()),this.pendingRequests=[])};e?self.onmessage=t:window.addEventListener(`message`,t),this.sendHello(e),n.on(`self.rimori.triggerInitFinished`,()=>{this.sendFinishedInit(e)})}sendHello(e=!1){try{let t={type:`rimori:hello`,pluginId:this.pluginId};e?self.postMessage(t):window.parent.postMessage(t,`*`)}catch(e){console.error(`[PluginController] Error sending hello:`,e)}}sendFinishedInit(e=!1){try{let t={type:`rimori:acknowledged`,pluginId:this.pluginId};e?self.postMessage(t):window.parent.postMessage(t,`*`)}catch(e){console.error(`[PluginController] Error sending finished init:`,e)}}getQueryParam(e){return this.queryParams[e]||null}getSupabase(e,t,n){return new g(`${e}/rest/v1`,{schema:this.rimoriInfo?.dbSchema,headers:{apikey:t,Authorization:`Bearer ${n}`,"plugin-id":this.pluginId}})}async getClient(){if(this.supabase&&this.rimoriInfo&&this.rimoriInfo.expiration>new Date)return{supabase:this.supabase,info:this.rimoriInfo};if(!this.isMessageChannelReady)return new Promise(e=>{this.pendingRequests.push(async()=>{e(await this.getClient())})});if(this.rimoriInfo&&this.supabase)return{supabase:this.supabase,info:this.rimoriInfo};if(!this.rimoriInfo)if(typeof WorkerGlobalScope<`u`){let e=Math.floor(Math.random()*1e9),t={event:{timestamp:new Date().toISOString(),eventId:e,sender:this.pluginId,topic:`global.supabase.requestAccess`,data:{},debug:!1}};return new Promise(n=>{let r=self.onmessage;self.onmessage=t=>{t.data?.topic===`global.supabase.requestAccess`&&t.data?.eventId===e?(this.rimoriInfo=t.data.data,this.supabase=this.getSupabase(this.rimoriInfo.url,this.rimoriInfo.key,this.rimoriInfo.token),self.onmessage=r,n({supabase:this.supabase,info:this.rimoriInfo})):r&&r.call(self,t)},self.postMessage(t)})}else{let{data:e}=await n.request(this.pluginId,`global.supabase.requestAccess`);this.rimoriInfo=e,this.supabase=this.getSupabase(this.rimoriInfo.url,this.rimoriInfo.key,this.rimoriInfo.token)}return{supabase:this.supabase,info:this.rimoriInfo}}handleRimoriInfoUpdate(e){JSON.stringify(this.rimoriInfo)!==JSON.stringify(e)&&(this.rimoriInfo=e,this.supabase=this.getSupabase(e.url,e.key,e.token),this.updateCallbacks.forEach(t=>{try{t(e)}catch(e){console.error(`[RimoriCommunicationHandler] Error in update callback:`,e)}}))}onUpdate(e){return this.updateCallbacks.add(e),()=>{this.updateCallbacks.delete(e)}}fetchBackend(e,t={}){if(!this.rimoriInfo)throw Error(`[CommunicationHandler:${this.pluginId}] fetchBackend called before rimoriInfo was initialized`);let{token:n,backendUrl:r}=this.rimoriInfo,i={};typeof t.body==`string`&&(i[`Content-Type`]=`application/json`);let a={...i,...t.headers,Authorization:`Bearer ${n}`,"plugin-id":this.pluginId};return fetch(r+e,{...t,headers:a})}},v=class e{static instance;isProduction;logs=[];logIdCounter=0;originalConsole;constructor(e,t){this.isProduction=this.validateIsProduction(t),this.originalConsole={log:console.log,info:console.info,warn:console.warn,error:console.error,debug:console.debug},this.overrideConsoleMethods(),this.exposeToDevTools(),this.setupNavigationClearing(),e.event.respond(`logging.requestPluginLogs`,async()=>{this.addLogEntry(await this.createLogEntry(`info`,`Log capture`));let t={logs:this.logs,pluginId:e.plugin.pluginId,timestamp:new Date().toISOString()};return this.logs=[],this.logIdCounter=0,t})}static getInstance(t,n){return e.instance||=new e(t,n),e.instance}validateIsProduction(e){return e===void 0?typeof window<`u`&&window.location.href?!window.location.href.includes(`localhost`):!0:e}exposeToDevTools(){typeof window<`u`&&(window.getRimoriLogs=()=>this.logs)}setupNavigationClearing(){if(typeof window>`u`||typeof history>`u`)return;window.addEventListener(`popstate`,()=>this.logs=[]);let e=history.pushState,t=history.replaceState;history.pushState=(...t)=>{e.apply(history,t),this.logs=[]},history.replaceState=(...e)=>{t.apply(history,e),this.logs=[]};let n=window.location.href;setInterval(()=>{window.location.href!==n&&(n=window.location.href,this.logs=[])},100),window.addEventListener(`hashchange`,()=>this.logs=[])}overrideConsoleMethods(){console.log=(...e)=>{let{location:t,style:n}=this.getCallerLocation();this.originalConsole.log(t,n,...e),this.handleConsoleCall(`info`,e)},console.info=(...e)=>{let{location:t,style:n}=this.getCallerLocation();this.originalConsole.info(t,n,...e),this.handleConsoleCall(`info`,e)},console.warn=(...e)=>{let{location:t,style:n}=this.getCallerLocation();this.originalConsole.warn(t,n,...e),this.handleConsoleCall(`warn`,e)},console.error=(...e)=>{let{location:t,style:n}=this.getCallerLocation();this.originalConsole.error(t,n,...e),this.handleConsoleCall(`error`,e)},console.debug=(...e)=>{let{location:t,style:n}=this.getCallerLocation();this.originalConsole.debug(t,n,...e),this.handleConsoleCall(`debug`,e)}}getCallerLocation(){let e={location:``,style:``},t=`color: #0063A2; font-weight: bold;`;if(this.isProduction)return e;try{let n=Error().stack;if(!n)return e;let r=n.split(`
|
|
2
|
+
`)[3];if(!r)return e;let i=r.match(/(?:at\s+.*?\s+\()?([^/\\(]+\.(?:ts|tsx|js|jsx)):(\d+):(\d+)\)?/);if(i){let[,e,n]=i;return{style:t,location:`%c[${e}:${n}]`}}let a=r.match(/([^/\\]+\.(?:ts|tsx|js|jsx))/);return a?{style:t,location:`%c[${a[1]}]`}:e}catch{return e}}async handleConsoleCall(e,t){if(this.isProduction&&(e===`debug`||e===`info`))return;let n=t.map(e=>{if(typeof e!=`object`)return e;try{return JSON.stringify(e)}catch(t){return`Error adding object to log: `+t.message+` `+String(e)}}).join(` `),r=t.length>1?t.slice(1):void 0,i=await this.createLogEntry(e,n,r);this.addLogEntry(i)}getBrowserInfo(){return{userAgent:navigator.userAgent,language:navigator.language,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine,screenResolution:`${screen.width}x${screen.height}`,windowSize:`${window.innerWidth}x${window.innerHeight}`,timestamp:new Date().toISOString()}}async createLogEntry(e,t,n){let r={};return typeof window>`u`||typeof document>`u`?{id:`log_${++this.logIdCounter}_${Date.now()}`,timestamp:new Date().toISOString(),level:e,message:t,data:n}:(r.url=window.location.href,r.browserInfo=this.getBrowserInfo(),r.userAgent=r.browserInfo.userAgent,{id:`log_${++this.logIdCounter}_${Date.now()}`,timestamp:new Date().toISOString(),level:e,message:t,data:n,context:r})}addLogEntry(e){this.logs.push(e),this.logs.length>1e3&&(this.logs=this.logs.slice(-1e3))}},y=e=>typeof e==`string`,b=()=>{let e,t,n=new Promise((n,r)=>{e=n,t=r});return n.resolve=e,n.reject=t,n},x=e=>e==null?``:``+e,S=(e,t,n)=>{e.forEach(e=>{t[e]&&(n[e]=t[e])})},ee=/###/g,C=e=>e&&e.indexOf(`###`)>-1?e.replace(ee,`.`):e,w=e=>!e||y(e),T=(e,t,n)=>{let r=y(t)?t.split(`.`):t,i=0;for(;i<r.length-1;){if(w(e))return{};let t=C(r[i]);!e[t]&&n&&(e[t]=new n),e=Object.prototype.hasOwnProperty.call(e,t)?e[t]:{},++i}return w(e)?{}:{obj:e,k:C(r[i])}},E=(e,t,n)=>{let{obj:r,k:i}=T(e,t,Object);if(r!==void 0||t.length===1){r[i]=n;return}let a=t[t.length-1],o=t.slice(0,t.length-1),s=T(e,o,Object);for(;s.obj===void 0&&o.length;)a=`${o[o.length-1]}.${a}`,o=o.slice(0,o.length-1),s=T(e,o,Object),s?.obj&&s.obj[`${s.k}.${a}`]!==void 0&&(s.obj=void 0);s.obj[`${s.k}.${a}`]=n},te=(e,t,n,r)=>{let{obj:i,k:a}=T(e,t,Object);i[a]=i[a]||[],i[a].push(n)},D=(e,t)=>{let{obj:n,k:r}=T(e,t);if(n&&Object.prototype.hasOwnProperty.call(n,r))return n[r]},ne=(e,t,n)=>{let r=D(e,n);return r===void 0?D(t,n):r},re=(e,t,n)=>{for(let r in t)r!==`__proto__`&&r!==`constructor`&&(r in e?y(e[r])||e[r]instanceof String||y(t[r])||t[r]instanceof String?n&&(e[r]=t[r]):re(e[r],t[r],n):e[r]=t[r]);return e},O=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,`\\$&`),ie={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`,"/":`/`},ae=e=>y(e)?e.replace(/[&<>"'\/]/g,e=>ie[e]):e,oe=class{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){let t=this.regExpMap.get(e);if(t!==void 0)return t;let n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}},se=[` `,`,`,`?`,`!`,`;`],ce=new oe(20),le=(e,t,n)=>{t||=``,n||=``;let r=se.filter(e=>t.indexOf(e)<0&&n.indexOf(e)<0);if(r.length===0)return!0;let i=ce.getRegExp(`(${r.map(e=>e===`?`?`\\?`:e).join(`|`)})`),a=!i.test(e);if(!a){let t=e.indexOf(n);t>0&&!i.test(e.substring(0,t))&&(a=!0)}return a},k=(e,t,n=`.`)=>{if(!e)return;if(e[t])return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;let r=t.split(n),i=e;for(let e=0;e<r.length;){if(!i||typeof i!=`object`)return;let t,a=``;for(let o=e;o<r.length;++o)if(o!==e&&(a+=n),a+=r[o],t=i[a],t!==void 0){if([`string`,`number`,`boolean`].indexOf(typeof t)>-1&&o<r.length-1)continue;e+=o-e+1;break}i=t}return i},A=e=>e?.replace(/_/g,`-`),ue={type:`logger`,log(e){this.output(`log`,e)},warn(e){this.output(`warn`,e)},error(e){this.output(`error`,e)},output(e,t){console?.[e]?.apply?.(console,t)}},j=new class e{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||`i18next:`,this.logger=e||ue,this.options=t,this.debug=t.debug}log(...e){return this.forward(e,`log`,``,!0)}warn(...e){return this.forward(e,`warn`,``,!0)}error(...e){return this.forward(e,`error`,``)}deprecate(...e){return this.forward(e,`warn`,`WARNING DEPRECATED: `,!0)}forward(e,t,n,r){return r&&!this.debug?null:(y(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[t](e))}create(t){return new e(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return t||=this.options,t.prefix=t.prefix||this.prefix,new e(this.logger,t)}},M=class{constructor(){this.observers={}}on(e,t){return e.split(` `).forEach(e=>{this.observers[e]||(this.observers[e]=new Map);let n=this.observers[e].get(t)||0;this.observers[e].set(t,n+1)}),this}off(e,t){if(this.observers[e]){if(!t){delete this.observers[e];return}this.observers[e].delete(t)}}emit(e,...t){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([e,n])=>{for(let r=0;r<n;r++)e(...t)}),this.observers[`*`]&&Array.from(this.observers[`*`].entries()).forEach(([n,r])=>{for(let i=0;i<r;i++)n.apply(n,[e,...t])})}},N=class extends M{constructor(e,t={ns:[`translation`],defaultNS:`translation`}){super(),this.data=e||{},this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator=`.`),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){let t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}getResource(e,t,n,r={}){let i=r.keySeparator===void 0?this.options.keySeparator:r.keySeparator,a=r.ignoreJSONStructure===void 0?this.options.ignoreJSONStructure:r.ignoreJSONStructure,o;e.indexOf(`.`)>-1?o=e.split(`.`):(o=[e,t],n&&(Array.isArray(n)?o.push(...n):y(n)&&i?o.push(...n.split(i)):o.push(n)));let s=D(this.data,o);return!s&&!t&&!n&&e.indexOf(`.`)>-1&&(e=o[0],t=o[1],n=o.slice(2).join(`.`)),s||!a||!y(n)?s:k(this.data?.[e]?.[t],n,i)}addResource(e,t,n,r,i={silent:!1}){let a=i.keySeparator===void 0?this.options.keySeparator:i.keySeparator,o=[e,t];n&&(o=o.concat(a?n.split(a):n)),e.indexOf(`.`)>-1&&(o=e.split(`.`),r=t,t=o[1]),this.addNamespaces(t),E(this.data,o,r),i.silent||this.emit(`added`,e,t,n,r)}addResources(e,t,n,r={silent:!1}){for(let r in n)(y(n[r])||Array.isArray(n[r]))&&this.addResource(e,t,r,n[r],{silent:!0});r.silent||this.emit(`added`,e,t,n)}addResourceBundle(e,t,n,r,i,a={silent:!1,skipCopy:!1}){let o=[e,t];e.indexOf(`.`)>-1&&(o=e.split(`.`),r=n,n=t,t=o[1]),this.addNamespaces(t);let s=D(this.data,o)||{};a.skipCopy||(n=JSON.parse(JSON.stringify(n))),r?re(s,n,i):s={...s,...n},E(this.data,o,s),a.silent||this.emit(`added`,e,t,n)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit(`removed`,e,t)}hasResourceBundle(e,t){return this.getResource(e,t)!==void 0}getResourceBundle(e,t){return t||=this.options.defaultNS,this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){let t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(e=>t[e]&&Object.keys(t[e]).length>0)}toJSON(){return this.data}},P={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,i){return e.forEach(e=>{t=this.processors[e]?.process(t,n,r,i)??t}),t}},F=Symbol(`i18next/PATH_KEY`);function de(){let e=[],t=Object.create(null),n;return t.get=(r,i)=>(n?.revoke?.(),i===F?e:(e.push(i),n=Proxy.revocable(r,t),n.proxy)),Proxy.revocable(Object.create(null),t).proxy}function I(e,t){let{[F]:n}=e(de()),r=t?.keySeparator??`.`,i=t?.nsSeparator??`:`;if(n.length>1&&i){let e=t?.ns,a=Array.isArray(e)?e:null;if(a&&a.length>1&&a.slice(1).includes(n[0]))return`${n[0]}${i}${n.slice(1).join(r)}`}return n.join(r)}var L={},R=e=>!y(e)&&typeof e!=`boolean`&&typeof e!=`number`,z=class e extends M{constructor(e,t={}){super(),S([`resourceStore`,`languageUtils`,`pluralResolver`,`interpolator`,`backendConnector`,`i18nFormat`,`utils`],e,this),this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator=`.`),this.logger=j.create(`translator`)}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){let n={...t};if(e==null)return!1;let r=this.resolve(e,n);if(r?.res===void 0)return!1;let i=R(r.res);return!(n.returnObjects===!1&&i)}extractFromKey(e,t){let n=t.nsSeparator===void 0?this.options.nsSeparator:t.nsSeparator;n===void 0&&(n=`:`);let r=t.keySeparator===void 0?this.options.keySeparator:t.keySeparator,i=t.ns||this.options.defaultNS||[],a=n&&e.indexOf(n)>-1,o=!this.options.userDefinedKeySeparator&&!t.keySeparator&&!this.options.userDefinedNsSeparator&&!t.nsSeparator&&!le(e,n,r);if(a&&!o){let t=e.match(this.interpolator.nestingRegexp);if(t&&t.length>0)return{key:e,namespaces:y(i)?[i]:i};let a=e.split(n);(n!==r||n===r&&this.options.ns.indexOf(a[0])>-1)&&(i=a.shift()),e=a.join(r)}return{key:e,namespaces:y(i)?[i]:i}}translate(t,n,r){let i=typeof n==`object`?{...n}:n;if(typeof i!=`object`&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),typeof i==`object`&&(i={...i}),i||={},t==null)return``;typeof t==`function`&&(t=I(t,{...this.options,...i})),Array.isArray(t)||(t=[String(t)]),t=t.map(e=>typeof e==`function`?I(e,{...this.options,...i}):String(e));let a=i.returnDetails===void 0?this.options.returnDetails:i.returnDetails,o=i.keySeparator===void 0?this.options.keySeparator:i.keySeparator,{key:s,namespaces:c}=this.extractFromKey(t[t.length-1],i),l=c[c.length-1],u=i.nsSeparator===void 0?this.options.nsSeparator:i.nsSeparator;u===void 0&&(u=`:`);let d=i.lng||this.language,f=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(d?.toLowerCase()===`cimode`)return f?a?{res:`${l}${u}${s}`,usedKey:s,exactUsedKey:s,usedLng:d,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:`${l}${u}${s}`:a?{res:s,usedKey:s,exactUsedKey:s,usedLng:d,usedNS:l,usedParams:this.getUsedParamsDetails(i)}:s;let p=this.resolve(t,i),m=p?.res,h=p?.usedKey||s,g=p?.exactUsedKey||s,_=[`[object Number]`,`[object Function]`,`[object RegExp]`],v=i.joinArrays===void 0?this.options.joinArrays:i.joinArrays,b=!this.i18nFormat||this.i18nFormat.handleAsObject,x=i.count!==void 0&&!y(i.count),S=e.hasDefaultValue(i),ee=x?this.pluralResolver.getSuffix(d,i.count,i):``,C=i.ordinal&&x?this.pluralResolver.getSuffix(d,i.count,{ordinal:!1}):``,w=x&&!i.ordinal&&i.count===0,T=w&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${ee}`]||i[`defaultValue${C}`]||i.defaultValue,E=m;b&&!m&&S&&(E=T);let te=R(E),D=Object.prototype.toString.apply(E);if(b&&E&&te&&_.indexOf(D)<0&&!(y(v)&&Array.isArray(E))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn(`accessing an object - but returnObjects options is not enabled!`);let e=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,E,{...i,ns:c}):`key '${s} (${this.language})' returned an object instead of string.`;return a?(p.res=e,p.usedParams=this.getUsedParamsDetails(i),p):e}if(o){let e=Array.isArray(E),t=e?[]:{},n=e?g:h;for(let e in E)if(Object.prototype.hasOwnProperty.call(E,e)){let r=`${n}${o}${e}`;S&&!m?t[e]=this.translate(r,{...i,defaultValue:R(T)?T[e]:void 0,joinArrays:!1,ns:c}):t[e]=this.translate(r,{...i,joinArrays:!1,ns:c}),t[e]===r&&(t[e]=E[e])}m=t}}else if(b&&y(v)&&Array.isArray(m))m=m.join(v),m&&=this.extendTranslation(m,t,i,r);else{let e=!1,n=!1;!this.isValidLookup(m)&&S&&(e=!0,m=T),this.isValidLookup(m)||(n=!0,m=s);let a=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&n?void 0:m,c=S&&T!==m&&this.options.updateMissing;if(n||e||c){if(this.logger.log(c?`updateKey`:`missingKey`,d,l,s,c?T:m),o){let e=this.resolve(s,{...i,keySeparator:!1});e&&e.res&&this.logger.warn(`Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.`)}let e=[],t=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if(this.options.saveMissingTo===`fallback`&&t&&t[0])for(let n=0;n<t.length;n++)e.push(t[n]);else this.options.saveMissingTo===`all`?e=this.languageUtils.toResolveHierarchy(i.lng||this.language):e.push(i.lng||this.language);let n=(e,t,n)=>{let r=S&&n!==m?n:a;this.options.missingKeyHandler?this.options.missingKeyHandler(e,l,t,r,c,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(e,l,t,r,c,i),this.emit(`missingKey`,e,l,t,m)};this.options.saveMissing&&(this.options.saveMissingPlurals&&x?e.forEach(e=>{let t=this.pluralResolver.getSuffixes(e,i);w&&i[`defaultValue${this.options.pluralSeparator}zero`]&&t.indexOf(`${this.options.pluralSeparator}zero`)<0&&t.push(`${this.options.pluralSeparator}zero`),t.forEach(t=>{n([e],s+t,i[`defaultValue${t}`]||T)})}):n(e,s,T))}m=this.extendTranslation(m,t,i,p,r),n&&m===s&&this.options.appendNamespaceToMissingKey&&(m=`${l}${u}${s}`),(n||e)&&this.options.parseMissingKeyHandler&&(m=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${u}${s}`:s,e?m:void 0,i))}return a?(p.res=m,p.usedParams=this.getUsedParamsDetails(i),p):m}extendTranslation(e,t,n,r,i){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});let a=y(e)&&(n?.interpolation?.skipOnVariables===void 0?this.options.interpolation.skipOnVariables:n.interpolation.skipOnVariables),o;if(a){let t=e.match(this.interpolator.nestingRegexp);o=t&&t.length}let s=n.replace&&!y(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),e=this.interpolator.interpolate(e,s,n.lng||this.language||r.usedLng,n),a){let t=e.match(this.interpolator.nestingRegexp),r=t&&t.length;o<r&&(n.nest=!1)}!n.lng&&r&&r.res&&(n.lng=this.language||r.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...e)=>i?.[0]===e[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${e[0]} in key: ${t[0]}`),null):this.translate(...e,t),n)),n.interpolation&&this.interpolator.reset()}let a=n.postProcess||this.options.postProcess,o=y(a)?[a]:a;return e!=null&&o?.length&&n.applyPostProcessor!==!1&&(e=P.handle(o,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,t={}){let n,r,i,a,o;return y(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(e=>typeof e==`function`?I(e,{...this.options,...t}):e)),e.forEach(e=>{if(this.isValidLookup(n))return;let s=this.extractFromKey(e,t),c=s.key;r=c;let l=s.namespaces;this.options.fallbackNS&&(l=l.concat(this.options.fallbackNS));let u=t.count!==void 0&&!y(t.count),d=u&&!t.ordinal&&t.count===0,f=t.context!==void 0&&(y(t.context)||typeof t.context==`number`)&&t.context!==``,p=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);l.forEach(e=>{this.isValidLookup(n)||(o=e,!L[`${p[0]}-${e}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(o)&&(L[`${p[0]}-${e}`]=!0,this.logger.warn(`key "${r}" for languages "${p.join(`, `)}" won't get resolved as namespace "${o}" was not yet loaded`,`This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!`)),p.forEach(r=>{if(this.isValidLookup(n))return;a=r;let o=[c];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(o,c,r,e,t);else{let e;u&&(e=this.pluralResolver.getSuffix(r,t.count,t));let n=`${this.options.pluralSeparator}zero`,i=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(u&&(t.ordinal&&e.indexOf(i)===0&&o.push(c+e.replace(i,this.options.pluralSeparator)),o.push(c+e),d&&o.push(c+n)),f){let r=`${c}${this.options.contextSeparator||`_`}${t.context}`;o.push(r),u&&(t.ordinal&&e.indexOf(i)===0&&o.push(r+e.replace(i,this.options.pluralSeparator)),o.push(r+e),d&&o.push(r+n))}}let s;for(;s=o.pop();)this.isValidLookup(n)||(i=s,n=this.getResource(r,e,s,t))}))})}),{res:n,usedKey:r,exactUsedKey:i,usedLng:a,usedNS:o}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e===``)}getResource(e,t,n,r={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,n,r):this.resourceStore.getResource(e,t,n,r)}getUsedParamsDetails(e={}){let t=[`defaultValue`,`ordinal`,`context`,`replace`,`lng`,`lngs`,`fallbackLng`,`ns`,`keySeparator`,`nsSeparator`,`returnObjects`,`returnDetails`,`joinArrays`,`postProcess`,`interpolation`],n=e.replace&&!y(e.replace),r=n?e.replace:e;if(n&&e.count!==void 0&&(r.count=e.count),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!n){r={...r};for(let e of t)delete r[e]}return r}static hasDefaultValue(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&t.substring(0,12)===`defaultValue`&&e[t]!==void 0)return!0;return!1}},B=class{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=j.create(`languageUtils`)}getScriptPartFromCode(e){if(e=A(e),!e||e.indexOf(`-`)<0)return null;let t=e.split(`-`);return t.length===2||(t.pop(),t[t.length-1].toLowerCase()===`x`)?null:this.formatLanguageCode(t.join(`-`))}getLanguagePartFromCode(e){if(e=A(e),!e||e.indexOf(`-`)<0)return e;let t=e.split(`-`);return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(y(e)&&e.indexOf(`-`)>-1){let t;try{t=Intl.getCanonicalLocales(e)[0]}catch{}return t&&this.options.lowerCaseLng&&(t=t.toLowerCase()),t||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load===`languageOnly`||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach(e=>{if(t)return;let n=this.formatLanguageCode(e);(!this.options.supportedLngs||this.isSupportedCode(n))&&(t=n)}),!t&&this.options.supportedLngs&&e.forEach(e=>{if(t)return;let n=this.getScriptPartFromCode(e);if(this.isSupportedCode(n))return t=n;let r=this.getLanguagePartFromCode(e);if(this.isSupportedCode(r))return t=r;t=this.options.supportedLngs.find(e=>{if(e===r||!(e.indexOf(`-`)<0&&r.indexOf(`-`)<0)&&(e.indexOf(`-`)>0&&r.indexOf(`-`)<0&&e.substring(0,e.indexOf(`-`))===r||e.indexOf(r)===0&&r.length>1))return e})}),t||=this.getFallbackCodes(this.options.fallbackLng)[0],t}getFallbackCodes(e,t){if(!e)return[];if(typeof e==`function`&&(e=e(t)),y(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let n=e[t];return n||=e[this.getScriptPartFromCode(t)],n||=e[this.formatLanguageCode(t)],n||=e[this.getLanguagePartFromCode(t)],n||=e.default,n||[]}toResolveHierarchy(e,t){let n=this.getFallbackCodes((t===!1?[]:t)||this.options.fallbackLng||[],e),r=[],i=e=>{e&&(this.isSupportedCode(e)?r.push(e):this.logger.warn(`rejecting language code not found in supportedLngs: ${e}`))};return y(e)&&(e.indexOf(`-`)>-1||e.indexOf(`_`)>-1)?(this.options.load!==`languageOnly`&&i(this.formatLanguageCode(e)),this.options.load!==`languageOnly`&&this.options.load!==`currentOnly`&&i(this.getScriptPartFromCode(e)),this.options.load!==`currentOnly`&&i(this.getLanguagePartFromCode(e))):y(e)&&i(this.formatLanguageCode(e)),n.forEach(e=>{r.indexOf(e)<0&&i(this.formatLanguageCode(e))}),r}},V={zero:0,one:1,two:2,few:3,many:4,other:5},H={select:e=>e===1?`one`:`other`,resolvedOptions:()=>({pluralCategories:[`one`,`other`]})},fe=class{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=j.create(`pluralResolver`),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){let n=A(e===`dev`?`en`:e),r=t.ordinal?`ordinal`:`cardinal`,i=JSON.stringify({cleanedCode:n,type:r});if(i in this.pluralRulesCache)return this.pluralRulesCache[i];let a;try{a=new Intl.PluralRules(n,{type:r})}catch{if(typeof Intl>`u`)return this.logger.error(`No Intl support, please use an Intl polyfill!`),H;if(!e.match(/-|_/))return H;let n=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(n,t)}return this.pluralRulesCache[i]=a,a}needsPlural(e,t={}){let n=this.getRule(e,t);return n||=this.getRule(`dev`,t),n?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,t,n={}){return this.getSuffixes(e,n).map(e=>`${t}${e}`)}getSuffixes(e,t={}){let n=this.getRule(e,t);return n||=this.getRule(`dev`,t),n?n.resolvedOptions().pluralCategories.sort((e,t)=>V[e]-V[t]).map(e=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:``}${e}`):[]}getSuffix(e,t,n={}){let r=this.getRule(e,n);return r?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:``}${r.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix(`dev`,t,n))}},U=(e,t,n,r=`.`,i=!0)=>{let a=ne(e,t,n);return!a&&i&&y(n)&&(a=k(e,n,r),a===void 0&&(a=k(t,n,r))),a},W=e=>e.replace(/\$/g,`$$$$`),G=class{constructor(e={}){this.logger=j.create(`interpolator`),this.options=e,this.format=e?.interpolation?.format||(e=>e),this.init(e)}init(e={}){e.interpolation||={escapeValue:!0};let{escape:t,escapeValue:n,useRawValueToEscape:r,prefix:i,prefixEscaped:a,suffix:o,suffixEscaped:s,formatSeparator:c,unescapeSuffix:l,unescapePrefix:u,nestingPrefix:d,nestingPrefixEscaped:f,nestingSuffix:p,nestingSuffixEscaped:m,nestingOptionsSeparator:h,maxReplaces:g,alwaysFormat:_}=e.interpolation;this.escape=t===void 0?ae:t,this.escapeValue=n===void 0?!0:n,this.useRawValueToEscape=r===void 0?!1:r,this.prefix=i?O(i):a||`{{`,this.suffix=o?O(o):s||`}}`,this.formatSeparator=c||`,`,this.unescapePrefix=l?``:u||`-`,this.unescapeSuffix=this.unescapePrefix?``:l||``,this.nestingPrefix=d?O(d):f||O(`$t(`),this.nestingSuffix=p?O(p):m||O(`)`),this.nestingOptionsSeparator=h||`,`,this.maxReplaces=g||1e3,this.alwaysFormat=_===void 0?!1:_,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){let e=(e,t)=>e?.source===t?(e.lastIndex=0,e):new RegExp(t,`g`);this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,t,n,r){let i,a,o,s=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=e=>{if(e.indexOf(this.formatSeparator)<0){let i=U(t,s,e,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(i,void 0,n,{...r,...t,interpolationkey:e}):i}let i=e.split(this.formatSeparator),a=i.shift().trim(),o=i.join(this.formatSeparator).trim();return this.format(U(t,s,a,this.options.keySeparator,this.options.ignoreJSONStructure),o,n,{...r,...t,interpolationkey:a})};this.resetRegExp();let l=r?.missingInterpolationHandler||this.options.missingInterpolationHandler,u=r?.interpolation?.skipOnVariables===void 0?this.options.interpolation.skipOnVariables:r.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:e=>W(e)},{regex:this.regexp,safeValue:e=>this.escapeValue?W(this.escape(e)):W(e)}].forEach(t=>{for(o=0;i=t.regex.exec(e);){let n=i[1].trim();if(a=c(n),a===void 0)if(typeof l==`function`){let t=l(e,i,r);a=y(t)?t:``}else if(r&&Object.prototype.hasOwnProperty.call(r,n))a=``;else if(u){a=i[0];continue}else this.logger.warn(`missed to pass in variable ${n} for interpolating ${e}`),a=``;else !y(a)&&!this.useRawValueToEscape&&(a=x(a));let s=t.safeValue(a);if(e=e.replace(i[0],s),u?(t.regex.lastIndex+=a.length,t.regex.lastIndex-=i[0].length):t.regex.lastIndex=0,o++,o>=this.maxReplaces)break}}),e}nest(e,t,n={}){let r,i,a,o=(e,t)=>{let n=this.nestingOptionsSeparator;if(e.indexOf(n)<0)return e;let r=e.split(RegExp(`${O(n)}[ ]*{`)),i=`{${r[1]}`;e=r[0],i=this.interpolate(i,a);let o=i.match(/'/g),s=i.match(/"/g);((o?.length??0)%2==0&&!s||(s?.length??0)%2!=0)&&(i=i.replace(/'/g,`"`));try{a=JSON.parse(i),t&&(a={...t,...a})}catch(t){return this.logger.warn(`failed parsing options string in nesting for key ${e}`,t),`${e}${n}${i}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,e};for(;r=this.nestingRegexp.exec(e);){let s=[];a={...n},a=a.replace&&!y(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;let c=/{.*}/.test(r[1])?r[1].lastIndexOf(`}`)+1:r[1].indexOf(this.formatSeparator);if(c!==-1&&(s=r[1].slice(c).split(this.formatSeparator).map(e=>e.trim()).filter(Boolean),r[1]=r[1].slice(0,c)),i=t(o.call(this,r[1].trim(),a),a),i&&r[0]===e&&!y(i))return i;y(i)||(i=x(i)),i||=(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),``),s.length&&(i=s.reduce((e,t)=>this.format(e,t,n.lng,{...n,interpolationkey:r[1].trim()}),i.trim())),e=e.replace(r[0],i),this.regexp.lastIndex=0}return e}},pe=e=>{let t=e.toLowerCase().trim(),n={};if(e.indexOf(`(`)>-1){let r=e.split(`(`);t=r[0].toLowerCase().trim();let i=r[1].substring(0,r[1].length-1);t===`currency`&&i.indexOf(`:`)<0?n.currency||=i.trim():t===`relativetime`&&i.indexOf(`:`)<0?n.range||=i.trim():i.split(`;`).forEach(e=>{if(e){let[t,...r]=e.split(`:`),i=r.join(`:`).trim().replace(/^'+|'+$/g,``),a=t.trim();n[a]||(n[a]=i),i===`false`&&(n[a]=!1),i===`true`&&(n[a]=!0),isNaN(i)||(n[a]=parseInt(i,10))}})}return{formatName:t,formatOptions:n}},K=e=>{let t={};return(n,r,i)=>{let a=i;i&&i.interpolationkey&&i.formatParams&&i.formatParams[i.interpolationkey]&&i[i.interpolationkey]&&(a={...a,[i.interpolationkey]:void 0});let o=r+JSON.stringify(a),s=t[o];return s||(s=e(A(r),i),t[o]=s),s(n)}},me=e=>(t,n,r)=>e(A(n),r)(t),he=class{constructor(e={}){this.logger=j.create(`formatter`),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||`,`;let n=t.cacheInBuiltFormats?K:me;this.formats={number:n((e,t)=>{let n=new Intl.NumberFormat(e,{...t});return e=>n.format(e)}),currency:n((e,t)=>{let n=new Intl.NumberFormat(e,{...t,style:`currency`});return e=>n.format(e)}),datetime:n((e,t)=>{let n=new Intl.DateTimeFormat(e,{...t});return e=>n.format(e)}),relativetime:n((e,t)=>{let n=new Intl.RelativeTimeFormat(e,{...t});return e=>n.format(e,t.range||`day`)}),list:n((e,t)=>{let n=new Intl.ListFormat(e,{...t});return e=>n.format(e)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=K(t)}format(e,t,n,r={}){let i=t.split(this.formatSeparator);if(i.length>1&&i[0].indexOf(`(`)>1&&i[0].indexOf(`)`)<0&&i.find(e=>e.indexOf(`)`)>-1)){let e=i.findIndex(e=>e.indexOf(`)`)>-1);i[0]=[i[0],...i.splice(1,e)].join(this.formatSeparator)}return i.reduce((e,t)=>{let{formatName:i,formatOptions:a}=pe(t);if(this.formats[i]){let t=e;try{let o=r?.formatParams?.[r.interpolationkey]||{},s=o.locale||o.lng||r.locale||r.lng||n;t=this.formats[i](e,s,{...a,...r,...o})}catch(e){this.logger.warn(e)}return t}else this.logger.warn(`there was no format function for ${i}`);return e},e)}},ge=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)},_e=class extends M{constructor(e,t,n,r={}){super(),this.backend=e,this.store=t,this.services=n,this.languageUtils=n.languageUtils,this.options=r,this.logger=j.create(`backendConnector`),this.waitingReads=[],this.maxParallelReads=r.maxParallelReads||10,this.readingCalls=0,this.maxRetries=r.maxRetries>=0?r.maxRetries:5,this.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(n,r.backend,r)}queueLoad(e,t,n,r){let i={},a={},o={},s={};return e.forEach(e=>{let r=!0;t.forEach(t=>{let o=`${e}|${t}`;!n.reload&&this.store.hasResourceBundle(e,t)?this.state[o]=2:this.state[o]<0||(this.state[o]===1?a[o]===void 0&&(a[o]=!0):(this.state[o]=1,r=!1,a[o]===void 0&&(a[o]=!0),i[o]===void 0&&(i[o]=!0),s[t]===void 0&&(s[t]=!0)))}),r||(o[e]=!0)}),(Object.keys(i).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(i),pending:Object.keys(a),toLoadLanguages:Object.keys(o),toLoadNamespaces:Object.keys(s)}}loaded(e,t,n){let r=e.split(`|`),i=r[0],a=r[1];t&&this.emit(`failedLoading`,i,a,t),!t&&n&&this.store.addResourceBundle(i,a,n,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&n&&(this.state[e]=0);let o={};this.queue.forEach(n=>{te(n.loaded,[i],a),ge(n,e),t&&n.errors.push(t),n.pendingCount===0&&!n.done&&(Object.keys(n.loaded).forEach(e=>{o[e]||(o[e]={});let t=n.loaded[e];t.length&&t.forEach(t=>{o[e][t]===void 0&&(o[e][t]=!0)})}),n.done=!0,n.errors.length?n.callback(n.errors):n.callback())}),this.emit(`loaded`,o),this.queue=this.queue.filter(e=>!e.done)}read(e,t,n,r=0,i=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:t,fcName:n,tried:r,wait:i,callback:a});return}this.readingCalls++;let o=(o,s)=>{if(this.readingCalls--,this.waitingReads.length>0){let e=this.waitingReads.shift();this.read(e.lng,e.ns,e.fcName,e.tried,e.wait,e.callback)}if(o&&s&&r<this.maxRetries){setTimeout(()=>{this.read.call(this,e,t,n,r+1,i*2,a)},i);return}a(o,s)},s=this.backend[n].bind(this.backend);if(s.length===2){try{let n=s(e,t);n&&typeof n.then==`function`?n.then(e=>o(null,e)).catch(o):o(null,n)}catch(e){o(e)}return}return s(e,t,o)}prepareLoading(e,t,n={},r){if(!this.backend)return this.logger.warn(`No backend was added via i18next.use. Will not load resources.`),r&&r();y(e)&&(e=this.languageUtils.toResolveHierarchy(e)),y(t)&&(t=[t]);let i=this.queueLoad(e,t,n,r);if(!i.toLoad.length)return i.pending.length||r(),null;i.toLoad.forEach(e=>{this.loadOne(e)})}load(e,t,n){this.prepareLoading(e,t,{},n)}reload(e,t,n){this.prepareLoading(e,t,{reload:!0},n)}loadOne(e,t=``){let n=e.split(`|`),r=n[0],i=n[1];this.read(r,i,`read`,void 0,void 0,(n,a)=>{n&&this.logger.warn(`${t}loading namespace ${i} for language ${r} failed`,n),!n&&a&&this.logger.log(`${t}loaded namespace ${i} for language ${r}`,a),this.loaded(e,n,a)})}saveMissing(e,t,n,r,i,a={},o=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(t)){this.logger.warn(`did not save key "${n}" as the namespace "${t}" was not yet loaded`,`This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!`);return}if(!(n==null||n===``)){if(this.backend?.create){let s={...a,isUpdate:i},c=this.backend.create.bind(this.backend);if(c.length<6)try{let i;i=c.length===5?c(e,t,n,r,s):c(e,t,n,r),i&&typeof i.then==`function`?i.then(e=>o(null,e)).catch(o):o(null,i)}catch(e){o(e)}else c(e,t,n,r,o,s)}!e||!e[0]||this.store.addResource(e[0],t,n,r)}}},q=()=>({debug:!1,initAsync:!0,ns:[`translation`],defaultNS:[`translation`],fallbackLng:[`dev`],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:`all`,preload:!1,simplifyPluralSuffix:!0,keySeparator:`.`,nsSeparator:`:`,pluralSeparator:`_`,contextSeparator:`_`,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:`fallback`,saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]==`object`&&(t=e[1]),y(e[1])&&(t.defaultValue=e[1]),y(e[2])&&(t.tDescription=e[2]),typeof e[2]==`object`||typeof e[3]==`object`){let n=e[3]||e[2];Object.keys(n).forEach(e=>{t[e]=n[e]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:`{{`,suffix:`}}`,formatSeparator:`,`,unescapePrefix:`-`,nestingPrefix:`$t(`,nestingSuffix:`)`,nestingOptionsSeparator:`,`,maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),ve=e=>(y(e.ns)&&(e.ns=[e.ns]),y(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),y(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs?.indexOf?.(`cimode`)<0&&(e.supportedLngs=e.supportedLngs.concat([`cimode`])),typeof e.initImmediate==`boolean`&&(e.initAsync=e.initImmediate),e),J=()=>{},ye=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(t=>{typeof e[t]==`function`&&(e[t]=e[t].bind(e))})},be=`__i18next_supportNoticeShown`,xe=()=>!!(typeof globalThis<`u`&&globalThis[be]||typeof process<`u`&&{}.I18NEXT_NO_SUPPORT_NOTICE||typeof process<`u`),Se=()=>{typeof globalThis<`u`&&(globalThis[be]=!0)},Ce=e=>!!(e?.modules?.backend?.name?.indexOf(`Locize`)>0||e?.modules?.backend?.constructor?.name?.indexOf(`Locize`)>0||e?.options?.backend?.backends&&e.options.backend.backends.some(e=>e?.name?.indexOf(`Locize`)>0||e?.constructor?.name?.indexOf(`Locize`)>0)||e?.options?.backend?.projectId||e?.options?.backend?.backendOptions&&e.options.backend.backendOptions.some(e=>e?.projectId)),Y=class e extends M{constructor(e={},t){if(super(),this.options=ve(e),this.services={},this.logger=j,this.modules={external:[]},ye(this),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(e={},t){this.isInitializing=!0,typeof e==`function`&&(t=e,e={}),e.defaultNS==null&&e.ns&&(y(e.ns)?e.defaultNS=e.ns:e.ns.indexOf(`translation`)<0&&(e.defaultNS=e.ns[0]));let n=q();this.options={...n,...this.options,...ve(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!=`function`&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler),this.options.showSupportNotice!==!1&&!Ce(this)&&!xe()&&(typeof console<`u`&&console.info!==void 0&&console.info(`🌐 i18next is made possible by our own product, Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙`),Se());let r=e=>e?typeof e==`function`?new e:e:null;if(!this.options.isClone){this.modules.logger?j.init(r(this.modules.logger),this.options):j.init(null,this.options);let e;e=this.modules.formatter?this.modules.formatter:he;let t=new B(this.options);this.store=new N(this.options.resources,this.options);let i=this.services;i.logger=j,i.resourceStore=this.store,i.languageUtils=t,i.pluralResolver=new fe(t,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==n.interpolation.format&&this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`),e&&(!this.options.interpolation.format||this.options.interpolation.format===n.interpolation.format)&&(i.formatter=r(e),i.formatter.init&&i.formatter.init(i,this.options),this.options.interpolation.format=i.formatter.format.bind(i.formatter)),i.interpolator=new G(this.options),i.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},i.backendConnector=new _e(r(this.modules.backend),i.resourceStore,i,this.options),i.backendConnector.on(`*`,(e,...t)=>{this.emit(e,...t)}),this.modules.languageDetector&&(i.languageDetector=r(this.modules.languageDetector),i.languageDetector.init&&i.languageDetector.init(i,this.options.detection,this.options)),this.modules.i18nFormat&&(i.i18nFormat=r(this.modules.i18nFormat),i.i18nFormat.init&&i.i18nFormat.init(this)),this.translator=new z(this.services,this.options),this.translator.on(`*`,(e,...t)=>{this.emit(e,...t)}),this.modules.external.forEach(e=>{e.init&&e.init(this)})}if(this.format=this.options.interpolation.format,t||=J,this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){let e=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);e.length>0&&e[0]!==`dev`&&(this.options.lng=e[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn(`init: no languageDetector is used and no lng is defined`),[`getResource`,`hasResourceBundle`,`getResourceBundle`,`getDataByLanguage`].forEach(e=>{this[e]=(...t)=>this.store[e](...t)}),[`addResource`,`addResources`,`addResourceBundle`,`removeResourceBundle`].forEach(e=>{this[e]=(...t)=>(this.store[e](...t),this)});let i=b(),a=()=>{let e=(e,n)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn(`init: i18next is already initialized. You should call init just once!`),this.isInitialized=!0,this.options.isClone||this.logger.log(`initialized`,this.options),this.emit(`initialized`,this.options),i.resolve(n),t(e,n)};if(this.languages&&!this.isInitialized)return e(null,this.t.bind(this));this.changeLanguage(this.options.lng,e)};return this.options.resources||!this.options.initAsync?a():setTimeout(a,0),i}loadResources(e,t=J){let n=t,r=y(e)?e:this.language;if(typeof e==`function`&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if(r?.toLowerCase()===`cimode`&&(!this.options.preload||this.options.preload.length===0))return n();let e=[],t=t=>{t&&t!==`cimode`&&this.services.languageUtils.toResolveHierarchy(t).forEach(t=>{t!==`cimode`&&e.indexOf(t)<0&&e.push(t)})};r?t(r):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(e=>t(e)),this.options.preload?.forEach?.(e=>t(e)),this.services.backendConnector.load(e,this.options.ns,e=>{!e&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(e)})}else n(null)}reloadResources(e,t,n){let r=b();return typeof e==`function`&&(n=e,e=void 0),typeof t==`function`&&(n=t,t=void 0),e||=this.languages,t||=this.options.ns,n||=J,this.services.backendConnector.reload(e,t,e=>{r.resolve(),n(e)}),r}use(e){if(!e)throw Error(`You are passing an undefined module! Please check the object you are passing to i18next.use()`);if(!e.type)throw Error(`You are passing a wrong module! Please check the object you are passing to i18next.use()`);return e.type===`backend`&&(this.modules.backend=e),(e.type===`logger`||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type===`languageDetector`&&(this.modules.languageDetector=e),e.type===`i18nFormat`&&(this.modules.i18nFormat=e),e.type===`postProcessor`&&P.addPostProcessor(e),e.type===`formatter`&&(this.modules.formatter=e),e.type===`3rdParty`&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!([`cimode`,`dev`].indexOf(e)>-1)){for(let e=0;e<this.languages.length;e++){let t=this.languages[e];if(!([`cimode`,`dev`].indexOf(t)>-1)&&this.store.hasLanguageSomeTranslations(t)){this.resolvedLanguage=t;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,t){this.isLanguageChangingTo=e;let n=b();this.emit(`languageChanging`,e);let r=e=>{this.language=e,this.languages=this.services.languageUtils.toResolveHierarchy(e),this.resolvedLanguage=void 0,this.setResolvedLanguage(e)},i=(i,a)=>{a?this.isLanguageChangingTo===e&&(r(a),this.translator.changeLanguage(a),this.isLanguageChangingTo=void 0,this.emit(`languageChanged`,a),this.logger.log(`languageChanged`,a)):this.isLanguageChangingTo=void 0,n.resolve((...e)=>this.t(...e)),t&&t(i,(...e)=>this.t(...e))},a=t=>{!e&&!t&&this.services.languageDetector&&(t=[]);let n=y(t)?t:t&&t[0],a=this.store.hasLanguageSomeTranslations(n)?n:this.services.languageUtils.getBestMatchFromCodes(y(t)?[t]:t);a&&(this.language||r(a),this.translator.language||this.translator.changeLanguage(a),this.services.languageDetector?.cacheUserLanguage?.(a)),this.loadResources(a,e=>{i(e,a)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(e),n}getFixedT(e,t,n){let r=(e,t,...i)=>{let a;a=typeof t==`object`?{...t}:this.options.overloadTranslationOptionHandler([e,t].concat(i)),a.lng=a.lng||r.lng,a.lngs=a.lngs||r.lngs,a.ns=a.ns||r.ns,a.keyPrefix!==``&&(a.keyPrefix=a.keyPrefix||n||r.keyPrefix);let o={...this.options,...a};typeof a.keyPrefix==`function`&&(a.keyPrefix=I(a.keyPrefix,o));let s=this.options.keySeparator||`.`,c;return a.keyPrefix&&Array.isArray(e)?c=e.map(e=>(typeof e==`function`&&(e=I(e,o)),`${a.keyPrefix}${s}${e}`)):(typeof e==`function`&&(e=I(e,o)),c=a.keyPrefix?`${a.keyPrefix}${s}${e}`:e),this.t(c,a)};return y(e)?r.lng=e:r.lngs=e,r.ns=t,r.keyPrefix=n,r}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn(`hasLoadedNamespace: i18next was not initialized`,this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn(`hasLoadedNamespace: i18n.languages were undefined or empty`,this.languages),!1;let n=t.lng||this.resolvedLanguage||this.languages[0],r=this.options?this.options.fallbackLng:!1,i=this.languages[this.languages.length-1];if(n.toLowerCase()===`cimode`)return!0;let a=(e,t)=>{let n=this.services.backendConnector.state[`${e}|${t}`];return n===-1||n===0||n===2};if(t.precheck){let e=t.precheck(this,a);if(e!==void 0)return e}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(n,e)&&(!r||a(i,e)))}loadNamespaces(e,t){let n=b();return this.options.ns?(y(e)&&(e=[e]),e.forEach(e=>{this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}),this.loadResources(e=>{n.resolve(),t&&t(e)}),n):(t&&t(),Promise.resolve())}loadLanguages(e,t){let n=b();y(e)&&(e=[e]);let r=this.options.preload||[],i=e.filter(e=>r.indexOf(e)<0&&this.services.languageUtils.isSupportedCode(e));return i.length?(this.options.preload=r.concat(i),this.loadResources(e=>{n.resolve(),t&&t(e)}),n):(t&&t(),Promise.resolve())}dir(e){if(e||=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language),!e)return`rtl`;try{let t=new Intl.Locale(e);if(t&&t.getTextInfo){let e=t.getTextInfo();if(e&&e.direction)return e.direction}}catch{}let t=`ar.shu.sqr.ssh.xaa.yhd.yud.aao.abh.abv.acm.acq.acw.acx.acy.adf.ads.aeb.aec.afb.ajp.apc.apd.arb.arq.ars.ary.arz.auz.avl.ayh.ayl.ayn.ayp.bbz.pga.he.iw.ps.pbt.pbu.pst.prp.prd.ug.ur.ydd.yds.yih.ji.yi.hbo.men.xmn.fa.jpr.peo.pes.prs.dv.sam.ckb`.split(`.`),n=this.services?.languageUtils||new B(q());return e.toLowerCase().indexOf(`-latn`)>1?`ltr`:t.indexOf(n.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf(`-arab`)>1?`rtl`:`ltr`}static createInstance(t={},n){let r=new e(t,n);return r.createInstance=e.createInstance,r}cloneInstance(t={},n=J){let r=t.forkResourceStore;r&&delete t.forkResourceStore;let i={...this.options,...t,isClone:!0},a=new e(i);if((t.debug!==void 0||t.prefix!==void 0)&&(a.logger=a.logger.clone(t)),[`store`,`services`,`language`].forEach(e=>{a[e]=this[e]}),a.services={...this.services},a.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},r&&(a.store=new N(Object.keys(this.store.data).reduce((e,t)=>(e[t]={...this.store.data[t]},e[t]=Object.keys(e[t]).reduce((n,r)=>(n[r]={...e[t][r]},n),e[t]),e),{}),i),a.services.resourceStore=a.store),t.interpolation){let e={...q().interpolation,...this.options.interpolation,...t.interpolation},n={...i,interpolation:e};a.services.interpolator=new G(n)}return a.translator=new z(a.services,i),a.translator.on(`*`,(e,...t)=>{a.emit(e,...t)}),a.init(i,n),a.translator.options=i,a.translator.backendConnector.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},a}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}.createInstance(),we=Y.createInstance;Y.dir,Y.init,Y.loadResources,Y.reloadResources,Y.use,Y.changeLanguage,Y.getFixedT,Y.t,Y.exists,Y.setDefaultNamespace,Y.hasLoadedNamespace,Y.loadNamespaces,Y.loadLanguages;var Te=class{currentLanguage;initializationState;initializationPromise;i18n;translationUrl;ai;aiTranslationCache=new Map;aiTranslationPending=new Map;constructor(e,t,n){this.currentLanguage=e,this.initializationState=`not-inited`,this.initializationPromise=null,this.translationUrl=t,this.ai=n}async initialize(){if(this.initializationState!==`finished`)return this.initializationState===`initing`&&this.initializationPromise?this.initializationPromise:(this.initializationState=`initing`,this.initializationPromise=(async()=>{try{let e=await this.fetchTranslations(this.currentLanguage),t=we({lng:this.currentLanguage,resources:{[this.currentLanguage]:{translation:e}},debug:!1,showSupportNotice:!1,parseMissingKeyHandler:(e,t)=>e.trim()?this.isTranslationKey(e)?(console.warn(`Translation key not found: ${e}`),t??``):(this.fetchTranslation(e).then(t=>{this.i18n?.addResource(this.currentLanguage,`translation`,e,t),this.i18n?.emit(`languageChanged`)}),e):``});await t.init(),this.i18n=t,this.initializationState=`finished`}catch(e){throw this.initializationState=`not-inited`,this.initializationPromise=null,e}})(),this.initializationPromise)}getTranslationUrl(e){return`${(this.translationUrl||window.location.origin).replace(/\/+$/,``)}/locales/${e}.json`}usePlugin(e){if(!this.i18n)throw Error(`Translator is not initialized`);this.i18n.use(e)}onLanguageChanged(e){if(!this.i18n)throw Error(`Translator is not initialized`);this.i18n.on(`languageChanged`,e)}async fetchTranslations(e,t=0){try{let n=await fetch(this.getTranslationUrl(e));if(!n.ok)throw Error(`Failed to fetch translations for ${e}: ${n.status}`);let r=await n.json();return Object.keys(r).length===0&&t===0?(await new Promise(e=>setTimeout(e,300)),this.fetchTranslations(e,1)):r}catch(n){return t===0?(await new Promise(e=>setTimeout(e,300)),this.fetchTranslations(e,1)):(console.warn(`Fetching of ${e} translation not possible. Falling back to english. Error details: `+n.message),e===`en`?{}:this.fetchTranslations(`en`).catch(e=>(console.error(`Failed to fetch fallback translations:`,e),{})))}}t(e,t){if(!this.i18n)throw Error(`Translator is not initialized`);return this.i18n.t(e,t)}getCurrentLanguage(){return this.currentLanguage}isReady(){return this.initializationState===`finished`}isTranslationKey(e){return/^[^\s.]+(\.[^\s.]+)+$/.test(e)}async fetchTranslation(e,t){let n=this.aiTranslationCache.get(e);if(n)return n;let r=this.aiTranslationPending.get(e);if(r)return r;if(!this.ai||this.currentLanguage===`en`)return e;let i=(async()=>{try{let n=(await this.ai.getObject({prompt:`global.translator.translate`,variables:{additionalInstructions:t??``,language:this.currentLanguage,text:e},cache:!0}))?.translation;if(n)return this.aiTranslationCache.set(e,n),n}catch(t){console.warn(`Failed to translate freeform text:`,{text:e,error:t})}finally{this.aiTranslationPending.delete(e)}return e})();return this.aiTranslationPending.set(e,i),i}},Ee=class{pluginId;rimoriInfo;translator;supabase;communicationHandler;releaseChannel;applicationMode;theme;ttsEnabled=!0;constructor(e,t,n,r){this.rimoriInfo=n,this.supabase=e,this.pluginId=n.pluginId,this.releaseChannel=n.releaseChannel,this.communicationHandler=t;let i=n.installedPlugins.find(e=>e.id===n.pluginId);this.translator=new Te(n.interfaceLanguage,i?.endpoint||``,r),this.ttsEnabled=n.ttsEnabled??!0,this.communicationHandler.onUpdate(e=>{this.rimoriInfo=e,this.ttsEnabled=e.ttsEnabled??!0}),this.applicationMode=this.communicationHandler.getQueryParam(`applicationMode`),this.theme=this.communicationHandler.getQueryParam(`rm_theme`)||`light`}async fetchSettings(){let e=!this.rimoriInfo.guild.allowUserPluginSettings,{data:t}=await this.supabase.schema(`public`).from(`plugin_settings`).select(`*`).eq(`plugin_id`,this.pluginId).eq(`guild_id`,this.rimoriInfo.guild.id).eq(`is_guild_setting`,e).maybeSingle();return t?.settings??null}async setSettings(e){let t=!this.rimoriInfo.guild.allowUserPluginSettings,n={plugin_id:this.pluginId,settings:e,guild_id:this.rimoriInfo.guild.id,is_guild_setting:t};t&&(n.user_id=null);let r=this.supabase.schema(`public`).from(`plugin_settings`).update({settings:e}).eq(`plugin_id`,this.pluginId).eq(`guild_id`,this.rimoriInfo.guild.id).eq(`is_guild_setting`,t),{data:i,error:a}=await(t?r.is(`user_id`,null).select():r.select());if(a&&(a.code===`42501`||a.message?.includes(`policy`)))throw Error(`Cannot set ${t?`guild`:`user`} settings: Permission denied.`);if(i&&i.length>0)return;let{error:o}=await this.supabase.schema(`public`).from(`plugin_settings`).insert(n);if(o){if(o.code===`23505`){let n=this.supabase.schema(`public`).from(`plugin_settings`).update({settings:e}).eq(`plugin_id`,this.pluginId).eq(`guild_id`,this.rimoriInfo.guild.id).eq(`is_guild_setting`,t),{error:r}=await(t?n.is(`user_id`,null):n);if(!r)return}throw o}}async getSettings(e){let t=await this.fetchSettings();if(!t)return await this.setSettings(e),e;let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length){let n=Object.fromEntries(Object.entries(t).filter(([e])=>r.includes(e))),i={...e,...n};return await this.setSettings(i),i}return t}getUserInfo(){return this.rimoriInfo.profile}getGuildInfo(){return{id:this.rimoriInfo.guild.id,name:this.rimoriInfo.guild.name,description:this.rimoriInfo.guild.description,isShadowGuild:this.rimoriInfo.guild.isShadowGuild}}onRimoriInfoUpdate(e){return this.communicationHandler.onUpdate(e)}getPluginInfo(){return{installedPlugins:this.rimoriInfo.installedPlugins,mainPanelPlugin:this.rimoriInfo.mainPanelPlugin,sidePanelPlugin:this.rimoriInfo.sidePanelPlugin}}async getTranslator(){return await this.translator.initialize(),this.translator}},De=[`anonymous`,`free`,`standard`,`premium`,`early_access`],Oe=[`user`,`plugin_moderator`,`lang_moderator`,`admin`],ke=class{supabase;communicationHandler;tablePrefix;schema;constructor(e,t,n){this.supabase=e,this.communicationHandler=t,this.tablePrefix=n.tablePrefix,this.schema=n.dbSchema,t.onUpdate(e=>{this.tablePrefix=e.tablePrefix,this.schema=e.dbSchema})}from(e){let t=this.getTableName(e);return e.startsWith(`global_`)?this.supabase.schema(`public`).from(t):this.supabase.schema(this.schema).from(t)}getTableName(e){if(/[A-Z]/.test(e))throw Error(`Table name cannot include uppercase letters. Please use snake_case for table names.`);return e.startsWith(`global_`)?e.replace(`global_`,``):this.tablePrefix+`_`+e}async setPublicity(e,t,n){let r=this.getTableName(e);await this.communicationHandler.fetchBackend(`/db-entry/publicity`,{method:`POST`,body:JSON.stringify({table_name:r,schema:this.schema,entry_id:t,publicity:n})})}async vectorSearch(e){let t=await this.communicationHandler.fetchBackend(`/plugin-search/vector-search`,{method:`POST`,body:JSON.stringify(e)});if(!t.ok)throw Error(`Vector search failed: ${t.statusText}`);return await t.json()}},Ae=[`reading`,`listening`,`speaking`,`writing`,`learning`,`community`],je=class{pluginId;eventBus;constructor(e,t){this.pluginId=e,this.eventBus=t??n}emitAccomplishment(e){let t={...e,type:`durationMinutes`in e?`macro`:`micro`};if(!this.validateAccomplishment(t))return;let n=this.sanitizeAccomplishment(t),r=`global.accomplishment.trigger`+(t.type===`macro`?`Macro`:`Micro`);this.eventBus.emit(this.pluginId,r,n)}validateAccomplishment(e){if(!Ae.includes(e.skillCategory))throw Error(`Invalid skill category: ${e.skillCategory}`);if(!/^[0-9a-z_.-]+$/.test(e.accomplishmentKeyword))throw Error(`The accomplishment keyword: ${e.accomplishmentKeyword} is invalid. Only lowercase letters, minuses, underscores and periods are allowed`);if(e.description.length<10)throw Error(`Description is too short`);if(![`micro`,`macro`].includes(e.type))throw Error(`Invalid accomplishment type `+e.type);if(e.type===`macro`&&(e.errorRatio<0||e.errorRatio>1))throw Error(`The error ratio must be between 0 and 1`);return!0}sanitizeAccomplishment(e){return e.description=e.description.replace(/[^\x20-\x7E]/g,``),e.meta?.forEach(e=>{e.description=e.description.replace(/[^\x20-\x7E]/g,``)}),e.meta?.forEach(e=>{e.key=e.key.replace(/([A-Z])/g,`_$1`).toLowerCase()}),e}getDecoupledTopic(e){let[t,n,r]=e.split(`.`);return{plugin:t||`*`,skillCategory:n||`*`,accomplishmentKeyword:r||`*`}}subscribe(e=`*`,t){typeof e==`string`&&(e=[e]),e.forEach(e=>{let n=e.split(`.`).length;if(n===1)e+=`.*.*`;else if(n===2)e+=`.*`;else if(n!==3)throw Error(`Invalid accomplishment topic pattern. The pattern must be plugin.skillCategory.accomplishmentKeyword or an * as wildcard for any plugin, skill category or accomplishment keyword`);this.eventBus.on([`global.accomplishment.triggerMicro`,`global.accomplishment.triggerMacro`],n=>{let{plugin:r,skillCategory:i,accomplishmentKeyword:a}=this.getDecoupledTopic(e);r!==`*`&&n.sender!==r||i!==`*`&&n.data.skillCategory!==i||a!==`*`&&n.data.accomplishmentKeyword!==a||t(n)},[this.pluginId])})}},Me=class{pluginId;accomplishmentController;aiModule;eventBus;constructor(e,t,r){this.pluginId=e,this.aiModule=t,this.eventBus=r??n,this.accomplishmentController=new je(e,this.eventBus),this.eventBus.on([`global.session.triggerUpdate`],e=>{e.data.session_token?this.aiModule.session.set(e.data.session_token):this.aiModule.session.clear()})}getGlobalEventTopic(e){if(e.startsWith(`global.`)||e.startsWith(`self.`))return e;let t=e.split(`.`);if(t.length===3){if(!t[0].startsWith(`pl`)&&t[0]!==`global`)throw Error(`Invalid event topic '${e}'. The topic must start with the plugin id, 'self' or 'global'.`);return e}else if(t.length>3)throw Error(`The event topic must consist of 3 parts. <pluginId>.<topic area>.<action>. Received: ${e}`);return`${this.pluginId??`global`}.${e}`}emit(e,t,n){let r=this.getGlobalEventTopic(e);this.eventBus.emit(this.pluginId,r,t,n)}async request(e,t){let n=this.getGlobalEventTopic(e),r=this.aiModule.session.get()??void 0;return this.eventBus.request(this.pluginId,n,t,r)}on(e,t){let n=Array.isArray(e)?e:[e];return this.eventBus.on(n.map(e=>this.getGlobalEventTopic(e)),e=>{e.ai_session_token&&!this.aiModule.session.get()&&this.aiModule.session.set(e.ai_session_token),t(e)})}once(e,t){this.eventBus.once(this.getGlobalEventTopic(e),t)}respond(e,t){let n=Array.isArray(e)?e:[e],r=t;typeof t==`function`&&(r=async e=>{let n=this.aiModule.session.get();e.ai_session_token&&this.aiModule.session.set(e.ai_session_token);try{return await t(e)}finally{e.ai_session_token&&(n?this.aiModule.session.set(n):this.aiModule.session.clear())}}),this.eventBus.respond(this.pluginId,n.map(e=>this.getGlobalEventTopic(e)),r)}async emitAccomplishment(e){this.accomplishmentController.emitAccomplishment(e)}onAccomplishment(e,t){this.accomplishmentController.subscribe(e,t)}emitSidebarAction(e,t,n,r){this.emit(`global.sidebar.triggerAction`,{plugin_id:e,action_key:t,text:n,args:r})}emitMainPanelAction(e,t,n){this.emit(`global.mainPanel.triggerAction`,{plugin_id:e,action_key:t,...n})}onMainPanelAction(e,t=[]){let n=Array.isArray(t)?t:[t],r=this.on(`action.requestMain`,({data:t})=>{(n.length===0||n.includes(t.action_key))&&e(t)});return this.emit(`action.requestMain`),r}onSidePanelAction(e,t=[]){let n=Array.isArray(t)?t:[t],r=this.on(`action.requestSidebar`,({data:t})=>{(n.length===0||n.includes(t.action))&&e(t)});return this.emit(`action.requestSidebar`),this.eventBus.emit(this.pluginId,`global.session.requestCurrent`,{}),r}},Ne=class{controller;sessionTokenId=null;onRateLimitedCb;constructor(e){this.controller=e}resolvePromptName(e){return e.startsWith(`global.`)?e:e.split(`.`).length===2&&this.controller.pluginId?`${this.controller.pluginId}.${e}`:e}session={get:()=>this.sessionTokenId,set:e=>{this.sessionTokenId=e},clear:()=>{this.sessionTokenId=null}};setOnRateLimited(e){this.onRateLimitedCb=e}async getText(e){let{messages:t,tools:n,cache:r=!1,prompt:i,variables:a}=e,{result:o}=await this.streamObject({cache:r,tools:n,messages:t,prompt:i,variables:a});return o}async getStreamedText(e){let{messages:t,onMessage:n,tools:r,cache:i=!1,prompt:a,variables:o}=e,s=Math.random().toString(36).substring(3),{result:c}=await this.streamObject({cache:i,tools:r,messages:t,prompt:a,variables:o,onResult:({result:e})=>n(s,e,!1)});return n(s,c,!0),c}async getVoice(e,t=`alloy`,n=1,r,i=!1,a){return e.trim().length?await this.controller.fetchBackend(`/voice/tts`,{method:`POST`,body:JSON.stringify({input:e,voice:t,speed:n,language:r,cache:i,instructions:a,session_token_id:this.sessionTokenId??void 0})}).then(e=>e.blob()):(console.warn(`[rimori-client] getVoice called with empty text — skipping TTS request and returning empty Blob.`),new Blob([],{type:`audio/mpeg`}))}async getTextFromVoice(e,t){let n=new FormData;return n.append(`file`,e),t&&n.append(`language`,t.code),this.sessionTokenId&&n.append(`session_token_id`,this.sessionTokenId),await this.controller.fetchBackend(`/voice/stt`,{method:`POST`,body:n}).then(e=>e.json()).then(e=>e.text)}async getObject(e){let{cache:t=!1,tools:n=[],prompt:r,variables:i}=e;return await this.streamObject({messages:[],cache:t,tools:n,prompt:r,variables:i})}async getStreamedObject(e){let{onResult:t,cache:n=!1,tools:r=[],prompt:i,variables:a}=e;return await this.streamObject({messages:[],onResult:t,cache:n,tools:r,prompt:i,variables:a})}async streamObject(e){let{messages:t,onResult:n=()=>null,cache:r=!1,tools:i=[],prompt:a,variables:o}=e,s={cache:r,tools:i,stream:!0,messages:t.map((e,t)=>({...e,id:`${t+1}`})),session_token_id:this.sessionTokenId??void 0};a&&(s.prompt={name:this.resolvePromptName(a),variables:o??{}});let c=await this.controller.fetchBackend(`/ai/llm`,{method:`POST`,body:JSON.stringify(s)});if(!c.ok){if(c.status===429){let e=await c.json().catch(()=>({})),t=e.exercises_remaining??0;throw this.onRateLimitedCb?.(t),Error(`Rate limit exceeded: ${e.error??`Daily exercise limit reached`}. exercises_remaining: ${t}`)}throw Error(`Failed to stream object: ${c.status} ${c.statusText}`)}if(!c.body)throw Error(`No response body.`);let l=c.body.getReader(),u=new TextDecoder(`utf-8`),d={},f=``,p=!0;for(;p;){await new Promise(e=>setTimeout(e,30));let{value:e,done:t}=await l.read();if(t)return p=!1,n(d,!1),d;if(!e)continue;let r=u.decode(e,{stream:!0}),a=(f+r).split(`
|
|
3
|
+
`);f=a.pop()??``;let o=a.filter(e=>e.trim());for(let e of o){if(e.startsWith(`token:`)){try{let t=JSON.parse(e.slice(6).trim());t.token_id&&(this.sessionTokenId=t.token_id)}catch{console.error(`Failed to parse token: line`,e)}continue}if(e.startsWith(`debug:`)){try{let t=JSON.parse(e.slice(6).trim());console.group(`[Rimori Prompt] ${t.promptName}`),console.log(`System prompt:
|
|
4
|
+
`,t.system),console.log(`User prompt:
|
|
5
|
+
`,t.user),console.log(`Variables:`,t.variables),console.groupEnd()}catch{}continue}let t=e.substring(0,5),r=e.substring(5).trim();if(r===`[DONE]`)return p=!1,n(d,!1),d;if(t===`data:`)d=JSON.parse(r),n(d,!0);else if(t===`tool:`){let{toolCallId:e,toolName:t,args:n}=JSON.parse(r),a=i.find(e=>e.name===t);if(a&&a.execute){let t=await a.execute(n);await this.sendToolResult(e,t)}else a&&!a.execute?console.error(`Tool found but has no execute function:`,t):console.error(`Tool not found:`,t)}else t===`error`?console.error(`Error:`,r.substring(1)):t===`info:`||console.error(`Unknown stream data:`,e)}}return d}async sendToolResult(e,t){await this.controller.fetchBackend(`/ai/llm/tool_result`,{method:`POST`,body:JSON.stringify({toolCallId:e,result:t??`[DONE]`})})}},Pe=class{supabase;communicationHandler;eventModule;constructor(e,t,n,r){this.supabase=e,this.communicationHandler=t,this.eventModule=r}async view(){let{data:e,error:t}=await this.supabase.schema(`public`).from(`weekly_exercises`).select(`*`);if(t)throw Error(`Failed to fetch weekly exercises: ${t.message}`);return e||[]}async add(e){let t=Array.isArray(e)?e:[e],n=await this.communicationHandler.fetchBackend(`/exercises`,{method:`POST`,body:JSON.stringify({exercises:t})});if(!n.ok){let e=await n.text();throw Error(`Failed to create exercises: ${e}`)}let r=await n.json();return this.eventModule.emit(`global.exercises.triggerChange`),r}async start(e){return new Promise((t,n)=>{let r=setTimeout(()=>{i.off(),n(Error(`Exercise start timed out: rimori-main did not respond within 5s`))},5e3),i=this.eventModule.on(`global.session.triggerUpdate`,({data:e})=>{e.session_token&&(clearTimeout(r),i.off(),t())});this.eventModule.emit(`global.exercise.triggerStart`,e)})}async delete(e){let t=await this.communicationHandler.fetchBackend(`/exercises/${e}`,{method:`DELETE`});if(!t.ok){let e=await t.text();throw Error(`Failed to delete exercise: ${e}`)}return this.eventModule.emit(`global.exercises.triggerChange`),await t.json()}},Fe=class{controller;constructor(e){this.controller=e}async uploadImage(e){let t=new FormData;t.append(`file`,e,`image.png`);try{let e=await this.controller.fetchBackend(`/plugin-images/upload`,{method:`POST`,body:t});if(!e.ok){let t=await e.json().catch(()=>({}));return{error:Error(t.message??`Upload failed (${e.status})`)}}return{data:await e.json()}}catch(e){return{error:e instanceof Error?e:Error(String(e))}}}},Ie=class e{static instance;controller;sharedContent;db;event;plugin;ai;exercise;storage;eventBus;constructor(e,t,i,a){this.controller=e,this.eventBus=a??n,this.sharedContent=new r(t,this),this.ai=new Ne(e),this.ai.setOnRateLimited(e=>{this.eventBus.emit(i.pluginId,`global.quota.triggerExceeded`,{exercises_remaining:e})}),this.event=new Me(i.pluginId,this.ai,this.eventBus),this.db=new ke(t,e,i),this.plugin=new Ee(t,e,i,this.ai),this.exercise=new Pe(t,e,i,this.event),this.storage=new Fe(e),this.plugin.applicationMode!==`sidebar`&&v.getInstance(this)}static createWithInfo(n){let r=t.create(`Plugin EventBus `+n.pluginId),i=new _(n.pluginId,!0);i.handleRimoriInfoUpdate(n);let a=new e(i,new g(`${n.url}/rest/v1`,{schema:n.dbSchema,headers:{apikey:n.key,Authorization:`Bearer ${n.token}`,"plugin-id":n.pluginId}}),n,r);return r.on(`${n.pluginId}.supabase.triggerUpdate`,e=>{console.log(`[RimoriClient] Federated triggerUpdate received for`,n.pluginId,`| ttsEnabled:`,e.data?.ttsEnabled),i.handleRimoriInfoUpdate(e.data)}),a}static async getInstance(t){if(!e.instance){if(!t)throw Error(`Plugin ID is required`);let n=new _(t,!1),r=await n.getClient();e.instance=new e(n,r.supabase,r.info)}return e.instance}navigation={toDashboard:()=>{this.event.emit(`global.navigation.triggerToDashboard`)}};runtime={fetchBackend:(e,t={})=>this.controller.fetchBackend(e,t)}},Le=class e{static instance;config;supabase;constructor(e){throw Error(`Authentication is disabled until new developer platform is released.`)}static async getInstance(){if(!e.instance){let t=await fetch(`https://app.rimori.se/config.json`).then(e=>e.json()).catch(e=>{console.warn(`Error fetching config.json, using default values`,e)});e.instance=new e({url:t?.SUPABASE_URL||`https://pheptqdoqsdnadgoihvr.supabase.co`,key:t?.SUPABASE_ANON_KEY||`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InBoZXB0cWRvcXNkbmFkZ29paHZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzE2OTY2ODcsImV4cCI6MjA0NzI3MjY4N30.4GPFAXTF8685FaXISdAPNCIM-H3RGLo8GbyhQpu1mP0`,backendUrl:t?.BACKEND_URL||`https://api.rimori.se`})}return e.instance}async getClient(){return this.supabase}async needsLogin(){let{error:e}=await this.supabase.auth.getUser();return e!==null}async login(e,t){let{error:n}=await this.supabase.auth.signInWithPassword({email:e,password:t});return n?(console.error(`Login failed:`,n),!1):(console.log(`Successfully logged in`),!0)}static async initListeners(t){console.warn(`The plugin seams to not be running inside the Rimori platform. Switching to development standalone mode.`);let{supabase:r,config:i}=await e.getInstance();n.respond(`standalone`,`global.supabase.requestAccess`,async()=>{let e=await r.auth.getSession();console.log(`session`,e);let n=null;try{let{data:{user:e}}=await r.auth.getUser();if(e){let{data:t}=await r.from(`profiles`).select(`current_guild_id`).eq(`user_id`,e.id).maybeSingle();n=t?.current_guild_id||null}}catch{n=null}let a=await fetch(`${i.backendUrl}/plugin/token`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.data.session?.access_token}`},body:JSON.stringify({pluginId:t,guildId:n})});if(!a.ok){let e=await a.text();throw Error(`Failed to get plugin token. ${a.status}: ${e}`)}return{token:(await a.json()).token,pluginId:t,url:i.url,key:i.key,backendUrl:i.backendUrl,tablePrefix:t,expiration:new Date(Date.now()+1e3*60*60*1.5)}}),n.on(`*`,async e=>{console.log(`[standalone] would send event to parent`,e)},[`standalone`])}},Re=class{audioContext;chunkQueue=[];isPlaying=!1;analyser;dataArray;shouldMonitorLoudness=!0;isMonitoring=!1;handle=0;volume=1;loudnessCallback=()=>{};currentIndex=0;startedPlaying=!1;onEndOfSpeech=()=>{};backgroundNoiseLevel=30;currentSource=null;stopped=!1;constructor(){this.init()}init(){this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=256;let e=this.analyser.frequencyBinCount;this.dataArray=new Uint8Array(e)}setOnLoudnessChange(e){this.loudnessCallback=e}setVolume(e){this.volume=e}async addChunk(e,t){this.stopped||(console.log(`Adding chunk`,t,e),this.chunkQueue[t]=e,t===0&&!this.startedPlaying&&(this.startedPlaying=!0,this.playChunks()))}playChunks(){if(!(this.isPlaying||this.stopped)){if(!this.chunkQueue[this.currentIndex]){setTimeout(()=>this.playChunks(),10);return}this.isPlaying=!0,this.playChunk(this.chunkQueue[this.currentIndex]).then(()=>{this.isPlaying=!1,!this.stopped&&(this.currentIndex++,this.chunkQueue[this.currentIndex]?(this.shouldMonitorLoudness=!0,this.playChunks()):setTimeout(()=>{this.stopped||(this.chunkQueue.length>this.currentIndex?this.playChunks():(this.startedPlaying=!1,this.shouldMonitorLoudness=!1))},1e3))})}}stopPlayback(){if(this.stopped=!0,this.currentSource){try{this.currentSource.stop()}catch{}this.currentSource=null}this.isPlaying=!1,this.chunkQueue=[],this.startedPlaying=!1,this.shouldMonitorLoudness=!1,cancelAnimationFrame(this.handle),this.loudnessCallback(0)}cleanup(){this.stopPlayback(),this.audioContext&&this.audioContext.state!==`closed`&&this.audioContext.close().catch(e=>{console.warn(`Error closing AudioContext:`,e)})}playChunk(e){return!e||this.stopped?Promise.resolve():new Promise(t=>{let n=this.audioContext.createBufferSource();this.currentSource=n,this.audioContext.decodeAudioData(e.slice(0)).then(e=>{if(this.stopped){t();return}n.buffer=e;let r=this.audioContext.createGain();r.gain.value=this.volume,n.connect(r),r.connect(this.analyser),this.analyser.connect(this.audioContext.destination),n.start(0),r.gain.value=this.volume,n.onended=()=>{this.currentSource===n&&(this.currentSource=null),t()},this.isMonitoring||(this.isMonitoring=!0,this.shouldMonitorLoudness=!0,this.monitorLoudness())})})}async playAgain(){console.log(`Playing again`),this.chunkQueue.length>0&&!this.isPlaying&&this.playChunks()}monitorLoudness(){if(!this.shouldMonitorLoudness){cancelAnimationFrame(this.handle),this.loudnessCallback(0),this.onEndOfSpeech();return}this.analyser.getByteTimeDomainData(this.dataArray);let e=0;for(let t=0;t<this.dataArray.length;t++){let n=this.dataArray[t]/128-1;e+=n*n}let t=Math.sqrt(e/this.dataArray.length);if(t!==0){let e=20*Math.log10(t);e<-57&&(e=-57),e>-15&&(e=-15);let n=(e- -57)/42*100;n=n<this.backgroundNoiseLevel?0:(n-this.backgroundNoiseLevel)/(100-this.backgroundNoiseLevel)*100,this.loudnessCallback(Math.round(n))}this.handle=requestAnimationFrame(()=>this.monitorLoudness())}reset(){this.stopPlayback(),this.stopped=!1,this.currentIndex=0,this.shouldMonitorLoudness=!0,this.isMonitoring=!1,this.isPlaying=!1,this.init()}setOnEndOfSpeech(e){this.onEndOfSpeech=e}},ze=class{player=new Re;fetchedSentences=new Set;lastLoading=!1;voice;voiceBackend;cache;voiceSpeed=1;instructions;constructor(e,t,n=!1){if(t?.split(`_`).length!==2)throw Error(`Invalid voice id format '`+t+`'. Voice id needs to look like <provider>_<voice_id>`);this.voiceBackend=e,this.voice=t,this.cache=n}getCompletedSentences(e,t){let n=/(.+?[.?!]|.+?:\s+|.+?\n+)/g,r=[],i;for(;(i=n.exec(e))!==null;){let e=i[0].trim();e.length>0&&r.push(e)}if(!t){let t=r[r.length-1],n=e.lastIndexOf(t)+t.length;n<e.length&&r.push(e.slice(n).trim())}return r}async handleNewText(e,t){if(!this.lastLoading&&t&&this.reset(),this.lastLoading=t,!e)return;let n=this.getCompletedSentences(e,t);for(let e=0;e<n.length;e++){let t=n[e];if(!this.fetchedSentences.has(t)){this.fetchedSentences.add(t);let n=await this.generateSpeech(t);await this.player.addChunk(n,e)}}}setInstructions(e){this.instructions=e}async generateSpeech(e){return await(await this.voiceBackend(e,this.voice,this.voiceSpeed,void 0,this.cache,this.instructions)).arrayBuffer()}play(){this.player.playAgain()}stop(){this.player.stopPlayback()}cleanup(){this.player.cleanup()}reset(){this.stop(),this.fetchedSentences.clear(),this.player.reset()}setVolume(e){this.player.setVolume(e)}setOnLoudnessChange(e){this.player.setOnLoudnessChange(t=>{e(t)})}setOnEndOfSpeech(e){this.player.setOnEndOfSpeech(e)}setVoiceSpeed(e){this.voiceSpeed=e}},Be=[`Pre-A1`,`A1`,`A2`,`B1`,`B2`,`C1`,`C2`,`Post-C2`];function X(e){return Be.indexOf(e)+1}function Ve(e){return Be[e]}function He(e,t){return Ve(X(e)+t-1)}function Ue(e,t){return X(e)-X(t)}async function We(e,n){Object.assign(globalThis,{window:{isWorker:!0,location:{},parent:{postMessage:()=>{}},addEventListener:()=>{}}}),t.getInstance(`Worker `+e+` EventBus`);let r=await Ie.getInstance(e);console.debug(`[Worker] RimoriClient initialized.`);let i=Error(`[Worker `+e+`] Worker setup must complete within 5s. Use init event (e.g. onboarding.triggerInitPlugin) or run work async.`),a=Promise.resolve(n(r)),o=new Promise((e,t)=>setTimeout(()=>t(i),5e3));await Promise.race([a,o]),console.debug(`[Worker] Worker initialized.`),r.event.emit(`self.rimori.triggerInitFinished`)}var Ge=class{pluginId;constructor(e){this.pluginId=e}async startRecording(){n.emit(this.pluginId,`global.microphone.triggerStartRecording`)}async stopRecording(){return(await n.request(this.pluginId,`global.microphone.triggerStopRecording`)).data}async pauseRecording(){return(await n.request(this.pluginId,`global.microphone.triggerPauseRecording`)).data}async resumeRecording(){return(await n.request(this.pluginId,`global.microphone.triggerResumeRecording`)).data}async getCurrentStatus(){return(await n.request(this.pluginId,`global.microphone.triggerGetCurrentStatus`)).data}},Ke=e({AudioController:()=>Ge,EventBus:()=>n,EventBusHandler:()=>t,MessageSender:()=>ze,ROLE_ORDER:()=>Oe,RimoriClient:()=>Ie,RimoriCommunicationHandler:()=>_,StandaloneClient:()=>Le,StorageModule:()=>Fe,TIER_ORDER:()=>De,Translator:()=>Te,compareLanguageLevels:()=>Ue,getDifficultyLabel:()=>Ve,getDifficultyLevel:()=>X,getNeighborDifficultyLevel:()=>He,setupWorker:()=>We}),qe=e({AudioController:()=>$,EventBus:()=>rt,EventBusHandler:()=>nt,MessageSender:()=>ot,ROLE_ORDER:()=>et,RimoriClient:()=>it,RimoriCommunicationHandler:()=>dt,StandaloneClient:()=>at,StorageModule:()=>tt,TIER_ORDER:()=>$e,Translator:()=>Qe,__moduleExports:()=>Ye,compareLanguageLevels:()=>ut,default:()=>Xe,getDifficultyLabel:()=>ct,getDifficultyLevel:()=>st,getNeighborDifficultyLevel:()=>lt,setupWorker:()=>Ze}),Z=`__mf_module_cache__`;globalThis[Z]||={share:{},remote:{}},globalThis[Z].share||={},globalThis[Z].remote||={};var Je=globalThis[Z],Q=Je.share[`@rimori/client`];Q===void 0&&(Q=Ke,Je.share[`@rimori/client`]=Q);var Ye=Q,Xe=Q.__esModule?Q.default:Q.default??Q,{setupWorker:Ze,AudioController:$,Translator:Qe,TIER_ORDER:$e,ROLE_ORDER:et,StorageModule:tt,EventBusHandler:nt,EventBus:rt,RimoriClient:it,StandaloneClient:at,MessageSender:ot,getDifficultyLevel:st,getDifficultyLabel:ct,getNeighborDifficultyLevel:lt,compareLanguageLevels:ut,RimoriCommunicationHandler:dt}=Q;export{it as a,Ke as c,rt as i,ot as n,at as o,nt as r,qe as s,$ as t};
|