1var it=Object.defineProperty;var st=(i,e,t)=>e in i?it(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var f=(i,e,t)=>st(i,typeof e!="symbol"?e+"":e,t);import{X as Ie}from"./dexie2jmnBxhj.js";import{a as we,c as v,cX as rt,cY as nt,aP as ct,cZ as ot,c_ as dt,f as m,cC as T,b as ze,e as Ve,S as He,r as ut,K as lt,a1 as yt,R as E,c$ as ke,d0 as pt,V as mt,aY as ft,d1 as ht,d2 as gt}from"./chunkReloadRecoveryC4XyrbqR.js";function It(i){if(i instanceof Date){const e=i.getTime();return Number.isFinite(e)?e:0}if(typeof i=="number")return Number.isFinite(i)?i:0;if(typeof i=="string"&&i.length>0){const e=Date.parse(i);return Number.isFinite(e)?e:0}return 0}function wt(i,e=Date.now()){if(!i)return 0;const t=i.details||{},a=i.feedback||{},s=[t.createdAt,t.updatedAt,a.lastVisit,a.visitTime,a.starredDate,a.isReadDate,a.isReadLaterDate,a.reactionDate,a.archivedDate];let r=0;for(const n of s){const c=It(n);c>r&&(r=c)}return r>e?e:r}const bt=6e4;let Te=Number.NEGATIVE_INFINITY,te=null;function At(i){return!(i!=null&&i.isCustomServer)||!i.apiURL||v.privatelyHosted?!1:/^https?:\/\//i.test(i.apiURL)}function St(i){try{return new URL(i).hostname||null}catch{return null}}async function vt(i,e){const t=i.apiURL,a=St(t),s=Array.from(new Set([a,...rt].filter(n=>!!n))),r=await(e.discover??nt)({hostnames:s,ports:ot,subnetPrefix:ct(a),timeoutMs:2e3,lanTimeoutMs:1200});return r.some(n=>n.apiURL===t)||r.length!==1?!1:(await(e.update??dt)({apiURL:r[0].apiURL,isCustomServer:!0}),!0)}async function kt(i,e={}){if(!i||!At(i))return!1;if(te)return te;const t=e.now??Date.now;return t()-Te<bt?!1:(Te=t(),te=vt(i,e).catch(()=>!1).finally(()=>{te=null}),te)}async function Tt(){const i=await we();return kt(i)}async function Kt(i,e={}){m("[REQ] FETCHING",i);const{timeout:t=8e3}=e,a=new AbortController,s=setTimeout(()=>a.abort(),t),r=await fetch(i,{...e,signal:a.signal});return clearTimeout(s),r}const Et={enabled:!1,persistToIdb:!1,detailed:!1,maxTracesInMemory:200,maxSpansPerTrace:500,maxEventsPerTrace:500,maxTextPreviewLen:160},Ke="TRACE_CONFIG_V1";function ye(){try{return performance.now()}catch{return Date.now()}}function q(){const i=globalThis.crypto;return i!=null&&i.randomUUID?i.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}function Rt(i,e){return typeof i!="string"?void 0:i.length>e?i.slice(0,e):i}function ae(i,e,t="safe"){if(!i)return;const a={};for(const[s,r]of Object.entries(i))if(r!=null){if(t==="sensitive"&&!e.detailed){(typeof r=="number"||typeof r=="boolean")&&(a[s]=r);continue}if(typeof r=="string"){a[s]=e.detailed?Rt(r,e.maxTextPreviewLen):void 0,a[s]===void 0&&r.length<=80&&(a[s]=r);continue}if(typeof r=="number"||typeof r=="boolean"){a[s]=r;continue}if(Array.isArray(r)){a[s]=r.length<=10?r:r.slice(0,10);continue}a[s]=e.detailed?r:void 0}for(const s of Object.keys(a))a[s]===void 0&&delete a[s];return Object.keys(a).length?a:void 0}function Ee(i){return{...i,spans:i.spans.map(e=>({...e,attrs:e.attrs?{...e.attrs}:void 0})),events:i.events.map(e=>({...e,attrs:e.attrs?{...e.attrs}:void 0})),attrs:i.attrs?{...i.attrs}:void 0}}class Mt{constructor(){f(this,"cfg",{...Et});f(this,"initialized",!1);f(this,"lastConfigLoadEpochMs",0);f(this,"backgroundInitPromise",null);f(this,"active",new Map);f(this,"recent",[])}
1async init(){this.initialized=!0;const e=Date.now();if(!(e-this.lastConfigLoadEpochMs<1500)){this.lastConfigLoadEpochMs=e;try{const t=await T.kvGet(Ke);t&&typeof t=="object"&&(this.cfg={...this.cfg,...t})}catch{}}}getConfig(){return{...this.cfg}}initInBackground(){this.backgroundInitPromise||(this.backgroundInitPromise=this.init().finally(()=>{this.backgroundInitPromise=null}))}async setConfig(e){this.cfg={...this.cfg,...e};try{await T.kvSet(Ke,this.cfg)}catch{}}isEnabled(){return this.cfg.enabled===!0}isEnabledFast(){return this.cfg.enabled===!0}isDetailedFast(){return this.cfg.detailed===!0}shouldPersistFast(){return this.cfg.persistToIdb===!0}persistActiveSnapshot(e){if(!this.shouldPersistFast())return;const t=this.active.get(e);if(!t)return;const a=Ee(t);a.status="active",a.durationMs=Math.max(0,Date.now()-a.startedAtEpochMs),T.upsertTrace(a).catch(s=>{m("[TRACE] active snapshot persist failed (non-fatal)",s)})}startTrace(e,t,a){if(!this.cfg.enabled)return(a==null?void 0:a.traceId)||q();const s=(a==null?void 0:a.traceId)||q(),r=Date.now(),n={traceId:s,name:e,startedAtEpochMs:r,status:"active",spans:[],events:[],privacy:(a==null?void 0:a.privacy)||"safe",attrs:ae(t,this.cfg,(a==null?void 0:a.privacy)||"safe"),version:1};return this.active.set(s,n),this.persistActiveSnapshot(s),s}startSpan(e,t,a,s){if(!this.cfg.enabled)return q();const r=this.active.get(e);if(!r||r.spans.length>=this.cfg.maxSpansPerTrace)return q();const n=q(),c=ye();r.spans.push({spanId:n,parentSpanId:s==null?void 0:s.parentSpanId,name:t,startPerfMs:c,privacy:(s==null?void 0:s.privacy)||"safe",attrs:ae(a,this.cfg,(s==null?void 0:s.privacy)||"safe")});try{performance.mark(`trace:${e}:${n}:start`)}catch{}return this.persistActiveSnapshot(e),n}endSpan(e,t,a,s="ok"){if(!this.cfg.enabled)return;const r=this.active.get(e);if(!r)return;const n=r.spans.find(d=>d.spanId===t);if(!n||n.endPerfMs!=null)return;n.endPerfMs=ye(),n.durationMs=Math.max(0,n.endPerfMs-n.startPerfMs),n.status=s;const c=ae(a,this.cfg,n.privacy||"safe");c&&(n.attrs={...n.attrs||{},...c});try{performance.mark(`trace:${e}:${t}:end`),performance.measure(`trace:${e}:${n.name}`,`trace:${e}:${t}:start`,`trace:${e}:${t}:end`)}catch{}this.persistActiveSnapshot(e)}event(e,t,a,s){if(!this.cfg.enabled)return;const r=this.active.get(e);r&&(r.events.length>=this.cfg.maxEventsPerTrace||(r.events.push({eventId:q(),name:t,atPerfMs:ye(),privacy:(s==null?void 0:s.privacy)||"safe",attrs:ae(a,this.cfg,(s==null?void 0:s.privacy)||"safe")}),this.persistActiveSnapshot(e)))}async finishTrace(e,t,a="ok"){if(!this.cfg.enabled)return null;const s=this.active.get(e);if(!s)return null;const r=s.privacy||"safe";this.active.delete(e),s.endedAtEpochMs=Date.now(),s.durationMs=Math.max(0,s.endedAtEpochMs-s.startedAtEpochMs),s.status=a;const n=ae(t,this.cfg,r);n&&(s.attrs={...s.attrs||{},...n});try{const[c,d]=await Promise.all([T.getAccountId(),T.getUserId()]);s.accountId=c,s.userId=d}catch{}if(this.recent.unshift(s),this.recent.length>this.cfg.maxTracesInMemory&&(this.recent.length=this.cfg.maxTracesInMemory),m("[TRACE] trace finished",{traceId:s.traceId,name:s.name,durationMs:s.durationMs,spans:s.spans.length,events:s.events.length,status:a}),this.cfg.persistToIdb)try{await T.upsertTrace(s)}catch(c){m("[TRACE] persist failed (non-fatal)",c)}return s}getRecentTraces(e=50){return this.recent.slice(0,Math.max(0,e))}getActiveTraces(e=50){return Array.from(this.active.values()).sort((a,s)=>(s.startedAtEpochMs||0)-(a.startedAtEpochMs||0)).slice(0,Math.max(0,e)).map(a=>{const s=Ee(a);return s.status="active",s.durationMs=Math.max(0,Date.now()-s.startedAtEpochMs),s})}getActiveTrace(e){return this.active.get(e)||null}clearInMemory(){this.active.clear(),this.recent.length=0}async getPersistedTraces(e=200){try{return await T.listTraces(e)}catch{return[]}}async getPersistedTrace(e){try{return await T.getTrace(e)}catch{return null}}async clearPersistedTraces(){await T.clearTraces()}}const J=new Mt,D=globalThis.crypto??(typeof window<"u"?window.crypto:void 0);if(!D)throw new Error("Web Crypto API is not available in this runtime.");const Q=class Q{static get instance(){return Q._staticInstance||(Q._staticInstance=new TextDecoder("utf-8")),Q._staticInstance}};f(Q,"_staticInstance");let Re=Q;const X=class X{static get instance(){return X._staticInstance||(X._staticInstance=new TextEncoder),X._staticInstance}};f(X,"_staticInstance");let ue=X,ie=D;const pe=6e5,Me=1e5;class o{static randomUUID(){if(!ie)throw new Error("KM: WebCrypto not available");return ie.randomUUID()}static randomSaltString(e=16){const t=D.getRandomValues(new Uint8Array(e));return Array.from(t,a=>a.toString(16).padStart(2,"0")).join("")}static ab2strLim(e){const t=String.fromCharCode(...new Uint8Array(e instanceof Uint8Array?e.buffer:e));return btoa(t)}static ab2str(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let a="";for(let s=0;s<t.length;s++)a+=String.fromCharCode(t[s]);return btoa(a)}static ab2strPlain(e){return String.fromCharCode(...e instanceof Uint8Array?e:new Uint8Array(e))}static str2abx(e){const t=new ArrayBuffer(e.length);return new Uint8Array(t).set(new Uint8Array(e.split("").map(s=>s.charCodeAt(0)))),t}static str2ab(e){const t=(e||"").trim().replace(/-/g,"+").replace(/_/g,"/"),a=t+"===".slice((t.length+3)%4),s=atob(a),r=s.length,n=new Uint8Array(r);for(let c=0;c<r;c++)n[c]=s.charCodeAt(c);return n.buffer}static str2abV0(e){for(var t=new ArrayBuffer(e.length),a=new Uint8Array(t),s=0,r=e.length;s<r;s++)a[s]=e.charCodeAt(s);return t}static ab2strUTF(e){return new TextDecoder("utf-8").decode(e instanceof Uint8Array?e:new Uint8Array(e))}static str2abUTF(e){return new TextEncoder().encode(e).buffer}static ab2base64(e){const t=String.fromCharCode(...new Uint8Array(e));return btoa(t)}static base642ab(e){const t=atob(e),a=t.length,s=new Uint8Array(a);for(let r=0;r<a;r++)s[r]=t.charCodeAt(r);return s.buffer}static base64ToBytes(e){const t=atob(e);return Uint8Array.from(t,a=>a.codePointAt(0))}static bytesToBase64(e){const t=String.fromCodePoint(...e);return btoa(t)}static ab2base64_x(e){return o.bytesToBase64(new Uint8Array(e))}static base642ab_x(e){return o.base64ToBytes(e).buffer}static ab2base64_NA(e){let t="";const a=new Uint8Array(e),s=a.byteLength;for(let r=0;r<s;r++)t+=String.fromCharCode(a[r]);return btoa(t)}static base642ab_NA(e){m("Base64",e);const t=atob(e),a=t.length,s=new Uint8Array(a);for(let r=0;r<a;r++)s[r]=t.charCodeAt(r);return s.buffer}static keyFieldsToId(e){return`${e.groupType}:${e.groupId}:${e.keyType}_${e.keyName}.v${e.version}`}static getUserSecretKeyId(e){return o.keyFieldsToId({groupType:"user",groupId:e,keyType:"sym",keyName:"default",version:0})}static getRecoveryKeyId(e){return o.keyFieldsToId({groupType:"user",groupId:e,keyType:"sym",keyName:"recovery",ver
1sion:0})}static getPasskeyKeyId(e){return o.keyFieldsToId({groupType:"user",groupId:e,keyType:"sym",keyName:"passkey",version:0})}static getDiscoverablePasskeyKeyId(e){return o.keyFieldsToId({groupType:"user",groupId:e,keyType:"sym",keyName:"passkeyDiscoverable",version:0})}static getAcntSecretKeyId(e){return o.keyFieldsToId({groupType:"acnt",groupId:e,keyType:"sym",keyName:"default",version:0})}static getAcntAdminSecretKeyId(e){return o.keyFieldsToId({groupType:"acnt",groupId:e,keyType:"sym",keyName:"admin",version:0})}static getUserPublicKeyId(e){return o.keyFieldsToId({groupType:"user",groupId:e,keyType:"pub",keyName:"default",version:0})}static getAcntPublicKeyId(e){return o.keyFieldsToId({groupType:"acnt",groupId:e,keyType:"pub",keyName:"default",version:0})}static keyInfoToId(e,t=0){return e.groupType==="user"&&e.keyName==="password"?"userPassword":o.keyFieldsToId({groupType:e.groupType,groupId:e.groupId,keyType:e.keyType,keyName:e.keyName,version:t})}static invKeyInfoToId(e,t=0){return e.keyType==="pvt"?o.keyInfoToId({...e,keyType:"pub"},t):e.keyType==="pub"?o.keyInfoToId({...e,keyType:"pvt"},t):o.keyInfoToId(e,t)}static serializeAlgo(e){let t={};for(let a in e)if(a==="publicExponent"||a==="publicExpponent"){const s=e.publicExponent??e.publicExpponent,r=o.ab2str(s);t.publicExponent=r,t.publicExpponent=r}else t[a]=e[a];return t}static deserializeAlgo(e){let t={};for(let a in e)if(a==="publicExponent"||a==="publicExpponent"){const s=e[a];let r;if(typeof s=="string")r=o.str2ab(s);else if(s instanceof ArrayBuffer)r=s;else if(ArrayBuffer.isView(s))r=new Uint8Array(s.buffer,s.byteOffset,s.byteLength).slice().buffer;else if(Array.isArray(s))r=new Uint8Array(s).buffer;else if(s&&typeof s=="object"&&Array.isArray(s.data))r=new Uint8Array(s.data).buffer;else if(s&&typeof s=="object"){const n=Object.entries(s).filter(([c,d])=>/^[0-9]+$/.test(c)&&typeof d=="number").sort((c,d)=>Number(c[0])-Number(d[0])).map(([,c])=>c);if(n.length>0)r=new Uint8Array(n).buffer;else throw new Error(`KM:Unsupported publicExponent type: ${Object.prototype.toString.call(s)}`)}else throw new Error(`KM:Unsupported publicExponent type: ${typeof s}`);t.publicExponent=r,t.publicExpponent=r}else t[a]=e[a];return t}static async createSecretKey(e,t,a,s=["wrapKey","unwrapKey","encrypt","decrypt"]){const r={name:"AES-GCM",length:256},n=await ie.subtle.generateKey(r,!0,s),c={groupType:e,groupId:t,keyType:"sym",keyName:a,keyAlgo:r,keyOps:s};return{keyId:o.keyInfoToId(c),keyInfo:c,key:n}}static async createKeyGroup(e,t){m("createKeyGroup",e,t);const a={name:"RSA-OAEP",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},s=["encrypt","decrypt","wrapKey","unwrapKey"],{publicKey:r,privateKey:n}=await D.subtle.generateKey(a,!0,s),c={groupType:e,groupId:t,keyType:"pub",keyName:"default",keyAlgo:a,keyOps:s},d={keyId:o.keyInfoToId(c),keyInfo:c,key:r},l={groupType:e,groupId:t,keyType:"pvt",keyName:"default",keyAlgo:a,keyOps:s},u={keyId:o.keyInfoToId(l),keyInfo:l,key:n},h=await o.createSecretKey(e,t,"default");return{publicKey:d,privateKey:u,secret:h}}static async createPasswordKey(e,t,a="password",s=pe){if(typeof e!="string"||e.length===0)throw new Error("createPasswordKey: refusing to derive a key from an empty password");if(typeof t!="string"||t.length===0)throw new Error("createPasswordKey: refusing to derive a key from an empty salt");const r=ue.instance,n=await ie.subtle.importKey("raw",r.encode(e),"PBKDF2",!1,["deriveKey"]),c={name:"PBKDF2",salt:r.encode(t),iterations:s,hash:"SHA-256"},d={name:"AES-GCM",length:256},l=["wrapKey","unwrapKey","encrypt","decrypt"],u=await ie.subtle.deriveKey(c,n,d,!1,l),h={groupType:"user",groupId:"default",keyType:"sym",keyName:a,keyAlgo:d,keyOps:l,kdfIterations:s,kdfSalt:t};return{keyId:o.keyInfoToId(h),keyInfo:h,key:u}}static async wrapKey(e,t){const a=D.getRandomValues(new Uint8Array(12)),s=await D.subtle.exportKey("jwk",e.key),n=ue.instance.encode(JSON.stringify(s)),c=await D.subtle.encrypt({name:t.keyInfo.keyAlgo.name,iv:a},t.key,n);return{keyId:e.keyId,wrappingKeyId:t.keyId,unwrappingKeyId:o.invKeyInfoToId(t.keyInfo),keyInfo:e.keyInfo,iv:a,wrappedData:c,wrappingKeyGroup:t.keyInfo.groupType,wrappingKdfIterations:t.keyInfo.kdfIterations,wrappingKdfSalt:t.keyInfo.kdfSalt}}static async unwrapKey(e,t){var d,l;if(!e||!t)throw new Error("Invalid input: wrappedKey and unwrappingKey are required");if(!((l=(d=t.keyInfo)==null?void 0:d.keyAlgo)!=null&&l.name))throw new Error("Invalid unwrappingKey: missing algorithm information");const a={name:t.keyInfo.keyAlgo.name,iv:e.iv},s=await D.subtle.decrypt(a,t.key,e.wrappedData),r=JSON.parse(o.ab2strPlain(s)),n=r,c=await D.subtle.importKey("jwk",n,e.keyInfo.keyAlgo,!0,r.key_ops);return{keyId:e.keyId,key:c,keyInfo:e.keyInfo}}static async serializeWrappedKey(e,t){const a=o.serializeAlgo(e.keyInfo.keyAlgo),s={...e.keyInfo,keyAlgo:a};return{keyId:e.keyId,iv:o.ab2str(e.iv),data:o.ab2str(e.wrappedData),wrappingKeyId:e.wrappingKeyId,wrappingKeyGroup:e.wrappingKeyGroup,unwrappingKeyId:e.unwrappingKeyId,keyInfo:s,format:"wrapped",permission:t,kdfIterations:e.wrappingKdfIterations,kdfSalt:e.wrappingKdfSalt}}static async deserializeSerializedWrappedKey(e){const t=o.deserializeAlgo(e.keyInfo.keyAlgo),a={...e.keyInfo,keyAlgo:t};return{keyId:e.keyId,iv:o.str2ab(e.iv),wrappedData:o.str2ab(e.data),wrappingKeyId:e.wrappingKeyId,wrappingKeyGroup:e.wrappingKeyGroup,unwrappingKeyId:e.unwrappingKeyId,keyInfo:a}}static async keyEntryToWrappedKey(e){if(e.keyData==null||e.keyData.wrappedKey==null||e.keyData.iv==null||e.wrappingKeyId==null||e.wrappingKeyGroup==null||e.unwrappingKeyId==null)throw new Error("Ke
1y entry is not wrapped: "+e.keyId);const a={keyAlgo:o.deserializeAlgo(e.keyAlgo)||{},keyType:e.keyType,keyName:e.keyName,groupId:e.groupId,groupType:e.groupType},s=o.str2ab(e.keyData.wrappedKey),r=o.str2ab(e.keyData.iv);return{keyId:e.keyId,wrappingKeyId:e.wrappingKeyId,wrappingKeyGroup:e.wrappingKeyGroup,unwrappingKeyId:e.unwrappingKeyId,keyInfo:a,iv:r,wrappedData:s,wrappingKdfIterations:e.keyData.kdfIterations,wrappingKdfSalt:e.keyData.kdfSalt}}static async keyEntryToKeyInstance(e){if(e.isWrapped)throw new Error("Key entry is wrapped");const t=o.deserializeAlgo(e.keyAlgo)||{},a=e.keyOps||["encrypt","decrypt"],s=JSON.parse(e.keyData.data),r={keyAlgo:t,keyType:e.keyType,keyName:e.keyName,groupId:e.groupId,groupType:e.groupType,keyOps:a};m("[KM] Importing key",e);const n=await D.subtle.importKey(e.keyData.format,s,t,!0,s.key_ops);return{keyId:e.keyId,key:n,keyInfo:r}}static async serializeKey(e,t="self"){const a=await D.subtle.exportKey("jwk",e.key),s=o.serializeAlgo(e.keyInfo.keyAlgo),r={...e.keyInfo,keyAlgo:s};return{keyId:e.keyId,format:"jwk",data:JSON.stringify(a),keyInfo:r,permission:t}}static async getSymmetricKeyString(e){const t=await o.serializeKey(e,"self"),a=JSON.parse(t.data);return typeof(a==null?void 0:a.k)=="string"?a.k:null}static async deserializeKey(e){const t=JSON.parse(e.data),a=o.deserializeAlgo(e.keyInfo.keyAlgo)||{name:"RSA-OAEP",hash:"SHA-256"},s=await D.subtle.importKey("jwk",t,a,!0,t.key_ops);return{keyId:e.keyId,key:s,keyInfo:e.keyInfo}}static async serializedWrappedKeyToKeyEntry(e){const t={iv:e.iv,wrappedKey:e.data};e.kdfIterations!=null&&(t.kdfIterations=e.kdfIterations),e.kdfSalt!=null&&(t.kdfSalt=e.kdfSalt);const a=e.keyInfo.keyAlgo;return{keyId:e.keyId,groupId:e.keyInfo.groupId,groupType:e.keyInfo.groupType,keyType:e.keyInfo.keyType,keyName:e.keyInfo.keyName,keyAlgo:a,isWrapped:!0,version:"0",keyData:t,wrappingKeyId:e.wrappingKeyId,unwrappingKeyId:e.unwrappingKeyId,wrappingKeyGroup:e.wrappingKeyGroup,keyOps:e.keyInfo.keyOps||[],permission:e.permission}}static async serializedKeyToKeyEntry(e){const t=e.keyInfo.keyAlgo;return{keyId:e.keyId,groupId:e.keyInfo.groupId,groupType:e.keyInfo.groupType,keyType:e.keyInfo.keyType,keyName:e.keyInfo.keyName,keyAlgo:t,isWrapped:!1,version:"0",keyData:{format:e.format,data:e.data},keyOps:e.keyInfo.keyOps||[],permission:e.permission}}static async serializedKeyThingToKeyEntry(e){return e.format=="wrapped"?o.serializedWrappedKeyToKeyEntry(e):o.serializedKeyToKeyEntry(e)}static async serializedKeyMapToKeyEntries(e){const t=[];for(const a of Object.values(e))a&&t.push(await o.serializedKeyThingToKeyEntry(a));return t}static async generateUserKeys(e,t,a){const s=v.passwordKdfV2Enabled,r=s?pe:Me,n=s?o.randomSaltString():a,c=t?await o.createPasswordKey(t,n,"password",r):null,{publicKey:d,privateKey:l,secret:u}=await o.createKeyGroup("user",e),h=c?await o.wrapKey(u,c):null,p=await o.wrapKey(l,u),{recoveryKeyWrapped:y,recoverySecretWrapped:g}=await o.generateRecoveryKeys(e,u);return{passwordKey:c,publicKey:d,privateKey:l,privateKeyWrapped:p,secret:u,secretWrapped:h,recoveryKeyWrapped:y,recoverySecretWrapped:g}}static async generateRecoveryKeys(e,t){const a=await o.createSecretKey("user",e,"recovery"),s=await o.wrapKey(a,t),r=await o.wrapKey(t,a);return{recoveryKeyWrapped:s,recoverySecretWrapped:r}}static async generateUserKeysWithSecret(e,t){const{publicKey:a,privateKey:s,secret:r}=await o.createKeyGroup("user",e),n=await o.wrapKey(r,t),c=await o.wrapKey(s,r),{recoveryKeyWrapped:d,recoverySecretWrapped:l}=await o.generateRecoveryKeys(e,r);return{publicKey:a,privateKey:s,privateKeyWrapped:c,secret:r,secretWrapped:n,recoveryKeyWrapped:d,recoverySecretWrapped:l}}static async generateNewPasswordWrappedKey(e,t,a){const s=v.passwordKdfV2Enabled,r=s?pe:Me,n=s?o.randomSaltString():t,c=await o.createPasswordKey(e,n,"password",r),d=await o.wrapKey(a,c);return{passwordKey:c,secret:a,secretWrapped:d}}static async generateAccountKeys(e){const{publicKey:t,privateKey:a,secret:s}=await o.createKeyGroup("acnt",e),r=await o.wrapKey(a,s);return{publicKey:t,privateKey:a,privateKeyWrapped:r,secret:s}}static async generateGroupKey(e,t,a,s){const r=await o.createSecretKey(e,t,a),n=await o.wrapKey(r,s);return{secret:r,secretWrapped:n}}static async generateNewAccountKeyBundleForExistingUser(e,t){m("[KM] Generating account keys for existing user");const a=await o.generateAccountKeys(e),s=await o.wrapKey(a.secret,t),r={usersCopyOfAcntSecret:await o.serializeWrappedKey(s,"user")},n={acntPrivateKeyWrapped:await o.serializeWrappedKey(a.privateKeyWrapped,"user"),acntPublicKey:await o.serializeKey(a.publicKey,"public")};return{user:r,acnt:n}}static async generateUserKeyBundleForNewAccount(e,t,a,s){m("[KM] Generating user keys for new account");const r=await o.generateUserKeys(e,a,s),n=await o.generateAccountKeys(t),c=await o.wrapKey(n.secret,r.secret),d={userPublicKey:await o.serializeKey(r.publicKey,"public"),userSecretWrapped:r.secretWrapped?await o.serializeWrappedKey(r.secretWrapped,"self"):void 0,userPrivateKeyWrapped:await o.serializeWrappedKey(r.privateKeyWrapped,"user"),usersCopyOfAcntSecret:await o.serializeWrappedKey(c,"user"),userRecoveryKeyWrapped:await o.serializeWrappedKey(r.recoveryKeyWrapped,"user"),userRecoverySecretWrapped:await o.serializeWrappedKey(r.recoverySecretWrapped,"user")},l={acntPrivateKeyWrapped:await o.serializeWrappedKey(n.privateKeyWrapped,"user"),acntPublicKey:await o.serializeKey(n.publicKey,"public")};return{user:d,acnt:l,userSecretKeyString:await o.getSymmetricKeyString(r.secret)}}static async generateUserKeyBundleWithAccountSecretKey(e,t){m("[KM] Generating user keys for existing account");const a=await o.generateUserKeysWithSecret(e,t),s={userPublicKey:await o.serializeKey(a.publicKey,"public"),userPrivateKeyWrapped:await o.serializeWrappedKey(a.privateKeyWrapped,"user"),userRecoveryKeyWrapped:await o.serializeWrappedKey(a.recoveryKeyWrapped,"user"),userRecoverySecretWrapped:await o.serializeWrappedKey(a.recoverySecretWrapped,"user")},r={userSecretWrapped:await o.serializeWrappedKey(a.secretWrapped,"user")};return{user:s,acnt:r}}static async generateUserKeyBundleForExistingAccount(e,t,a,s,r,n
1){m("[KM] Generating user keys for existing account");const c=await o.generateUserKeys(e,t,a),d=await o.wrapKey(s,c.secret),l={userPublicKey:await o.serializeKey(c.publicKey,"public"),userSecretWrapped:c.secretWrapped?await o.serializeWrappedKey(c.secretWrapped,"self"):void 0,userPrivateKeyWrapped:await o.serializeWrappedKey(c.privateKeyWrapped,"user"),usersCopyOfAcntSecret:await o.serializeWrappedKey(d,"user"),userRecoveryKeyWrapped:await o.serializeWrappedKey(c.recoveryKeyWrapped,"user"),userRecoverySecretWrapped:await o.serializeWrappedKey(c.recoverySecretWrapped,"user")};if(n==="admin"){const u=await o.wrapKey(c.secret,r);l.usersCopyOfAcntAdminSecret=await o.serializeWrappedKey(u,"user")}else l.adminsCopyOfUserSecret=await o.serializeWrappedKey(await o.wrapKey(c.secret,r),"admin");return Object.values(l).forEach(u=>{if(!u)throw new Error("Key is null");m("userKeys ",u.keyId,", permission",u.permission)}),l}static async generateUserKeyBundle(e,t,a){m("[KM] Generating user keys for existing account");const s=await o.generateUserKeys(e,t,a);return{userPublicKey:await o.serializeKey(s.publicKey,"public"),userSecretWrapped:s.secretWrapped?await o.serializeWrappedKey(s.secretWrapped,"self"):void 0,userPrivateKeyWrapped:await o.serializeWrappedKey(s.privateKeyWrapped,"user"),userRecoveryKeyWrapped:await o.serializeWrappedKey(s.recoveryKeyWrapped,"user"),userRecoverySecretWrapped:await o.serializeWrappedKey(s.recoverySecretWrapped,"user")}}static async hashPassword(e,t){const s=new TextEncoder().encode(e+t),r=await D.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(r)).map(d=>d.toString(16).padStart(2,"0")).join("")}}const De="kindredClientId";let G=null;async function be(){return G||(G=await ze(De),G||(G="CLID_"+await o.randomUUID(),await Ve(De,G)),G)}async function fa(){const i=await be(),e=v.clientVersion,t=v.appId,a=v.appVersion,s=v.appType;return{clientId:i,clientVersion:e,appId:t,appVersion:a,appType:s}}const Dt=["/","/auth/signin","/auth/signinlocal","/auth/register","/auth/tokenLogin","/auth/providerLogin/fail","/auth/recoverAccountAccess","/auth/resetPassword","/auth/resetPasswordRequest","/auth/recoverPassword","/auth/startEmailVerification","/auth/completeEmailVerification","/auth/genUniqueUsername","/auth/providerLogin/create","/auth/providerLogin/status","/auth/providerLogin/verify","/auth/providerLogin/confirmSession","/auth/provider/apple","/auth/passkey/challenge","/auth/passkey/login","/admin/signin","/invite/checkCode","/invite/getInfo","/published/get","/published/listChildren","/published/view","/published/countView","/published/filteredSearch","/published/categoryCoverage","/published/listRecent","/published/listForMap","/published/matchForURL","/published/collectionsByUser","/published/reviewsByUser","/published/getGalleryGroupAndItems","/published/listGroupIdsForGallery","/published/listWithIds","/published/listWithChild","/published/collectionItemFeed","/curationReview/listForItem","/thinkingPuzzles/catalog","/user/public/get","/review/listForItem","/realm/restore/list","/realm/restore/preflight","/realm/restore/run","/realm/claim/list","/realm/claim/withPassword","/system/status","/system/version","/system/contactRequest","/plugin/list","/plans/list","/store/config","/serverSettings/get","/serverSettings/discover","/serverSettings/checkUrl","/pubfile/get","/data/categories"];function me(i){return Dt.includes(i)}const Ue="kindredHostDevice";let Y;async function qe(){if(Y!==void 0)return Y;try{const i=await ze(Ue);Y=i&&i.deviceId?i:null}catch{Y=null}return Y}async function ha(i){const e=String((i==null?void 0:i.deviceId)||"").trim();if(!e)return;const t=String((i==null?void 0:i.deviceName)||"").trim(),a=await qe();if((a==null?void 0:a.deviceId)===e&&((a==null?void 0:a.deviceName)||"")===t)return;const s=t?{deviceId:e,deviceName:t}:{deviceId:e};Y=s;try{await Ve(Ue,s)}catch{}}const Ct=new TextEncoder;function re(i){return Ct.encode(i).length}function Lt(i){return re(typeof i=="string"?i:JSON.stringify(i))}function Pt(i){var t;const e=Number((t=i.headers)==null?void 0:t.get("content-length"));return Number.isFinite(e)&&e>=0?e:void 0}function xt(i){const e=i;return{sentBytes:e.sentBytes,receivedBytes:e.receivedBytes}}function _t(i,e){return ft()&&!!i&&!!e}function Ot(){var i;return v.appType==="electron"&&typeof window<"u"&&!!((i=window.electron)!=null&&i.request)}async function Bt(i){const e=Object.entries(i.headers||{}).reduce((r,[n,c])=>(c!=null&&(r[n]=String(c)),r),{}),t=await window.electron.request({path:i.path,method:i.method==="POST"?"POST":"GET",headers:e,body:i.bodyOutput});if(!(t!=null&&t.ok)){const r=new Response(JSON.stringify({success:!1,message:(t==null?void 0:t.error)||"request failed"}),{status:503,headers:{"Content-Type":"application/json"}});return r.sentBytes=i.sentBytes,r.receivedBytes=0,r}const a=t.body??"",s=new Response(a,{status:t.status,headers:t.headers||{}});
1return s.sentBytes=i.sentBytes,s.receivedBytes=re(a),s}function Nt(i,e,t){const a=i>=500,s=e.toLowerCase().includes("text/html")||t.trim().startsWith("<");return a||s?{message:"Uh oh â the server is unavailable right now. ð¡ Try again in a moment.",errorType:"CONNECTION_FAILED"}:{message:"Uh oh â I couldn't read the server response. ð¡ Please try again.",errorType:"MALFORMED"}}async function ga(i,e){var a;let t="";try{return t=await i.text(),JSON.parse(t)}catch(s){let r="";try{r=((a=i.headers)==null?void 0:a.get("content-type"))||""}catch{}const n=i.status||500,{message:c}=Nt(n,r,t.slice(0,200));throw m("Unparseable response body",{path:e,status:n,contentType:r,responseTextSnippet:t.slice(0,200),parseError:(s==null?void 0:s.message)||String(s)}),new E(c,n,s)}}const Ce=3e4,Le=12e4,Ae=new Map;function Ft(i){if(!i)return Ce;const e=Number(i);if(Number.isFinite(e)&&e>0)return Math.min(e*1e3,Le);const t=Date.parse(i);if(Number.isFinite(t)){const a=t-Date.now();if(a>0)return Math.min(a,Le)}return Ce}function Wt(i,e){Ae.set(i,Date.now()+e)}const Ge="AI_BUDGET_EXCEEDED";async function zt(i){var e;try{const t=JSON.parse(await((e=i.text)==null?void 0:e.call(i))||"{}");return(t==null?void 0:t.errorType)!==Ge?null:{message:String(t.message||"AI limit reached."),details:t.details??null}}catch{return null}}function Vt(i){const e=Ae.get(i);if(!e)return 0;const t=e-Date.now();return t<=0?(Ae.delete(i),0):t}async function Ht(i){const e=await ht.request({url:i.url,method:i.method,headers:i.headers,data:i.method==="GET"?void 0:i.body,connectTimeout:6e4,readTimeout:6e4}),t=Object.entries(e.headers||{}).reduce((r,[n,c])=>(Array.isArray(c)?r[n]=c.join(", "):c!=null&&(r[n]=String(c)),r),{}),a=typeof e.data=="string"?e.data:JSON.stringify(e.data??null),s=new Response(a,{status:e.status,headers:t});return s.sentBytes=i.sentBytes,s.receivedBytes=Lt(e.data??a),s}async function Pe(){try{const i=await qe();return i!=null&&i.deviceId?{tsdeviceid:i.deviceId,...i.deviceName?{tsdevicename:i.deviceName}:{},tsdevicetype:"computer"}:{}}catch{return{}}}const $=class ${constructor(e=He.instance){this.connService=e}static get instance(){return $._staticInstance||($._staticInstance=new $),$._staticInstance}async handleFatalAuthError(e,t={}){try{const a=(t==null?void 0:t.authOptional)===!0||me(e),s=(t==null?void 0:t.ignoreAuthError)===!0;if(a||s||(e||"").startsWith("/auth/")||!await this.connService.isActive())return;if(v.appType!=="webapp"){const n=await this.connService.getCurrentUser();if(ut(n)){m("[REQ] Auth failed for restricted user; preserving session to keep restrictions",e);return}}await this.connService.reset(),lt.emit("force-signout",{reason:"auth-token-invalid",status:401,path:e})}catch(a){m("[REQ] handleFatalAuthError failed",a)}}async remoteRequestRaw(e,t={},a={},s={}){var k,H,U;const r=(a==null?void 0:a.method)||"POST";function n(S,P){if(!P||P.length===0)return!0;const I=S||"",et=P.includes("library"),tt=P.includes("settings"),at=P.includes("desktop");return!!(et&&(I.startsWith("/library/")||I.startsWith("/collection/")||I.startsWith("/item/"))||tt&&(I.startsWith("/clientSettings/")||I.startsWith("/serverSettings/")||I.startsWith("/user/settings"))||at&&(I.startsWith("/nativeDesktop")||I.startsWith("/nativeClientCheck"))||P.includes("deviceProtection")&&I.startsWith("/companion/protection/"))}const c=await yt(),d=Date.now()/1e3,l=!(c!=null&&c.expiresAtSec)||c.expiresAtSec>d,u=n(e,(c==null?void 0:c.scopes)||null);if(!((a==null?void 0:a.authOptional)===!0||me(e))&&!await this.connService.isActive())throw m("[REQ] Not authenticated, skipping request:",e),new E("Not Authenticated, not sending request",401,null,"AUTH");const p=await this.connService.getAuthInfo(),y=t&&typeof t=="object"&&!Array.isArray(t)?t:null;r==="POST"&&!!(c!=null&&c.tokenData)&&l&&u&&(a==null?void 0:a.disablePermissionOverrideToken)!==!0&&!!y&&!y.tempAuthToken&&(y.tempAuthToken=c.tokenData);const C=await we(),B=typeof(a==null?void 0:a.serverBaseURLOverride)=="string"?a.serverBaseURLOverride.replace(/\/+$/,""):"",w=B||C.apiURL;(e==="/auth/tokenLogin"||e==="/auth/providerLogin/verify"||e==="/auth/providerLogin/fail")&&m("[AUTH_CALLBACK][REMOTE_TARGET]",{path:e,requestBaseURL:w,usedOverride:!!B});const A=!!((k=p==null?void 0:p.tokenData)!=null&&k.token)&&((H=p==null?void 0:p.tokenData)==null?void 0:H.token)!="local_token";m("[REQ] Making Request (remote)",e,r,t,`AuthRequired=${A}`);const L={"Content-Type":"application/json",API_VERSION:v.apiVersion,tsclientid:await be(),tsapptype:v.appType,tsappid:v.appId,tsappversion:v.appVersion,tsclientversion:v.clientVersion,...await Pe()};A&&(L.authorization=`Bearer ${(U=p==null?void 0:p.tokenData)==null?void 0:U.token}`);const{headers:_,__skipTraceCapture:M=!1,...z}=s||{},N=_?{...L,..._}:L,F=r=="POST"?JSON.stringify(t):void 0,V=F?re(F):0,ce=performance.now(),ee=`${w}${e}`,W=_t(w,B)?await Ht({url:ee,method:r,headers:N,body:t,sentBytes:V}):Ot()?await Bt({path:e,method:r,headers:N,bodyOutput:F,sentBytes:V}):await Kt(ee,{method:r,mode:"cors",cache:"no-cache",credentials:"include",headers:N,redirect:"follow",referrerPolicy:"no-referrer",body:F,timeout:6e4,...z}),j=W;if(j.sentBytes=V,j.receivedBytes=Pt(W),!M){const S=performance.now()-ce;ke(e,t,S,{success:W.ok,status:W.status},{sentBytes:V,receivedBytes:j.receivedBytes})}return W}
1async remoteAPIRequest(e,t={},a={},s={}){const r=Vt(e);if(r>0)throw m(`[REQ] Skipping ${e}; rate-limit cooldown for another ${Math.round(r/1e3)}s`),new E("Too many requests, please try again later.",429,{retryAfterMs:r},"RATE_LIMIT");await J.init();const n=J.isEnabled(),c=n?J.startTrace("remoteAPIRequest",{path:e},{privacy:"safe"}):"",d=n?J.startSpan(c,e,{path:e},{privacy:"safe"}):"",l=performance.now();let u,h={};try{u=await this.remoteRequestRaw(e,t,a,{...s,__skipTraceCapture:!0}).then(async y=>{var g,C,B;if(h=xt(y),y.status==401)return m("401 data",e,y.body),await this.handleFatalAuthError(e,a),{success:!1,message:"Unauthenticated",errorType:"AUTH",status:y.status};if(y.status==403)return m("403 data",e,y.body),{success:!1,message:"Access Denied",errorType:"AUTH",status:y.status};if(y.status==429){const w=await zt(y);if(w)return{success:!1,message:w.message,errorType:Ge,status:y.status,details:w.details};const A=Ft((C=(g=y.headers)==null?void 0:g.get)==null?void 0:C.call(g,"retry-after"));return Wt(e,A),console.warn(`[REQ] Rate limited (429) on ${e}; backing off ${Math.round(A/1e3)}s`),{success:!1,message:"Too many requests, please try again later.",errorType:"RATE_LIMIT",status:y.status,details:{retryAfterMs:A},retryAfterMs:A}}try{const w=await y.text();if(h.receivedBytes=w?re(w):h.receivedBytes??0,!w)return{};try{return JSON.parse(w)}catch(A){let L="";try{L=((B=y.headers)==null?void 0:B.get("content-type"))||""}catch{}const _=w.slice(0,200),M=y.status||500,z=M===502||M===503||M===504||M>=500,N=L.toLowerCase().includes("text/html")||_.trim().startsWith("<");return{success:!1,message:z||N?"Uh oh â the server is unavailable right now. ð¡ Try again in a moment.":"Uh oh â I couldn't read the server response. ð¡ Please try again.",errorType:z?"CONNECTION_FAILED":"MALFORMED",details:{path:e,contentType:L,status:M,responseTextSnippet:_,parseError:(A==null?void 0:A.message)||String(A)},status:M}}}catch(w){const A=y.status||500;return{success:!1,message:"Uh oh â I couldn't read the server response. ð¡ Please try again.",errorType:"MALFORMED",details:{path:e,status:A,parseError:(w==null?void 0:w.message)||String(w)},status:A}}}).catch(y=>{if(m("Response status",y.status),y instanceof E)return y.status===401&&m("Auth required for",e),{success:!1,message:y.message,errorType:y.errorType||"AUTH",details:y.details,status:y.status};if(y instanceof TypeError&&y.message.includes("Failed to fetch")){const g=`Failed to connect to server. <a target="blank" href='https://kindredly.ai/status'>Click here</a> to check Kindredly.ai's system status.`;return console.error(g,e,y),{success:!1,message:g,errorType:"CONNECTION_FAILED",details:{e:y},status:500}}else{if(y instanceof SyntaxError&&y.message.includes("Unexpected token < in JSON"))return{success:!1,message:"API response error for "+e};if(y instanceof DOMException&&y.name==="AbortError")return{success:!1,message:"Server timeout, please try again later",errorType:"TIMEOUT",details:{e:y},status:500};if(y.message.includes("The user aborted a request"))return{success:!1,message:"Server timeout, please try again later",errorType:"TIMEOUT",details:{e:y},status:500};if(console.error("Unknown error:",e,y),y!=null&&y.message&&y.message.includes("NetworkError")){const g=`Failed to connect to server. <a target="blank" href='https://thetaset.com/status'>Click here</a> to check ThetaSet's system status.`;return console.error(g,y),{success:!1,message:g,errorType:"CONNECTION_FAILED",details:{e:y},status:500}}return{success:!1,message:y.message,errorType:"UNKNOWN",details:{e:y},status:500}}})}finally{const y=performance.now()-l;if(n){const g=!!(u!=null&&u.success);J.endSpan(c,d,{latencyMs:Math.round(y),ok:g,status:u==null?void 0:u.status,errorType:u==null?void 0:u.errorType},g?"ok":"error"),await J.finishTrace(c,{latencyMs:Math.round(y),ok:g,status:u==null?void 0:u.status,errorType:u==null?void 0:u.errorType},g?"ok":"error")}}if((u==null?void 0:u.errorType)==="CONNECTION_FAILED"&&!s.__afterRediscovery&&await Tt().catch(()=>!1))return m("[REQ] server address changed; retrying once",e),this.remoteAPIRequest(e,t,a,{...s,__afterRediscovery:!0});const p=performance.now()-l;if(ke(e,t,p,u,h),pt(e,u),mt){let y=JSON.stringify(u),g=JSON.parse(y);m(`[REQ] Request result (Remote) ${p} ms `,e,g,t)}else m(`[REQ] Request result (Remote) ${p} ms `,e,t);if(u.success)return u.results;throw u.errorType!=="AUTH"?(console.error("ERROR:",e,u.message),console.error(u)):m("Auth error:",e,u.message),new E(u.message,u.status,u.details,u.errorType)}
1async remoteStreamRequest(e,t={},a={},s={}){var z,N,F,V,ce,ee,W,j;if(!((s==null?void 0:s.authOptional)===!0||me(e))&&!await this.connService.isActive())throw m("Not authenticated, skipping stream request:",e),new E("Not Authenticated, not sending request",401,null,"AUTH");const n=await this.connService.getAuthInfo(),c=await we(),d=!!((z=n==null?void 0:n.tokenData)!=null&&z.token)&&((N=n==null?void 0:n.tokenData)==null?void 0:N.token)!="local_token",l={"Content-Type":"application/json",API_VERSION:v.apiVersion,tsclientid:await be(),tsapptype:v.appType,tsappid:v.appId,tsappversion:v.appVersion,tsclientversion:v.clientVersion,...await Pe()};d&&(l.authorization=`Bearer ${(F=n==null?void 0:n.tokenData)==null?void 0:F.token}`),m("Making Stream Request (remote)",e,t);const u=new AbortController;let h=setTimeout(()=>u.abort(),3e4);const p=()=>{h!==null&&(clearTimeout(h),h=null)},y=s.signal,g=()=>(y==null?void 0:y.aborted)===!0;if(y){if(y.aborted)throw p(),new E("Stream request cancelled",499,null,"STREAM_CANCELLED");y.addEventListener("abort",()=>u.abort(),{once:!0})}let C;try{C=await fetch(`${c.apiURL}${e}`,{method:"POST",mode:"cors",cache:"no-cache",credentials:"include",headers:l,body:JSON.stringify(t),signal:u.signal})}catch(k){throw p(),(k==null?void 0:k.name)==="AbortError"?g()?new E("Stream request cancelled",499,null,"STREAM_CANCELLED"):new E("Stream request timed out",504,null,"STREAM_ERROR"):k}if(!C.ok){p();let k=`Stream request failed: ${C.status}`,H="STREAM_ERROR",U=null;try{const S=await C.json();S!=null&&S.message&&(k=String(S.message)),S!=null&&S.errorType&&(H=String(S.errorType)),S!=null&&S.details&&(U=S.details)}catch{}throw new E(k,C.status,U,H)}if(!C.body)throw p(),new E("No response body for stream",500,null,"STREAM_ERROR");const B=C.body.getReader(),w=new TextDecoder;let A="",L=null,_="",M="";try{for(;;){const{done:k,value:H}=await B.read();if(p(),k)break;const U=w.decode(H,{stream:!0});A+=U;const S=A.split(` 2`);A=S.pop()||"";for(const P of S)if(P.startsWith("event: "))_=P.slice(7).trim();else if(P.startsWith("data: "))M=P.slice(6);else if(P===""&&_&&M){try{const I=JSON.parse(M);switch(_){case"start":(V=a.onStart)==null||V.call(a,I);break;case"chunk":(ce=a.onChunk)==null||ce.call(a,I);break;case"tool_call":(ee=a.onToolCall)==null||ee.call(a,I);break;case"complete":L=I,(W=a.onComplete)==null||W.call(a,I);break;case"error":throw(j=a.onError)==null||j.call(a,I),new E(I.message,500,null,"STREAM_ERROR");case"done":break}}catch(I){if(I instanceof E)throw I;console.warn("Failed to parse SSE data:",M,I)}_="",M=""}}}catch(k){throw(k==null?void 0:k.name)==="AbortError"&&g()?new E("Stream request cancelled",499,null,"STREAM_CANCELLED"):k}finally{p(),B.releaseLock()}if(g()&&!L)throw new E("Stream request cancelled",499,null,"STREAM_CANCELLED");if(!L)throw new E("Stream ended without complete event",500,null,"STREAM_ERROR");return L}};f($,"_staticInstance");let xe=$;function Ia(){return typeof chrome<"u"&&chrome.runtime&&chrome.runtime.id||typeof browser<"u"&&browser.runtime&&browser.runtime.id}function ne(){return typeof window<"u"?window:typeof self<"u"?self:globalThis}function wa(i,e){return ne().setInterval(i,e)}function ba(i){ne().clearInterval(i)}function $e(i,e){return ne().setTimeout(i,e)}function Aa(i){const e=ne();return"addEventListener"in e?(e.addEventListener("online",i),()=>e.removeEventListener("online",i)):(console.warn("Online events not supported in this context"),()=>{})}function Sa(i){const e=ne();return"addEventListener"in e?(e.addEventListener("offline",i),()=>e.removeEventListener("offline",i)):(console.warn("Offline events not supported in this context"),()=>{})}function va(){return typeof navigator<"u"&&"onLine"in navigator?navigator.onLine:!0}const Se=60*60*1e3,R=24*Se,x={enabled:!0,cadenceMs:R,startupDelayMs:45*1e3,batchSize:500,pipelineRetentionMs:3*R,embeddingsRetentionMs:3*R,activityEmbeddingsRetentionMs:30*R,itemEmbeddingsRetentionMs:30*R,metaLookupRetentionMs:14*R,emailCacheRetentionMs:30*R,finishedJobsRetentionMs:7*R},b={minCadenceMs:6*Se,maxCadenceMs:7*R,minStartupDelayMs:5*1e3,maxStartupDelayMs:5*60*1e3,minBatchSize:50,maxBatchSize:2e3,minRetentionMs:Se,maxPipelineRetentionMs:3*R,maxEmbeddingsRetentionMs:30*R,maxActivityEmbeddingsRetentionMs:90*R,maxItemEmbeddingsRetentionMs:90*R,maxMetaLookupRetentionMs:90*R,maxEmailCacheRetentionMs:90*R,maxFinishedJobsRetentionMs:30*R};function O(i,e,t,a){return typeof i!="number"||!Number.isFinite(i)?a:i<e?e:i>t?t:Math.round(i)}function Ut(i){return{enabled:(i==null?void 0:i.enabled)??x.enabled,cadenceMs:O(i==null?void 0:i.cadenceMs,b.minCadenceMs,b.maxCadenceMs,x.ca
2denceMs),startupDelayMs:O(i==null?void 0:i.startupDelayMs,b.minStartupDelayMs,b.maxStartupDelayMs,x.startupDelayMs),batchSize:O(i==null?void 0:i.batchSize,b.minBatchSize,b.maxBatchSize,x.batchSize),pipelineRetentionMs:O(i==null?void 0:i.pipelineRetentionMs,b.minRetentionMs,b.maxPipelineRetentionMs,x.pipelineRetentionMs),embeddingsRetentionMs:O(i==null?void 0:i.embeddingsRetentionMs,b.minRetentionMs,b.maxEmbeddingsRetentionMs,x.embeddingsRetentionMs),activityEmbeddingsRetentionMs:O(i==null?void 0:i.activityEmbeddingsRetentionMs,b.minRetentionMs,b.maxActivityEmbeddingsRetentionMs,x.activityEmbeddingsRetentionMs),itemEmbeddingsRetentionMs:O(i==null?void 0:i.itemEmbeddingsRetentionMs,b.minRetentionMs,b.maxItemEmbeddingsRetentionMs,x.itemEmbeddingsRetentionMs),metaLookupRetentionMs:O(i==null?void 0:i.metaLookupRetentionMs,b.minRetentionMs,b.maxMetaLookupRetentionMs,x.metaLookupRetentionMs),emailCacheRetentionMs:O(i==null?void 0:i.emailCacheRetentionMs,b.minRetentionMs,b.maxEmailCacheRetentionMs,x.emailCacheRetentionMs),finishedJobsRetentionMs:O(i==null?void 0:i.finishedJobsRetentionMs,b.minRetentionMs,b.maxFinishedJobsRetentionMs,x.finishedJobsRetentionMs)}}function qt(i){return Ut(i==null?void 0:i.storageCleanup)}const Gt="clientStorageCleanup:lastRun:",fe=new Map,oe=new Map;function je(i){return`${Gt}${i}`}async function Je(){const i=await gt();return qt(i)}async function Ye(i){const e=await T.kvGet(je(i));return typeof e=="number"&&Number.isFinite(e)?e:null}async function $t(i,e){await T.kvSet(je(i),e)}async function jt(i){const{accountDbKey:e,db:t}=i,a=oe.get(e);if(a)return await a;const s=(async()=>{const r=await Je();if(!r.enabled)return{skippedReason:"disabled",deletedPipelineData:0,deletedEmbeddings:0,deletedActivityEmbeddings:0,deletedItemEmbeddings:0,deletedMetaLookup:0,deletedEmailCache:0,deletedFinishedJobs:0};const n=typeof i.now=="number"?i.now:Date.now(),c=await Ye(e);if(typeof c=="number"&&n-c<r.cadenceMs)return{skippedReason:"throttled",deletedPipelineData:0,deletedEmbeddings:0,deletedActivityEmbeddings:0,deletedItemEmbeddings:0,deletedMetaLookup:0,deletedEmailCache:0,deletedFinishedJobs:0};const d={deletedPipelineData:0,deletedEmbeddings:0,deletedActivityEmbeddings:0,deletedItemEmbeddings:0,deletedMetaLookup:0,deletedEmailCache:0,deletedFinishedJobs:0};try{return d.deletedPipelineData=await t.purgePipelineDataOlderThan(n-r.pipelineRetentionMs,r.batchSize),d.deletedEmbeddings=await t.purgeEmbeddingsOlderThan(n-r.embeddingsRetentionMs,r.batchSize),d.deletedActivityEmbeddings=await t.purgeActivityEmbeddingsOlderThan(n-r.activityEmbeddingsRetentionMs,r.batchSize),d.deletedItemEmbeddings=await t.purgeItemEmbeddingsOlderThan(n-r.itemEmbeddingsRetentionMs,r.batchSize),d.deletedMetaLookup=await t.purgeMetaLookupOlderThan(n-r.metaLookupRetentionMs,r.batchSize),d.deletedEmailCache=await t.purgeEmailCacheOlderThanAnyUser(n-r.emailCacheRetentionMs,r.batchSize),d.deletedFinishedJobs=await t.purgeFinishedJobsOlderThan(n-r.finishedJobsRetentionMs,r.batchSize),m("[STORAGE_CLEANUP] completed",{accountDbKey:e,summary:d}),d}catch(l){return console.warn("[STORAGE_CLEANUP] failed",{accountDbKey:e,error:l}),d}finally{await $t(e,n)}})();oe.set(e,s);try{return await s}finally{oe.delete(e)}}async function Jt(i){const{accountDbKey:e,db:t}=i;if(!e||!t||fe.has(e)||oe.has(e))return;const a=await Je();if(!a.enabled)return;const s=await Ye(e),r=Date.now();if(typeof s=="number"&&r-s<a.cadenceMs)return;const n=$e(()=>{fe.delete(e),jt({accountDbKey:e,db:t}).catch(c=>{console.warn("[STORAGE_CLEANUP] scheduled run failed",{accountDbKey:e,error:c})})},a.startupDelayMs);fe.set(e,n)}const _e="legacy_search_index_removed_v1",Yt=["idx_v1_itemSearch","itemSearch_"];async function Qt(){try{if(await T.kvGet(_e))return 0;let i=0;for(const e of Yt)i+=await T.kvDeleteWithPrefix(e);return await T.kvSet(_e,{at:new Date().toISOString(),deleted:i}),i>0&&m("[STORAGE] removed legacy FlexSearch index blobs",{deleted:i}),i}catch(i){return console.error("removeLegacySearchIndex failed",i),0}}const Xt=5e3;let Oe=null,K=le();function le(){return{exactById:new Map,bySessionId:new Map,byLegacyKey:new Map}}function Zt(){return K.exactById.size+K.bySessionId.size+K.byLegacyKey.size}function ve(){Zt()>Xt&&(K=le())}function ka(i){const e=typeof i=="string"&&i?i:null;e!==Oe&&(Oe=e,K=le())}function Ta(i){const e={},t=[];for(const a of i)if(K.exactById.has(a)){const s=K.exactById.get(a);s&&(e[a]=s)}else t.push(a);return{cached:e,missing:t}}function Ka(i){return Qe(K.bySessionId,i)}function Ea(i){return Qe(K.byLegacyKey,i)}function Qe(i,e){const t={},a=[];for(const s of e)i.has(s)?t[s]=i.get(s):a.push(s);return{cached:t,missing:a}}function Ra(i,e){for(const t of i)K.exactById.set(t,e[t]??null);ve()}function Ma(i,e){for(const t of i)K.bySessionId.set(t,e[t]??[]);ve()}function Da(i,e){for(const t of i)K.byLegacyKey.set(t,e[t]??[]);ve()}function ea(i){if(!i)return;const e=typeof i.id=="string"?i.id.trim():"";if(e){const t=K.exactById.get(e);t&&Be(t),K.exactById.delete(e)}Be(i)}function Be(i){const e=typeof i.activitySessionId=="string"?i.activitySessionId.trim():"";e&&K.bySessionId.delete(e);const t=typeof i.key=="string"?i.key.trim():"";t&&K.byLegacyKey.delete(t)}function Ne(){K=le()}function ta(i,e){if(i.length===0)return 0;const t=[...i].sort((s,r)=>s-r),a=Math.min(t.length-1,Math.max(0,Math.ceil(e/100*t.length)-1));return t[a]}const aa=6e4,Fe=new Set,he=new Set;class ia extends Ie{constructor(t){super(`kindredly_account_${t}`);f(this,"items");f(this,"itemRelations");f(this,"tagIndex");f(this,"userFiles");f(this,"visitHistory");f(this,"users");f(this,"prefs");f(this,"familyPolicyRules");f(this,"metaLookup");f(this,"pipelineData");f(this,"imageClassificationSamples");f(this,"embeddings");f(this,"itemEmbeddings");f(this,"activityEmbeddings");f(this,"refState");f(this,"binaryCache");f(this,"emailCache");f(this,"audioCache");f(this,"audioCacheBlobs");f(this,"jobs");this.on("blocked",a=>{console.warn("AccountDatabase BLOCKED - another tab may be upgrading",{accountId:t}),this.close()}),this.on("versionchange",a=>{console.warn("AccountDatabase versionchange detected - closing connection",{accountId:t}),this.close(),typeof window<"u"&&!window._dbVersionChangeNotified&&(window._dbVersionChangeNotified=!0)}),this.version(1).stores({items:"_id, details.type, details.createdAt, *details.tags, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType",pipelineData:"id, key, timestamp",embeddings:"textHash, timestamp"}),this.version(2).stores({items:"_id, details.type, details.createdAt, *details.tags, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType",pipelineData:"id, key, timestamp",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt"}),this.version(3).stores({items:"_id, details.type, details.createdAt, *details.tags, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType",pipelineData:"id, key, timestamp",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt"}).upgrade(async a=>{await a.table("refState").toCollection().modify(r=>{typeof r.dirty=="boolean"?r.dirty=r.dirty?1:0:r.dirty==null&&(r.dirty=0)})}),this.version(4).stores({items:"_id, details.type, details.createdAt, *details.tags, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType",pipelineData:"id, key, timestamp",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt",emailCache:"_id, provider, userId, accountId, fromEmail, internalDateMs, threadId, updatedAt"}),this.version(5).stores({items:"_id, details.type, details.createdAt, *details.tags, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType",pipelineData:"id, key, timestamp",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt",emailCache:"_id, provider, userId, accountId, fromEmail, internalDateMs, threadId, updatedAt"}),this.version(6).stores({items:"_id, details.type, details.createdAt, *details.tags, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType",pipelineData:"id, key, timestamp, activitySessionId",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt",emailCache:"_id, provider, userId, accountId, fromEmail, internalDateMs, threadId, updatedAt"}),this.version(7).stores({items:"_id, details.type, details.createdAt, *details.tags, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType, timestamp",pipelineData:"id, key, timestamp, activitySessionId",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt",emailCache:"_id, provider, userId, accountId, fromEmail, internalDateMs, threadId, updatedAt"}),this.version(8).stores({items:"_id, details.type, details.createdAt, *details.tags, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType, timestamp",pipelineData:"id, key, timestamp, activitySessionId",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt",emailCache:"_id, provider, userId, accountId, fromEmail, internalDateMs, threadId, updatedAt",itemEmbeddings:"itemId, modelId, updatedAt"}),this.version(9).stores({items:"_id, details.type, details.createdAt, *details.tags, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType, timestamp",pipelineData:"id, key, timestamp, activitySessionId",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt",emailCache:"_id, provider, userId, accountId, fromEmail, internalDateMs, threadId, updatedAt",itemEmbeddings:"itemId, modelId, updatedAt",activityEmbeddings:"key, url, activitySessionId, modelId, updatedAt"}),this.version(10).stores({items:"_id, details.type, details.createdAt, *details.tags, *details.kinds, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType, timestamp",pipelineData:"id, key, timestamp, activitySessionId",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt",emailCache:"_id, provider, userId, accountId, fromEmail, internalDateMs, threadId, updatedAt",itemEmbeddings:"itemId, modelId, updatedAt",activityEmbeddings:"key, url, activitySessionId, modelId, updatedAt"}),this.version(11).stores({items:"_id, details.type, details.createdAt, *details.tags, *details.kinds, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType, timestamp",pipelineData:"id, key, timestamp, activitySessionId",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt",emailCache:"_id, provider, userId, accountId, fromEmail, internalDateMs, threadId, updatedAt",itemEmbeddings:"itemId, modelId, updatedAt",activityEmbeddings:"key, url, activitySessionId, modelId, updatedAt",audioCache:"trackId, downloadedAtMs",audioCacheBlobs:"trackId"}),this.version(12).stores({items:"_id, details.type, details.createdAt, *details.tags, *details.kinds, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType, timestamp",pipelineData:"id, key, timestamp, activitySessionId",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt",emailCache:"_id, provider, userId, accountId, fromEmail, internalDateMs, threadId, updatedAt",itemEmbeddings:"itemId, modelId, updatedAt",activityEmbeddings:"key, url, activitySessionId, modelId, updatedAt",audioCache:"
2trackId, downloadedAtMs",audioCacheBlobs:"trackId",imageClassificationSamples:"id, timestamp, band, imageKey, uploadState"}),this.version(13).stores({items:"_id, details.type, details.createdAt, *details.tags, *details.kinds, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType, timestamp",pipelineData:"id, key, timestamp, activitySessionId",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt",emailCache:"_id, provider, userId, accountId, fromEmail, internalDateMs, threadId, updatedAt",itemEmbeddings:"itemId, modelId, updatedAt",activityEmbeddings:"key, url, activitySessionId, modelId, updatedAt",audioCache:"trackId, downloadedAtMs",audioCacheBlobs:"trackId",imageClassificationSamples:"id, timestamp, band, imageKey, uploadState",jobs:"id, status, kind, createdAtMs, ownerUserId, [status+createdAtMs]"}),this.version(14).stores({items:"_id, details.type, details.createdAt, lastUsedMs, *details.tags, *details.kinds, accountId",itemRelations:"_id, collectionId, itemId, userId, accountId",tagIndex:"_id, tag, itemId",userFiles:"_id, userId, filename, createdAt",visitHistory:"url, lastVisit",users:"_id, accountId, username, type",prefs:"_id, userId, key",familyPolicyRules:"_id, targetKind, targetValue, [targetKind+targetValue], decisionKind, enabled, updatedAt, dirty, source",metaLookup:"id, metaType, timestamp",pipelineData:"id, key, timestamp, activitySessionId",embeddings:"textHash, timestamp",refState:"_id, [refType+refId], refType, refId, ownerType, ownerId, stateKey, stateSubKey, updatedAt, dirty",binaryCache:"_id, refType, refId, cacheKey, updatedAt",emailCache:"_id, provider, userId, accountId, fromEmail, internalDateMs, threadId, updatedAt",itemEmbeddings:"itemId, modelId, updatedAt",activityEmbeddings:"key, url, activitySessionId, modelId, updatedAt",audioCache:"trackId, downloadedAtMs",audioCacheBlobs:"trackId",imageClassificationSamples:"id, timestamp, band, imageKey, uploadState",jobs:"id, status, kind, createdAtMs, ownerUserId, [status+createdAtMs]"})}async backfillLastUsedMs(t=500,a=5e3){if(he.has(this.name))return{stamped:0,done:!1};he.add(this.name);try{const s=`lastUsedBackfill:${this.name}`,r=await T.kvGet(s);let n=typeof r=="string"?r:"",c=0,d=0;for(;d<a;){const l=await this.items.where("_id").above(n).limit(Math.min(t,a-d)).toArray();if(l.length===0)return await T.kvSet(s,n),{stamped:c,done:!0};const u=Date.now(),h=l.filter(p=>typeof p.lastUsedMs!="number");h.length&&await this.items.bulkPut(h.map(p=>({...p,lastUsedMs:wt(p,u)}))),c+=h.length,d+=l.length,n=l[l.length-1]._id,await T.kvSet(s,n)}return{stamped:c,done:!1}}finally{he.delete(this.name)}}async purgeByIndexedCutoff(t,a,s,r=500){const n=Math.max(1,Math.round(r||500));let c=0;for(;;){const d=await t.where(a).below(s).limit(n).primaryKeys();if(!d.length||(await t.bulkDelete(d),c+=d.length,d.length<n))break}return c}async getItemById(t){return this.items.get(t)}async getItemsByIds(t){return(await this.items.bulkGet(t)).filter(s=>s!==void 0)}async getItemsByType(t){return this.items.where("details.type").equals(t).toArray()}async getItemsByTag(t){return this.items.where("details.tags").equals(t).toArray()}async upsertItems(t){await this.items.bulkPut(t)}async deleteItems(t){await this.items.bulkDelete(t)}async getLibraryStats(t=100){var l;const a=await this.items.count();if(a===0||t<=0)return{itemCount:a,sampledRows:0,meanRowBytes:0,p95RowBytes:0,approxTotalBytes:0};const s=await this.items.limit(t).toArray(),r=[];for(const u of s)try{r.push(((l=JSON.stringify(u))==null?void 0:l.length)??0)}catch{}if(r.length===0)return{itemCount:a,sampledRows:0,meanRowBytes:0,p95RowBytes:0,approxTotalBytes:0};const n=r.reduce((u,h)=>u+h,0),c=Math.round(n/r.length),d=ta(r,95);return{itemCount:a,sampledRows:r.length,meanRowBytes:c,p95RowBytes:d,approxTotalBytes:c*a}}async getRelationsByCollection(t){return this.itemRelations.where("collectionId").equals(t).toArray()}async getRelationsByItem(t){return this.itemRelations.where("itemId").equals(t).toArray()}async upsertRelations(t){await this.itemRelations.bulkPut(t)}async deleteRelation(t,a){const s=`${t}_${a}`;await this.itemRelations.delete(s)}async getItemIdsByTag(t){return(await this.tagIndex.where("tag").equals(t).toArray()).map(s=>s.itemId)}async getTagsByItemId(t){return(await this.tagIndex.where("itemId").equals(t).toArray()).map(s=>s.tag)}async updateTagIndex(t,a){await this.tagIndex.where("itemId").equals(t).delete();const s=a.map(r=>({_id:`${r}_${t}`,tag:r,itemId:t}));await this.tagIndex.bulkPut(s)}async getFileById(t){return this.userFiles.get(t)}async getFilesByUser(t){return this.userFiles.where("userId").equals(t).toArray()}async getFilesByRef(t,a){return this.userFiles.filter(s=>s.refType===t&&s.refId===a).toArray()}async saveFile(t){await this.userFiles.put(t)}async deleteFile(t){await this.userFiles.delete(t)}async getVisitHistory(t){return this.visitHistory.get(t)}async recordVisit(t,a){const s=await this.visitHistory.get(t),r=Date.now();s?await this.visitHistory.put({url:t,lastVisit:r,visitCount:s.visitCount+1,timespent:a??s.timespent}):await this.visitHistory.put({url:t,lastVisit:r,visitCount:1,timespent:a})}async upsertEmailCache(t){!t||t.length===0||await this.emailCache.bulkPut(t)}async listEmailCache(t){const{userId:a,minInternalDateMs:s,maxItems:r,from
2EmailAllowlist:n,toEmailAllowlist:c}=t;let d;try{d=await this.emailCache.where("userId").equals(a).filter(u=>(u.internalDateMs||0)>=s).toArray()}catch{d=await this.emailCache.filter(u=>u.userId===a&&(u.internalDateMs||0)>=s).toArray()}n&&(d=d.filter(u=>n.has(String(u.fromEmail||"").toLowerCase()))),c&&(d=d.filter(u=>(Array.isArray(u.toEmails)?u.toEmails:[]).some(p=>c.has(String(p||"").toLowerCase())))),d.sort((u,h)=>(h.internalDateMs||0)-(u.internalDateMs||0));const l=Math.max(0,Math.round(r||0));return l>0?d.slice(0,l):d}async purgeEmailCacheOlderThan(t){const{userId:a,cutoffInternalDateMs:s}=t,r=await this.emailCache.where("userId").equals(a).filter(n=>(n.internalDateMs||0)<s).primaryKeys();return!r||r.length===0?0:(await this.emailCache.bulkDelete(r),r.length)}async markEmailThreadRead(t){const a=String((t==null?void 0:t.userId)||"").trim(),s=String((t==null?void 0:t.threadId)||"").trim();if(!a||!s)return 0;const r=s;let n;try{n=await this.emailCache.where("userId").equals(a).filter(l=>String(l.threadId||"")===r||String(l._id||"")===r).toArray()}catch{n=await this.emailCache.filter(l=>l.userId===a&&(String(l.threadId||"")===r||String(l._id||"")===r)).toArray()}if(!n.length)return 0;const c=new Date().toISOString(),d=[];for(const l of n){const u=Array.isArray(l.labelIds)?l.labelIds:[];u.some(p=>String(p||"").toUpperCase()==="UNREAD")&&d.push({...l,labelIds:u.filter(p=>String(p||"").toUpperCase()!=="UNREAD"),updatedAt:c})}return d.length?(await this.emailCache.bulkPut(d),d.length):0}async markEmailThreadUnread(t){const a=String((t==null?void 0:t.userId)||"").trim(),s=String((t==null?void 0:t.threadId)||"").trim();if(!a||!s)return 0;const r=s;let n;try{n=await this.emailCache.where("userId").equals(a).filter(l=>String(l.threadId||"")===r||String(l._id||"")===r).toArray()}catch{n=await this.emailCache.filter(l=>l.userId===a&&(String(l.threadId||"")===r||String(l._id||"")===r)).toArray()}if(!n.length)return 0;const c=new Date().toISOString(),d=[];for(const l of n){const u=Array.isArray(l.labelIds)?l.labelIds:[];u.some(p=>String(p||"").toUpperCase()==="UNREAD")||d.push({...l,labelIds:["UNREAD",...u],updatedAt:c})}return d.length?(await this.emailCache.bulkPut(d),d.length):0}async getRecentVisits(t=100){return this.visitHistory.orderBy("lastVisit").reverse().limit(t).toArray()}async getUserById(t){return this.users.get(t)}async getAllUsers(){return this.users.toArray()}async upsertUser(t){await this.users.put(t)}async upsertUsers(t){await this.users.bulkPut(t)}async deleteUser(t){await this.users.delete(t)}async clearUsers(){await this.users.clear()}async getPrefs(t,a){const s=`${t}_${a}`,r=await this.prefs.get(s);return r==null?void 0:r.value}async setPrefs(t,a,s){const r=`${t}_${a}`;await this.prefs.put({_id:r,userId:t,key:a,value:s})}async getUserPrefs(t){return this.prefs.where("userId").equals(t).toArray()}async clearUserPrefs(t){await this.prefs.where("userId").equals(t).delete()}async getFamilyPolicyRule(t){return this.familyPolicyRules.get(t)}async getFamilyPolicyRules(){return this.familyPolicyRules.toArray()}async getDirtyFamilyPolicyRules(t){return this.familyPolicyRules.where("dirty").equals(1).limit(t).toArray()}async countDirtyFamilyPolicyRules(){return this.familyPolicyRules.where("dirty").equals(1).count()}async getFamilyPolicyRulesByTarget(t,a){return this.familyPolicyRules.where("[targetKind+targetValue]").equals([t,a]).toArray()}async upsertFamilyPolicyRule(t){await this.familyPolicyRules.put(t)}async upsertFamilyPolicyRules(t){await this.familyPolicyRules.bulkPut(t)}async replaceFamilyPolicyRules(t){await this.transaction("rw",this.familyPolicyRules,async()=>{await this.familyPolicyRules.clear(),t.length&&await this.familyPolicyRules.bulkPut(t)})}async deleteFamilyPolicyRule(t){await this.familyPolicyRules.delete(t)}async clearFamilyPolicyRules(){await this.familyPolicyRules.clear()}async getMetaLookup(t){return this.metaLookup.get(t)}async getMetaByType(t){return this.metaLookup.where("metaType").equals(t).toArray()}async upsertMetaLookup(t){await this.metaLookup.put(t)}async deleteMetaLookup(t){await this.metaLookup.delete(t)}async purgeMetaLookupOlderThan(t,a=500){return await this.purgeByIndexedCutoff(this.metaLookup,"timestamp",t,a)}async getPipelineData(t){return this.pipelineData.get(t)}async getPipelineDataByKey(t){return this.pipelineData.where("key").equals(t).toArray()}async upsertPipelineData(t){await this.pipelineData.put(t),ea(t)}async deletePipelineData(t){await this.pipelineData.delete(t),Ne()}async clearPipelineData(){await this.pipelineData.clear(),Ne()}async purgePipelineDataOlderThan(t,a=500){return await this.purgeByIndexedCutoff(this.pipelineData,"timestamp",t,a)}async addImageClassificationSample(t){await this.imageClassificationSamples.put(t)}async getImageClassificationSample(t){return this.imageClassificationSamples.get(t)}async listImageClassificationSamples(t=200){return this.imageClassificationSamples.orderBy("timestamp").reverse().limit(Math.max(1,t)).toArray()}async hasImageClassificationSampleForKey(t){return!!await this.imageClassificationSamples.where("imageKey").equals(t).first()}async countImageClassificationSamples(){return this.imageClassificationSamples.count()}async clearImageClassificationSamples(){await this.imageClassificationSamples.clear()}async purgeFinishedJobsOlderThan(t,a=500){const s=Math.max(1,Math.round(a||500));let r=0;for(const n of["completed","failed","cancelled"])for(;;){const c=await this.jobs.where("[status+createdAtMs]").between([n,Ie.minKey],[n,t],!0,!1).limit(s).primaryKeys();if(!c.length||(await this.jobs.bulkDelete(c),r+=c.length,c.length<s))break}return r}async purgeImageClassificationSamplesOlderThan(t,a=500){return await this.purgeByIndexedCutoff(this.imageClassificationSamples,"timestamp",t,a)}async trimImageClassificationSamples(t){const s=await this.imageClassificationSamples.count()-Math.max(1,t);if(s<=0)return 0;const n=(await this.imageClassificationSamples.orderBy("timestamp").limit(s+200).toArray()).filter(c=>c.trigger!=="reported").slice(0,s);return n.length?(await this.imageClassificationSamples.bulkDelete(n.map(c=>c.id)),n.length):0}async getEmbedding(t){return this.embeddings.get(t)}async upsertEmbedding(t){await this.embeddings.put(t)}async clearOldEmbeddings(t){await this.embeddings.where("timestamp").below(t).delete()}async purgeEmbeddingsOlderThan(t,a=500){return await this.purgeByIndexedCutoff(this.embeddings,"timestamp",t,a)}async purgeEmailCacheOlderThanAnyUser(t,a=500){return await this.purgeByIndexedCutoff(this.emailCache,"internalDateMs",t,a)}async clearEmbeddings(){await this.embeddings.clear()}async getItemEmbedding(t){return this.itemEmbeddings.get(t)}async bulkGetItemEmbeddings(t){return this.itemEmbeddings.bulkGet(t)}async upsertItemEmbedding(t){await this.itemEmbeddings.put(t)}async upsertItemEmbeddings(t){t.length&&await this.itemEmbeddings.bulkPut(t)}async purgeItemEmbeddingsOrphans(t){const a=new Set(t),r=(await this.itemEmbeddings.toCollection().primaryKeys()).filter(n=>!a.has(n));return r.length&&await this.itemEmbeddings.bulkDelete(r),r.length}async purgeItemEmbeddingsOlderThan(t,a=500){return await this.purgeByIndexedCutoff(this.itemEmbeddings,"updatedAt",t,a)}async clearItemEmbeddings(){await this.itemEmbeddings.clear()}async getItemEmbeddingStats(){const t={};let a=0,s=0;return await this.itemEmbeddings.each(r=>{var n;a++,t[r.modelId]=(t[r.modelId]??0)+1,s+=(r.dimensions||((n=r.embedding)==null?void 0:n.length)||0)*8}),{count:a,byModel:t,approxBytes:s}}async getActivityEmbedding(t){return this.activityEmbeddings.get(t)}async bulkGetActivityEmbeddings(t){return this.activityEmbeddings.bulkGet(t)}async upsertActivityEmbeddings(t){t.length&&await this.activityEmbeddings.bulkPut(t)}async getActivityEmbeddingsBySession(t){return t?this.activityEmbeddings.where("activitySessionId").equals(t).toArray():[]}async getActivityEmbeddingsByUrl(t){return t?this.activityEmbeddings.where("url").equals(t).toArray():[]}async setActivitySessionIdForUrl(t,a){return!t||!a?0:this.activityEmbeddings.where("url").equals(t).modify({activitySessionId:a})}async purgeActivityEmbeddingsOlderThan(t,a=500){return await this.purgeByIndexedCutoff(this.activityEmbeddings,"updatedAt",t,a)}async clearActivityEmbeddings(){await this.activityEmbeddings.clear()}async getActivityEmbeddingStats(){const t={};let a=0,s=0;return await this.activityEmbeddings.each(r=>{var n;a++,t[r.modelId]=(t[r.modelId]??0)+1,s+=(r.dimensions||((n=r.embedding)==null?void 0:n.length)||0)*8}),{count:a,byModel:t,approxBytes:s}}async putAudioCacheEntry(t,a){await this.transaction("rw",this.audioCache,this.audioCacheBlobs,async()=>{await this.audioCache.put(t),await this.audioCacheBlobs.put({trackId:t.trackId,data:a})})}async getAudioCacheBlob(t){const a=await this.audioCacheBlobs.get(t);return(a==null?void 0:a.data)||null}async listAudioCacheMeta(){return this.audioCache.orderBy("downloadedAtMs").reverse().toArray()}async deleteAudioCacheEntries(t){t.length&&await this.transaction("rw",this.audioCache,this.audioCacheBlobs,async()=>{await this.audioCache.bulkDelete(t),await this.audioCacheBlobs.bulkDelete(t)})}async clearAudioCache(){await this.transaction("rw",this.audioCache,this.audioCacheBlobs,async()=>{await this.audioCache.clear(),await this.audioCacheBlobs.clear()})}async purgeAudioCacheOlderThan(t){const a=await this.audioCache.where("downloadedAtMs").below(t).primaryKeys();return await this.deleteAudioCacheEntries(a),a}async clearAllData(){await Promise.all([this.items.clear(),this.itemRelations.clear(),this.tagIndex.clear(),this.userFiles.clear(),this.visitHistory.clear(),this.users.clear(),this.prefs.clear(),this.familyPolicyRules.clear(),this.metaLookup.clear(),this.pipelineData.clear(),this.embeddings.clear(),this.itemEmbeddings.clear(),this.activityEmbeddings.clear(),this.refState.clear(),this.binaryCache.clear(),this.emailCache.clear(),this.audioCache.clear(),this.audioCacheBlobs.clear()])}}const se=new Map;async function Ca(){const i=await He.instance.getCurrentUser(),e=(i==null?void 0:i.accountId)||null;if(!e)return null;const t=i.localUser?e:i._id,a=sa(t);return Jt({accountDbKey:t,db:a}),Qt(),Fe.has(t)||(Fe.add(t),$e(()=>{a.backfillLastUsedMs().catch(s=>{m("[lastUsedMs] backfill pass failed",s)})},aa)),a}function sa(i){if(!i)throw new Error("accountId is required to get AccountDatabase");if(!se.has(i)){const e=new ia(i);se.set(i,e)}return se.get(i)}async function ra(){for(const i of se.values())i.close();se.clear()}async function La(i){var t;if(await ra(),typeof(indexedDB==null?void 0:indexedDB.databases)!="function"){console.warn("indexedDB.databases() not supported, skipping prefix deletion");return}const e=await indexedDB.databases();for(const a of e)(t=a.name)!=null&&t.startsWith(i)&&await Ie.delete(a.name)}const Xe=/^(untitled|untitled (item|page|link|note|document|doc)|no title|\(no title\)|new tab)$/i,Ze=/^"?[A-Za-z0-9+/]{16,}={1,2}"?$/,We=80,na="Untitled";function Pa(i){const e=Z(i);return!e||Xe.test(e)}function xa(i){return typeof i=="string"&&Ze.test(i.trim())}function ge(i){const e=Z(i);return!e||Xe.test(e)||Ze.test(e)?"":e}function ca(i,e){const t=Z(i),a=Z(e);if(!t||!a)return!1;const s=a.replace(/^https?:\/\//i,"").replace(/\/+$/,"");return t===a||t===s||t===s.replace(/^www\./i,"")}function oa(i){const e=Z(i);if(!e)return"";try{const t=new URL(e);if(!t.hostname)return de(e);const a=t.pathname.replace(/\/+$/,"");return de(`${t.hostname.replace(/^www\./i,"")}${a}`)}catch{return de(e.replace(/^https?:\/\//i,""))}}function da(i){const e=i==null?void 0:i.value;if(typeof e!="string")return"";for(const t of e.split(/\r?\n/)){const a=Z(t.replace(/^\s*(#{1,6}\s+|[-*+]\s+|>\s*|\d+[.)]\s+)/,""));
2if(a)return de(a)}return""}function _a(i,e={}){return ua(i,e)||(e.fallback??na)}function ua(i,e={}){return la(i,e)||oa(i==null?void 0:i.url)}function la(i,e={}){var a,s,r,n,c;const t=i==null?void 0:i.url;for(const d of[e.relationName,i==null?void 0:i.name,(a=i==null?void 0:i.meta)==null?void 0:a.title]){const l=ge(d);if(l&&!ca(l,t))return l}return ge((r=(s=i==null?void 0:i.meta)==null?void 0:s.tsExtractedInfo)==null?void 0:r.channelName)||da(i==null?void 0:i.info)||ge((c=(n=i==null?void 0:i.meta)==null?void 0:n.fileInfo)==null?void 0:c.filename)}function Z(i){return typeof i=="string"?i.replace(/\s+/g," ").trim():""}function de(i){return i.length>We?`${i.slice(0,We-1).trimEnd()}â¦`:i}export{ka as A,Ta as B,o as C,Ka as D,Ea as E,Ra as F,Ma as G,Da as H,Me as L,pe as P,xe as R,ue as T,ua as a,_a as b,fa as c,Pa as d,ge as e,be as f,Ca as g,sa as h,Ia as i,Kt as j,ga as k,J as l,oa as m,wt as n,Re as o,ta as p,D as q,la as r,xa as s,va as t,wa as u,ba as v,Aa as w,Sa as x,La as y,ha as z};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.