From d1965038f701bab63ff1a37030e95a803741a11a Mon Sep 17 00:00:00 2001 From: aaronshaf Date: Sat, 16 Nov 2024 23:21:02 +0000 Subject: [PATCH] deploy: cb051f4cf71f6a39cff66b4306083c9e60476ae2 --- index.html | 2 +- static/js/{index.26ff25f0.js => index.b5e12056.js} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename static/js/{index.26ff25f0.js => index.b5e12056.js} (53%) diff --git a/index.html b/index.html index 0c6518b..ed6b8ba 100644 --- a/index.html +++ b/index.html @@ -1 +1 @@ -idb-cache
\ No newline at end of file +idb-cache
\ No newline at end of file diff --git a/static/js/index.26ff25f0.js b/static/js/index.b5e12056.js similarity index 53% rename from static/js/index.26ff25f0.js rename to static/js/index.b5e12056.js index 0b902a4..5241999 100644 --- a/static/js/index.26ff25f0.js +++ b/static/js/index.b5e12056.js @@ -1 +1 @@ -(()=>{"use strict";var e={2365:function(e,t,r){let n,o;var i,a=r("1549"),s=r("4194"),c=r("8082");class l extends Error{constructor(e){super(e),this.name="IDBCacheError",Object.setPrototypeOf(this,new.target.prototype)}}class d extends l{constructor(e){super(e),this.name="DatabaseError"}}class u extends l{constructor(e){super(e),this.name="CryptoError"}}class h extends l{constructor(e){super(e),this.name="WorkerInitializationError"}}class m extends l{constructor(e){super(e),this.name="EncryptionError"}}class f extends l{constructor(e){super(e),this.name="DecryptionError"}}class p extends l{constructor(e){super(e),this.name="TimeoutError"}}function w(e,t){e.forEach((r,n)=>{r.reject(new h(t)),clearTimeout(r.timer),e.delete(n)})}async function y(e,t,r,n,o,i=5e3){return new Promise((a,s)=>{let c=setTimeout(()=>{let e=n.get(t);e&&(e.reject(new p("Request timed out")),n.delete(t))},i);n.set(t,{resolve:a,reject:s,timer:c});let l=[];o&&o.length>0&&l.push(...o);try{l.length>0?e.postMessage(r,l):e.postMessage(r)}catch(r){console.error("Failed to post message to worker:",r);let e=n.get(t);e&&(clearTimeout(e.timer),e.reject(new h("Failed to communicate with the worker.")),n.delete(t));return}})}async function g(e,t,r){let n=crypto.randomUUID();try{return await y(e,n,{requestId:n,type:"encrypt",payload:{value:t}},r,[],5e3)}catch(e){if(e instanceof h||e instanceof m||e instanceof l)throw e;throw new m(e instanceof Error?e.message:"Unknown encryption error")}}async function b(e,t,r,n){let o=crypto.randomUUID();try{return await y(e,o,{requestId:o,type:"decrypt",payload:{iv:t,ciphertext:r}},n,[t,r],5e3)}catch(e){if(e instanceof h||e instanceof f||e instanceof l)throw e;throw new f(e instanceof Error?e.message:"Unknown decryption error")}}let k=(e,t)=>t.some(t=>e instanceof t),x=new WeakMap,j=new WeakMap,v=new WeakMap,I={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return x.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return E(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function C(e){I=e(I)}function E(e){if(e instanceof IDBRequest)return function(e){let t=new Promise((t,r)=>{let n=()=>{e.removeEventListener("success",o),e.removeEventListener("error",i)},o=()=>{t(E(e.result)),n()},i=()=>{r(e.error),n()};e.addEventListener("success",o),e.addEventListener("error",i)});return v.set(t,e),t}(e);if(j.has(e))return j.get(e);let t=function(e){if("function"==typeof e){var t;return t=e,(o||(o=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(B(this),e),E(this.request)}:function(...e){return E(t.apply(B(this),e))}}return(e instanceof IDBTransaction&&!function(e){if(x.has(e))return;let t=new Promise((t,r)=>{let n=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",i),e.removeEventListener("abort",i)},o=()=>{t(),n()},i=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",o),e.addEventListener("error",i),e.addEventListener("abort",i)});x.set(e,t)}(e),k(e,n||(n=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])))?new Proxy(e,I):e}(e);return t!==e&&(j.set(e,t),v.set(t,e)),t}let B=e=>v.get(e);function D(e,t,{blocked:r,upgrade:n,blocking:o,terminated:i}={}){let a=indexedDB.open(e,t),s=E(a);return n&&a.addEventListener("upgradeneeded",e=>{n(E(a.result),e.oldVersion,e.newVersion,E(a.transaction),e)}),r&&a.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),s.then(e=>{i&&e.addEventListener("close",()=>i()),o&&e.addEventListener("versionchange",e=>o(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}let S=["get","getKey","getAll","getAllKeys","count"],$=["put","add","delete","clear"],P=new Map;function M(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t))return;if(P.get(t))return P.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,o=$.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||S.includes(r)))return;let i=async function(e,...t){let i=this.transaction(e,o?"readwrite":"readonly"),a=i.store;return n&&(a=a.index(t.shift())),(await Promise.all([a[r](...t),o&&i.done]))[0]};return P.set(t,i),i}I=(e=>({...e,get:(t,r,n)=>M(t,r)||e.get(t,r,n),has:(t,r)=>!!M(t,r)||e.has(t,r)}))(I);let R=["continue","continuePrimaryKey","advance"],z={},L=new WeakMap,O=new WeakMap,W={get(e,t){if(!R.includes(t))return e[t];let r=z[t];return!r&&(r=z[t]=function(...e){L.set(this,O.get(this)[t](...e))}),r}};async function*T(...e){let t=this;if(!(t instanceof IDBCursor)&&(t=await t.openCursor(...e)),!t)return;let r=new Proxy(t,W);for(O.set(r,t),v.set(r,B(t));t;)yield r,t=await (L.get(r)||t.continue()),L.delete(r)}function N(e,t){return t===Symbol.asyncIterator&&k(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&k(e,[IDBIndex,IDBObjectStore])}I=(e=>({...e,get:(t,r,n)=>N(t,r)?T:e.get(t,r,n),has:(t,r)=>N(t,r)||e.has(t,r)}))(I);let U=new Map;async function K(e){var t;if(U.has(e)){let t=U.get(e);if("string"==typeof t)return t}let r=new TextEncoder().encode(e);let n=[(t=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-512",r))).map(e=>e.toString(16).padStart(2,"0")).join("")).slice(0,8),t.slice(8,12),`4${t.slice(13,16)}`,(3&Number.parseInt(t.slice(16,17),16)|8).toString(16)+t.slice(17,20),t.slice(20,32)].join("-");return U.set(e,n),n}async function A(e,t,r){let n=[],o=e.transaction(t,"readonly"),i=o.store,a=`${r}-chunk-000000-`,s=`${r}-chunk-999999\uffff`,c=IDBKeyRange.bound(a,s,!1,!1),l=await i.openKeyCursor(c);for(;l;)n.push(l.key),l=await l.continue();return await o.done,n}function V(e,t){if(!e.objectStoreNames.contains(t)){let r=e.createObjectStore(t,{keyPath:"key"});r.createIndex("byTimestamp","timestamp"),r.createIndex("byCacheBuster","cacheBuster")}}async function G(e,t,r){try{return await D(e,r,{upgrade(e){V(e,t)}})}catch(n){if(n instanceof DOMException&&"VersionError"===n.name)return console.warn(`VersionError: Deleting database ${e} and retrying...`),await function(e,{blocked:t}={}){let r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",e=>t(e.oldVersion,e)),E(r).then(()=>void 0)}(e),await D(e,r,{upgrade(e){V(e,t)}});throw n}}function F(){let e=null,t=new Map,r=1e5,n=null,o=null;async function i(e){if(!o)throw Error("Fixed salt (cacheBuster) not initialized");let n=`${new TextDecoder().decode(e)}-${new TextDecoder().decode(new Uint8Array(o))}`;if(t.has(n)){let e=t.get(n);if(void 0!==e)return e}let i=await crypto.subtle.importKey("raw",e,{name:"PBKDF2"},!1,["deriveKey"]),a=await crypto.subtle.deriveKey({name:"PBKDF2",salt:o,iterations:r,hash:"SHA-512"},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return t.set(n,a),a}async function a(){if(!e)throw Error("Cache key not provided for encryption worker");try{null==n||n.postMessage({type:"ready"})}catch(t){console.error("Worker: Failed to initialize AES key:",t);let e=t instanceof Error?t.message:"Unknown initialization error";null==n||n.postMessage({type:"initError",error:e})}}async function s(t){if(!e)throw Error("Cache key not initialized");if(!o)throw Error("Fixed salt (cacheBuster) not initialized");let r=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder,a=await i(e),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},a,n.encode(t));return{iv:r.buffer,ciphertext:s}}async function c(t,r){if(!e)throw Error("AES key not initialized");if(!o)throw Error("Fixed salt (cacheBuster) not initialized");let n=new Uint8Array(t),a=await i(e),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},a,r);return new TextDecoder().decode(s)}let l=[],d=1,u=0;function h(e){l.push(e),m()}async function m(){for(;u0;){let e=l.shift();e&&(u++,(async()=>{let t=performance.now();try{await e()}catch(e){console.error("Worker: Task execution error:",e)}finally{(function(e){e<40&&d<10?d++:e>80&&d>1&&d--})(performance.now()-t),u--,m()}})())}}async function f(t){var i,l,d,u,m;let{type:f,payload:p,requestId:w}=t.data;switch(f){case"initialize":{let{cacheKey:t,pbkdf2Iterations:n,cacheBuster:i}=p;e=new TextEncoder().encode(t),r=n||1e5,o=new TextEncoder().encode(i).buffer,await a()}break;case"encrypt":{;let{value:e}=p;await (i=w,l=e,void h(async()=>{try{let e=await s(l);if(!n)throw Error("MessagePort is not available");n.postMessage({requestId:i,type:"encryptResult",result:e},[e.iv,e.ciphertext])}catch(t){console.error("Worker: Encryption error:",t);let e=t instanceof Error?t.message:"Unknown encryption error";n&&n.postMessage({requestId:i,type:"error",error:e})}}))}break;case"decrypt":{;let{iv:e,ciphertext:t}=p;await (d=w,u=e,m=t,void h(async()=>{try{let e=await c(u,m);if(!n)throw Error("MessagePort is not available");n.postMessage({requestId:d,type:"decryptResult",result:e})}catch(t){console.error("Worker: Decryption error:",t);let e=t instanceof Error?t.message:"Unknown decryption error";n&&n.postMessage({requestId:d,type:"error",error:e})}}))}break;case"destroy":e&&(e.fill(0),e=null),o&&(new Uint8Array(o).fill(0),o=null),n&&(n.close(),n=null),self.close();break;default:console.warn(`Worker: Unknown message type received: ${f}. Ignoring the message.`)}}self.onmessage=function(e){let{type:t}=e.data;"init"===t&&e.ports&&e.ports.length>0&&((n=e.ports[0]).onmessage=f,n.start())}}function q(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}let _=null===(i=crypto)||void 0===i?void 0:i.subtle;var H=r("2773"),X=r.n(H);function Y(e){let t=0;for(let r=0;r{var o,i,a,s;let{worker:c,port:d}=function(e,t){let r=new Blob([`(${e.toString()})()`],{type:"application/javascript"}),n=URL.createObjectURL(r),o=new Worker(n),i=new MessageChannel;return o.postMessage({type:"init"},[i.port2]),o.onmessage=()=>{URL.revokeObjectURL(n)},o.onerror=e=>{console.error("Worker encountered an error:",e.message),t("Worker encountered an error and was terminated."),o.terminate()},i.port1.onmessageerror=()=>{console.warn("MessagePort encountered a message error. Worker may have been terminated."),t("Worker was terminated unexpectedly."),i.port1.close()},{worker:o,port:i.port1}}(F,e=>{n(new h(e)),w(this.pendingRequests,e)});this.worker=c,this.port=d,o=d,i=r,a=n,s=this.pendingRequests,o.onmessage=e=>{let t=e.data;if("ready"===t.type)i();else if("initError"===t.type)a(new h(t.error)),w(s,t.error);else{var r,n,o;if("encryptResult"===(r=t).type&&"string"==typeof r.requestId){let{requestId:e,result:r}=t,n=s.get(e);n&&(clearTimeout(n.timer),n.resolve(r),s.delete(e))}else{;if("decryptResult"===(n=t).type&&"string"==typeof n.requestId){let{requestId:e,result:r}=t,n=s.get(e);n&&(clearTimeout(n.timer),n.resolve(r),s.delete(e))}else{;if("error"===(o=t).type&&"string"==typeof o.requestId){let{requestId:e,error:r}=t,n=s.get(e);if(n){let t;let o=r.toLowerCase();t=o.includes("encrypt")?new m(r):o.includes("decrypt")?new f(r):o.includes("key")?new u(r):new l(r),clearTimeout(n.timer),n.reject(t),s.delete(e)}}else console.warn("WorkerUtils: Unknown message type received. Ignoring the message.",t)}}}},o.onmessageerror=e=>{console.error("Worker encountered a message error:",e),a(new h("Worker failed to initialize")),w(s,"Worker encountered an error and was terminated."),o.close()},d.postMessage({type:"initialize",payload:{cacheKey:e,cacheBuster:t,pbkdf2Iterations:this.pbkdf2Iterations}})});try{await this.workerReadyPromise}catch(e){if(console.error("Worker failed to initialize:",e),e instanceof l)throw e;throw new h("Worker failed to initialize.")}}async flushBustedCacheItems(){try{let e=(await this.dbReadyPromise).transaction(this.storeName,"readwrite"),t=e.store.index("byCacheBuster"),r=this.cacheBuster,n=IDBKeyRange.upperBound(r,!0),o=IDBKeyRange.lowerBound(r,!0),i=async e=>{let r=0,n=await t.openCursor(e);for(;n;)this.debug&&console.debug("Deleting item with cacheBuster:",n.value.cacheBuster),await n.delete(),r++,n=await n.continue();return r},a=await Promise.all([i(n),i(o)]);await e.done,this.debug&&a.reduce((e,t)=>e+(t||0),0)>0&&console.debug("Flushed old cache items with different cacheBuster.")}catch(e){if(console.error("Error during flushBustedCacheItems:",e),e instanceof d)throw e;throw new d("Failed to flush old cache items.")}}async cleanupCache(){try{let e=(await this.dbReadyPromise).transaction(this.storeName,"readwrite"),t=e.store,r=t.index("byTimestamp");t.index("byCacheBuster");let n=Date.now(),o=await r.openCursor();for(;o;){let{timestamp:e}=o.value;if(e<=n){let t=n-e;this.debug&&console.debug(`Deleting expired item with timestamp ${e}. It is ${t}ms older than the expiration.`),await o.delete()}else break;o=await o.continue()}if(void 0!==this.maxChunks){let e=await t.count();if(e>this.maxChunks){let t=e-this.maxChunks;this.debug&&console.debug(`Total chunks (${e}) exceed maxChunks (${this.maxChunks}). Deleting ${t} oldest chunks.`);let n=0,o=await r.openCursor(null,"next");for(;o&&ne.index-t.index);let s=await Promise.all(a.map(({data:{iv:e,ciphertext:t}})=>b(this.getPort(),e,t,this.pendingRequests))),c=Date.now()-t;return this.debug&&c>200&&console.debug(`getItem for key ${e} took ${c}ms`),s.join("")}catch(t){if(t instanceof f)throw console.error(`Decryption failed for key ${e}:`,t),t;if(t instanceof d)throw console.error(`Database error while getting key ${e}:`,t),t;if(t instanceof h)throw console.error(`Worker initialization error while getting key ${e}:`,t),t;if(t instanceof l)throw console.error(`IDBCache error while getting key ${e}:`,t),t;throw console.error(`Unexpected error while getting key ${e}:`,t),new l("An unexpected error occurred.")}}async setItem(e,t){try{let i=Date.now();if(!this.dbReadyPromise)return;await this.ensureWorkerInitialized();let a=await this.dbReadyPromise,s=await K(`${this.cacheKey}:${e}`),c=Date.now()+this.gcTime,l=await A(a,this.storeName,s),d=new Set(l),u=new Set,h=[],m=[];for(let e=0;e!u.has(e)),p=a.transaction(this.storeName,"readwrite"),w=p.store,y=[];for(let e of m)y.push(w.put(e));for(let{chunkKey:e,encryptedChunk:t}of h)y.push(w.put({...t,key:e,timestamp:c}));for(let e of f)y.push(w.delete(e));await Promise.all(y),await p.done;let b=Date.now()-i;this.debug&&b>200&&console.debug(`setItem for key ${e} took ${b}ms`)}catch(e){if(e instanceof h)throw console.error("Worker port is not initialized:",e),e;if(e instanceof d)throw console.error("Database error in setItem:",e),e;if(e instanceof m)throw console.error("Encryption error in setItem:",e),e;if(e instanceof l)throw console.error("IDBCache error in setItem:",e),e;throw console.error("Unexpected error in setItem:",e),new l("An unexpected error occurred during setItem.")}}async removeItem(e){try{let t=await this.dbReadyPromise,r=await K(`${this.cacheKey}:${e}`),n=await A(t,this.storeName,r),o=t.transaction(this.storeName,"readwrite"),i=o.store,a=n.map(e=>i.delete(e));await Promise.all(a),await o.done}catch(e){if(console.error("Error in removeItem:",e),e instanceof d||e instanceof l)throw e;throw new d("Failed to remove item from the cache.")}}async count(){try{let e=(await this.dbReadyPromise).transaction(this.storeName,"readonly"),t=e.store,r=await t.count();return await e.done,this.debug&&console.debug(`Total entries in cache: ${r}`),r}catch(e){if(console.error("Error in count():",e),e instanceof d)throw e;throw new d("Failed to count items in the cache.")}}async clear(){try{let e=(await this.dbReadyPromise).transaction(this.storeName,"readwrite"),t=e.store;await t.clear(),await e.done,this.debug&&console.debug("All items have been cleared from the cache.")}catch(e){if(console.error("Error in clear:",e),e instanceof d||e instanceof l)throw e;throw new d("Failed to clear the cache.")}}async destroy(e){let{clearData:t=!1}=e||{};try{t&&await this.clear(),void 0!==this.cleanupIntervalId&&clearInterval(this.cleanupIntervalId),this.pendingRequests.forEach((e,t)=>{e.reject(new l("IDBCache instance is being destroyed.")),this.pendingRequests.delete(t)}),this.port&&(this.port.postMessage({type:"destroy"}),this.port.close(),this.port=null),this.worker&&(this.worker.terminate(),this.worker=null),this.workerReadyPromise=null,this.debug&&console.debug("IDBCache instance has been destroyed.")}catch(e){if(console.error("Error in destroy:",e),e instanceof l)throw e;throw new l("Failed to destroy the cache instance.")}}constructor(e){q(this,"dbReadyPromise",void 0),q(this,"storeName",void 0),q(this,"worker",null),q(this,"port",null),q(this,"pendingRequests",void 0),q(this,"workerReadyPromise",null),q(this,"gcTime",void 0),q(this,"cleanupIntervalId",void 0),q(this,"cacheKey",void 0),q(this,"chunkSize",void 0),q(this,"cleanupInterval",void 0),q(this,"pbkdf2Iterations",void 0),q(this,"cacheBuster",void 0),q(this,"debug",void 0),q(this,"maxChunks",void 0);let{cacheKey:t,cacheBuster:r,debug:n=!1,dbName:o="idb-cache",gcTime:i=6048e5,chunkSize:a=25e3,cleanupInterval:s=6e4,pbkdf2Iterations:c=1e5,maxChunks:l}=e;if(this.storeName="cache",this.cacheKey=t,this.cacheBuster=r,this.debug=n,this.gcTime=i,this.chunkSize=a,this.cleanupInterval=s,this.pbkdf2Iterations=c,this.maxChunks=l,this.pendingRequests=new Map,!window.indexedDB)throw new d("IndexedDB is not supported.");if(!_)throw new u("Web Crypto API not available in this environment");this.dbReadyPromise=G(o,this.storeName,1),this.cleanupIntervalId=window.setInterval(async()=>{try{await this.cleanupCache()}catch(e){console.error("Error during cleanup:",e)}},this.cleanupInterval),this.initWorker(t,r).then(()=>{this.cleanupCache().catch(e=>console.error("Initial cleanup failed:",e)),this.flushBustedCacheItems().catch(e=>console.error("Failed to flush old cache items:",e))}).catch(e=>{console.error("Worker initialization failed:",e)})}}({cacheKey:es,cacheBuster:ec,debug:!0});window.idbCacheInstance=el;let ed=()=>{let e=Number.parseInt(new URLSearchParams(window.location.hash.slice(1)).get("size")??"0",10);return!Number.isNaN(e)&&e>0?1024*e:32768},eu=document.getElementById("root");eu&&c.createRoot(eu).render((0,a.jsx)(s.StrictMode,{children:(0,a.jsx)(()=>{let[e,t]=(0,s.useState)(null),[r,n]=(0,s.useState)(null),[o,i]=(0,s.useState)(null),[c,l]=(0,s.useState)(null),[d,u]=(0,s.useState)(null),[h,m]=(0,s.useState)(null),[f,p]=(0,s.useState)(null),[w,y]=(0,s.useState)(ed()),[g,b]=(0,s.useState)(null);(0,s.useEffect)(()=>{let e=new URLSearchParams(window.location.hash.slice(1));e.set("size",String(Math.round(w/1024))),window.location.hash=`#${e.toString()}`},[w]);let k=(0,s.useRef)(0),[x,j]=(0,s.useState)(()=>Y(`initial-seed-${k.current}`)),v=(0,s.useCallback)(async()=>{let e=Y(`seed-${k.current}`);k.current+=1,j(e);let r=performance.now(),n=Array.from({length:1},(t,r)=>(function(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",n=`${e}-${r}`;if(Z[n])return Z[n];let o=X().create(r),i=Math.ceil(e),a=Array(i);for(let e=0;ee;)s=s.slice(0,-1);return Z[n]=s,s})(w,`${e}-${r}`));i(performance.now()-r);let o=performance.now();for(let t=0;t<1;t++)await el.setItem(`item-${e}-${t}`,n[t]);l(performance.now()-o),t(Y(n.join("")))},[w]),I=(0,s.useCallback)(async()=>{let e=[],t=performance.now();for(let t=0;t<1;t++){let r=await el.getItem(`item-${x}-${t}`);e.push(r)}u(performance.now()-t),n(e.filter(e=>e).length>0?Y(e.join("")):null)},[x]),C=(0,s.useCallback)(async()=>{let e=performance.now(),t=await el.count();m(performance.now()-e),b(t)},[]),E=(0,s.useCallback)(async()=>{let e=performance.now();await el.clear(),p(performance.now()-e)},[]);return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(ei,{}),(0,a.jsx)("div",{className:"min-h-screen bg-gray-50 p-8",children:(0,a.jsxs)(ee.G,{as:"div",display:"block",width:"820px",margin:"0 auto",children:[(0,a.jsx)(er.X,{level:"h1",margin:"0 0 small 0",children:"@instructure/idb-cache"}),(0,a.jsxs)("form",{children:[(0,a.jsxs)(et.kC,{direction:"column",gap:"small",children:[(0,a.jsx)(et.kC.Item,{children:(0,a.jsxs)(et.kC,{gap:"medium",justifyItems:"space-between",children:[(0,a.jsx)(et.kC.Item,{width:"48%",children:(0,a.jsxs)(et.kC,{direction:"row",alignItems:"end",margin:"xx-small 0",children:[(0,a.jsx)(et.kC.Item,{shouldGrow:!0,children:(0,a.jsx)(eo.o,{renderLabel:"Cache key:",interaction:"disabled",defaultValue:es})}),(0,a.jsx)(et.kC.Item,{children:(0,a.jsx)(J.z,{"aria-label":"Reset cache key",margin:"0 0 0 xxx-small","data-testid":"reset-cacheKey",onClick:()=>{localStorage.removeItem("cacheKey"),window.location.reload()},children:"Reset"})})]})}),(0,a.jsx)(et.kC.Item,{width:"48%",children:(0,a.jsxs)(et.kC,{direction:"row",alignItems:"end",margin:"xx-small 0",children:[(0,a.jsx)(et.kC.Item,{shouldGrow:!0,children:(0,a.jsx)(eo.o,{renderLabel:"Cache buster:",interaction:"disabled",defaultValue:ec})}),(0,a.jsx)(et.kC.Item,{children:(0,a.jsx)(J.z,{"aria-label":"Reset cache buster",margin:"0 0 0 xxx-small","data-testid":"reset-cacheBuster",onClick:()=>{localStorage.removeItem("cacheBuster"),window.location.reload()},children:"Reset"})})]})})]})}),(0,a.jsxs)(et.kC,{justifyItems:"space-between",children:[(0,a.jsx)(et.kC.Item,{width:"48%",children:(0,a.jsx)(en.Y,{renderLabel:"Size of data (KB):",onChange:e=>{y(Math.max(1024*Number.parseInt(e.target.value,10),1024))},onIncrement:()=>{y(e=>Math.max(e+1024,1024))},onDecrement:()=>{y(e=>Math.max(e-1024,1024))},isRequired:!0,value:Math.round(w/1024)})}),(0,a.jsx)(et.kC.Item,{width:"48%",children:(0,a.jsx)(en.Y,{renderLabel:"Number of chunks:",interaction:"disabled",value:Math.ceil(w/25e3)})})]})]}),(0,a.jsx)(er.X,{level:"h2",margin:"medium 0 small 0",children:"Tests"}),(0,a.jsx)(ee.G,{as:"div",display:"block",margin:"small none",padding:"medium",background:"primary",shadow:"resting",children:(0,a.jsxs)(et.kC,{direction:"column",children:[(0,a.jsx)(J.z,{"data-testid":"set-item-button",color:"primary",onClick:v,children:"setItem"}),(0,a.jsx)(ee.G,{padding:"medium 0 0 0",children:(0,a.jsxs)(et.kC,{children:[(0,a.jsx)(et.kC.Item,{size:"33.3%",children:(0,a.jsx)(Q.j,{renderLabel:"Generate Test Data","data-testid":"generate-time",renderValue:null!==o?`${Math.round(o)} ms`:(0,a.jsx)(ea,{})})}),(0,a.jsx)(et.kC.Item,{shouldGrow:!0,children:(0,a.jsx)(Q.j,{renderLabel:"setItem","data-testid":"set-time",renderValue:null!==c?`${Math.round(c)} ms`:(0,a.jsx)(ea,{})})}),(0,a.jsx)(et.kC.Item,{size:"33.3%",children:(0,a.jsx)(Q.j,{"data-testid":"hash1",renderLabel:"Hash",renderValue:e||(0,a.jsx)(ea,{})})})]})})]})}),(0,a.jsx)(ee.G,{as:"div",display:"block",margin:"small none",padding:"medium",background:"primary",shadow:"resting",children:(0,a.jsxs)(et.kC,{direction:"column",children:[(0,a.jsx)(J.z,{"data-testid":"get-item-button",color:"primary",onClick:I,children:"getItem"}),(0,a.jsx)(ee.G,{padding:"medium 0 0 0",children:(0,a.jsxs)(et.kC,{children:[(0,a.jsx)(et.kC.Item,{size:"33.3%",children:"\xa0"}),(0,a.jsx)(et.kC.Item,{shouldGrow:!0,children:(0,a.jsx)(Q.j,{renderLabel:"getItem","data-testid":"get-time",renderValue:null!==d?`${Math.round(d)} ms`:(0,a.jsx)(ea,{})})}),(0,a.jsx)(et.kC.Item,{size:"33.3%",children:(0,a.jsx)(Q.j,{renderLabel:"Hash","data-testid":"hash2",renderValue:r||(0,a.jsx)(ea,{})})})]})})]})}),(0,a.jsx)(ee.G,{as:"div",display:"block",margin:"small none",padding:"medium",background:"primary",shadow:"resting",children:(0,a.jsxs)(et.kC,{direction:"column",children:[(0,a.jsx)(J.z,{"data-testid":"count-button",color:"primary",onClick:C,children:"count"}),(0,a.jsx)(ee.G,{padding:"medium 0 0 0",children:(0,a.jsxs)(et.kC,{children:[(0,a.jsx)(et.kC.Item,{size:"33.3%",children:"\xa0"}),(0,a.jsx)(et.kC.Item,{shouldGrow:!0,children:(0,a.jsx)(Q.j,{"data-testid":"count-time",renderLabel:"count",renderValue:null!==h?`${Math.round(h)} ms`:(0,a.jsx)(ea,{})})}),(0,a.jsx)(et.kC.Item,{size:"33.3%",children:(0,a.jsx)(Q.j,{renderLabel:"Chunks","data-testid":"count-value",renderValue:"number"==typeof g?g:(0,a.jsx)(ea,{})})})]})})]})}),(0,a.jsx)(ee.G,{as:"div",display:"block",margin:"small 0 0 0",padding:"medium",background:"primary",shadow:"resting",children:(0,a.jsxs)(et.kC,{direction:"column",children:[(0,a.jsx)(J.z,{"data-testid":"clear-button",color:"primary",onClick:E,children:"clear"}),(0,a.jsx)(ee.G,{padding:"medium 0 0 0",children:(0,a.jsxs)(et.kC,{children:[(0,a.jsx)(et.kC.Item,{size:"33.3%",children:"\xa0"}),(0,a.jsx)(et.kC.Item,{shouldGrow:!0,children:(0,a.jsx)(Q.j,{renderLabel:"clear","data-testid":"clear-time",renderValue:null!==f?`${Math.round(f)} ms`:(0,a.jsx)(ea,{})})}),(0,a.jsx)(et.kC.Item,{size:"33.3%",children:"\xa0"})]})})]})})]})]})})]})},{})}))}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}r.m=e,r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},(()=>{var e,t=Object.getPrototypeOf?function(e){return Object.getPrototypeOf(e)}:function(e){return e.__proto__};r.t=function(n,o){if(1&o&&(n=this(n)),8&o||"object"==typeof n&&n&&(4&o&&n.__esModule||16&o&&"function"==typeof n.then))return n;var i=Object.create(null);r.r(i);var a={};e=e||[null,t({}),t([]),t(t)];for(var s=2&o&&n;"object"==typeof s&&!~e.indexOf(s);s=t(s))Object.getOwnPropertyNames(s).forEach(function(e){a[e]=function(){return n[e]}});return a.default=function(){return n},r.d(i,a),i}})(),r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e=[];r.O=function(t,n,o,i){if(n){i=i||0;for(var a=e.length;a>0&&e[a-1][2]>i;a--)e[a]=e[a-1];e[a]=[n,o,i];return}for(var s=1/0,a=0;a=i)&&Object.keys(r.O).every(function(e){return r.O[e](n[l])})?n.splice(l--,1):(c=!1,i{var e={980:0};r.O.j=function(t){return 0===e[t]};var t=function(t,n){var o=n[0],i=n[1],a=n[2],s,c,l=0;if(o.some(function(t){return 0!==e[t]})){for(s in i)r.o(i,s)&&(r.m[s]=i[s]);if(a)var d=a(r)}for(t&&t(n);l{"use strict";var e={2365:function(e,t,r){let n,o;var a,i=r("1549"),s=r("4194"),c=r("8082");class l extends Error{constructor(e){super(e),this.name="IDBCacheError",Object.setPrototypeOf(this,new.target.prototype)}}class d extends l{constructor(e){super(e),this.name="DatabaseError"}}class u extends l{constructor(e){super(e),this.name="CryptoError"}}class h extends l{constructor(e){super(e),this.name="WorkerInitializationError"}}class m extends l{constructor(e){super(e),this.name="EncryptionError"}}class f extends l{constructor(e){super(e),this.name="DecryptionError"}}class p extends l{constructor(e){super(e),this.name="TimeoutError"}}function w(e,t){e.forEach((r,n)=>{r.reject(new h(t)),clearTimeout(r.timer),e.delete(n)})}async function y(e,t,r,n,o,a=5e3){return new Promise((i,s)=>{let c=setTimeout(()=>{let e=n.get(t);e&&(e.reject(new p("Request timed out")),n.delete(t))},a);n.set(t,{resolve:i,reject:s,timer:c});let l=[];o&&o.length>0&&l.push(...o);try{l.length>0?e.postMessage(r,l):e.postMessage(r)}catch(r){console.error("Failed to post message to worker:",r);let e=n.get(t);e&&(clearTimeout(e.timer),e.reject(new h("Failed to communicate with the worker.")),n.delete(t));return}})}async function g(e,t,r){let n=crypto.randomUUID();try{return await y(e,n,{requestId:n,type:"encrypt",payload:{value:t}},r,[],5e3)}catch(e){if(e instanceof h||e instanceof m||e instanceof l)throw e;throw new m(e instanceof Error?e.message:"Unknown encryption error")}}async function b(e,t,r,n){let o=crypto.randomUUID();try{return await y(e,o,{requestId:o,type:"decrypt",payload:{iv:t,ciphertext:r}},n,[t,r],5e3)}catch(e){if(e instanceof h||e instanceof f||e instanceof l)throw e;throw new f(e instanceof Error?e.message:"Unknown decryption error")}}let k=(e,t)=>t.some(t=>e instanceof t),x=new WeakMap,v=new WeakMap,I=new WeakMap,j={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return x.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return E(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function C(e){j=e(j)}function E(e){if(e instanceof IDBRequest)return function(e){let t=new Promise((t,r)=>{let n=()=>{e.removeEventListener("success",o),e.removeEventListener("error",a)},o=()=>{t(E(e.result)),n()},a=()=>{r(e.error),n()};e.addEventListener("success",o),e.addEventListener("error",a)});return I.set(t,e),t}(e);if(v.has(e))return v.get(e);let t=function(e){if("function"==typeof e){var t;return t=e,(o||(o=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(B(this),e),E(this.request)}:function(...e){return E(t.apply(B(this),e))}}return(e instanceof IDBTransaction&&!function(e){if(x.has(e))return;let t=new Promise((t,r)=>{let n=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",a),e.removeEventListener("abort",a)},o=()=>{t(),n()},a=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",o),e.addEventListener("error",a),e.addEventListener("abort",a)});x.set(e,t)}(e),k(e,n||(n=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])))?new Proxy(e,j):e}(e);return t!==e&&(v.set(e,t),I.set(t,e)),t}let B=e=>I.get(e);function D(e,t,{blocked:r,upgrade:n,blocking:o,terminated:a}={}){let i=indexedDB.open(e,t),s=E(i);return n&&i.addEventListener("upgradeneeded",e=>{n(E(i.result),e.oldVersion,e.newVersion,E(i.transaction),e)}),r&&i.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),s.then(e=>{a&&e.addEventListener("close",()=>a()),o&&e.addEventListener("versionchange",e=>o(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}let S=["get","getKey","getAll","getAllKeys","count"],$=["put","add","delete","clear"],P=new Map;function M(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t))return;if(P.get(t))return P.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,o=$.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||S.includes(r)))return;let a=async function(e,...t){let a=this.transaction(e,o?"readwrite":"readonly"),i=a.store;return n&&(i=i.index(t.shift())),(await Promise.all([i[r](...t),o&&a.done]))[0]};return P.set(t,a),a}j=(e=>({...e,get:(t,r,n)=>M(t,r)||e.get(t,r,n),has:(t,r)=>!!M(t,r)||e.has(t,r)}))(j);let R=["continue","continuePrimaryKey","advance"],z={},L=new WeakMap,O=new WeakMap,W={get(e,t){if(!R.includes(t))return e[t];let r=z[t];return!r&&(r=z[t]=function(...e){L.set(this,O.get(this)[t](...e))}),r}};async function*T(...e){let t=this;if(!(t instanceof IDBCursor)&&(t=await t.openCursor(...e)),!t)return;let r=new Proxy(t,W);for(O.set(r,t),I.set(r,B(t));t;)yield r,t=await (L.get(r)||t.continue()),L.delete(r)}function N(e,t){return t===Symbol.asyncIterator&&k(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&k(e,[IDBIndex,IDBObjectStore])}j=(e=>({...e,get:(t,r,n)=>N(t,r)?T:e.get(t,r,n),has:(t,r)=>N(t,r)||e.has(t,r)}))(j);let U=new Map;async function K(e){var t;if(U.has(e)){let t=U.get(e);if("string"==typeof t)return t}let r=new TextEncoder().encode(e);let n=[(t=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-512",r))).map(e=>e.toString(16).padStart(2,"0")).join("")).slice(0,8),t.slice(8,12),`4${t.slice(13,16)}`,(3&Number.parseInt(t.slice(16,17),16)|8).toString(16)+t.slice(17,20),t.slice(20,32)].join("-");return U.set(e,n),n}async function A(e,t,r){let n=[],o=e.transaction(t,"readonly"),a=o.store,i=`${r}-chunk-000000-`,s=`${r}-chunk-999999\uffff`,c=IDBKeyRange.bound(i,s,!1,!1),l=await a.openKeyCursor(c);for(;l;)n.push(l.key),l=await l.continue();return await o.done,n}function V(e,t){if(!e.objectStoreNames.contains(t)){let r=e.createObjectStore(t,{keyPath:"key"});r.createIndex("byTimestamp","timestamp"),r.createIndex("byCacheBuster","cacheBuster")}}async function G(e,t,r){try{return await D(e,r,{upgrade(e){V(e,t)}})}catch(n){if(n instanceof DOMException&&"VersionError"===n.name)return console.warn(`VersionError: Deleting database ${e} and retrying...`),await function(e,{blocked:t}={}){let r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",e=>t(e.oldVersion,e)),E(r).then(()=>void 0)}(e),await D(e,r,{upgrade(e){V(e,t)}});throw n}}function F(){let e=null,t=new Map,r=1e5,n=null,o=null;async function a(e){if(!o)throw Error("Fixed salt (cacheBuster) not initialized");let n=`${new TextDecoder().decode(e)}-${new TextDecoder().decode(new Uint8Array(o))}`;if(t.has(n)){let e=t.get(n);if(void 0!==e)return e}let a=await crypto.subtle.importKey("raw",e,{name:"PBKDF2"},!1,["deriveKey"]),i=await crypto.subtle.deriveKey({name:"PBKDF2",salt:o,iterations:r,hash:"SHA-512"},a,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return t.set(n,i),i}async function i(){if(!e)throw Error("Cache key not provided for encryption worker");try{null==n||n.postMessage({type:"ready"})}catch(t){console.error("Worker: Failed to initialize AES key:",t);let e=t instanceof Error?t.message:"Unknown initialization error";null==n||n.postMessage({type:"initError",error:e})}}async function s(t){if(!e)throw Error("Cache key not initialized");if(!o)throw Error("Fixed salt (cacheBuster) not initialized");let r=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder,i=await a(e),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},i,n.encode(t));return{iv:r.buffer,ciphertext:s}}async function c(t,r){if(!e)throw Error("AES key not initialized");if(!o)throw Error("Fixed salt (cacheBuster) not initialized");let n=new Uint8Array(t),i=await a(e),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},i,r);return new TextDecoder().decode(s)}let l=[],d=1,u=0;function h(e){l.push(e),m()}async function m(){for(;u0;){let e=l.shift();e&&(u++,(async()=>{let t=performance.now();try{await e()}catch(e){console.error("Worker: Task execution error:",e)}finally{(function(e){e<40&&d<10?d++:e>80&&d>1&&d--})(performance.now()-t),u--,m()}})())}}async function f(t){var a,l,d,u,m;let{type:f,payload:p,requestId:w}=t.data;switch(f){case"initialize":{let{cacheKey:t,pbkdf2Iterations:n,cacheBuster:a}=p;e=new TextEncoder().encode(t),r=n||1e5,o=new TextEncoder().encode(a).buffer,await i()}break;case"encrypt":{;let{value:e}=p;await (a=w,l=e,void h(async()=>{try{let e=await s(l);if(!n)throw Error("MessagePort is not available");n.postMessage({requestId:a,type:"encryptResult",result:e},[e.iv,e.ciphertext])}catch(t){console.error("Worker: Encryption error:",t);let e=t instanceof Error?t.message:"Unknown encryption error";n&&n.postMessage({requestId:a,type:"error",error:e})}}))}break;case"decrypt":{;let{iv:e,ciphertext:t}=p;await (d=w,u=e,m=t,void h(async()=>{try{let e=await c(u,m);if(!n)throw Error("MessagePort is not available");n.postMessage({requestId:d,type:"decryptResult",result:e})}catch(t){console.error("Worker: Decryption error:",t);let e=t instanceof Error?t.message:"Unknown decryption error";n&&n.postMessage({requestId:d,type:"error",error:e})}}))}break;case"destroy":e&&(e.fill(0),e=null),o&&(new Uint8Array(o).fill(0),o=null),n&&(n.close(),n=null),self.close();break;default:console.warn(`Worker: Unknown message type received: ${f}. Ignoring the message.`)}}self.onmessage=function(e){let{type:t}=e.data;"init"===t&&e.ports&&e.ports.length>0&&((n=e.ports[0]).onmessage=f,n.start())}}function q(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}let _=null===(a=crypto)||void 0===a?void 0:a.subtle;var H=r("2773"),X=r.n(H);function Y(e){let t=0;for(let r=0;r{var o,a,i,s;let{worker:c,port:d}=function(e,t){let r=new Blob([`(${e.toString()})()`],{type:"application/javascript"}),n=URL.createObjectURL(r),o=new Worker(n),a=new MessageChannel;return o.postMessage({type:"init"},[a.port2]),o.onmessage=()=>{URL.revokeObjectURL(n)},o.onerror=e=>{console.error("Worker encountered an error:",e.message),t("Worker encountered an error and was terminated."),o.terminate()},a.port1.onmessageerror=()=>{console.warn("MessagePort encountered a message error. Worker may have been terminated."),t("Worker was terminated unexpectedly."),a.port1.close()},{worker:o,port:a.port1}}(F,e=>{n(new h(e)),w(this.pendingRequests,e)});this.worker=c,this.port=d,o=d,a=r,i=n,s=this.pendingRequests,o.onmessage=e=>{let t=e.data;if("ready"===t.type)a();else if("initError"===t.type)i(new h(t.error)),w(s,t.error);else{var r,n,o;if("encryptResult"===(r=t).type&&"string"==typeof r.requestId){let{requestId:e,result:r}=t,n=s.get(e);n&&(clearTimeout(n.timer),n.resolve(r),s.delete(e))}else{;if("decryptResult"===(n=t).type&&"string"==typeof n.requestId){let{requestId:e,result:r}=t,n=s.get(e);n&&(clearTimeout(n.timer),n.resolve(r),s.delete(e))}else{;if("error"===(o=t).type&&"string"==typeof o.requestId){let{requestId:e,error:r}=t,n=s.get(e);if(n){let t;let o=r.toLowerCase();t=o.includes("encrypt")?new m(r):o.includes("decrypt")?new f(r):o.includes("key")?new u(r):new l(r),clearTimeout(n.timer),n.reject(t),s.delete(e)}}else console.warn("WorkerUtils: Unknown message type received. Ignoring the message.",t)}}}},o.onmessageerror=e=>{console.error("Worker encountered a message error:",e),i(new h("Worker failed to initialize")),w(s,"Worker encountered an error and was terminated."),o.close()},d.postMessage({type:"initialize",payload:{cacheKey:e,cacheBuster:t,pbkdf2Iterations:this.pbkdf2Iterations}})});try{await this.workerReadyPromise}catch(e){if(console.error("Worker failed to initialize:",e),e instanceof l)throw e;throw new h("Worker failed to initialize.")}}async flushBustedCacheItems(){try{let e=(await this.dbReadyPromise).transaction(this.storeName,"readwrite"),t=e.store.index("byCacheBuster"),r=this.cacheBuster,n=IDBKeyRange.upperBound(r,!0),o=IDBKeyRange.lowerBound(r,!0),a=async e=>{let r=0,n=await t.openCursor(e);for(;n;)this.debug&&console.debug("Deleting item with cacheBuster:",n.value.cacheBuster),await n.delete(),r++,n=await n.continue();return r},i=await Promise.all([a(n),a(o)]);await e.done,this.debug&&i.reduce((e,t)=>e+(t||0),0)>0&&console.debug("Flushed old cache items with different cacheBuster.")}catch(e){if(console.error("Error during flushBustedCacheItems:",e),e instanceof d)throw e;throw new d("Failed to flush old cache items.")}}async cleanupCache(){try{let e=(await this.dbReadyPromise).transaction(this.storeName,"readwrite"),t=e.store,r=t.index("byTimestamp");t.index("byCacheBuster");let n=Date.now(),o=await r.openCursor();for(;o;){let{timestamp:e}=o.value;if(e<=n){let t=n-e;this.debug&&console.debug(`Deleting expired item with timestamp ${e}. It is ${t}ms older than the expiration.`),await o.delete()}else break;o=await o.continue()}if(void 0!==this.maxChunks){let e=await t.count();if(e>this.maxChunks){let t=e-this.maxChunks;this.debug&&console.debug(`Total chunks (${e}) exceed maxChunks (${this.maxChunks}). Deleting ${t} oldest chunks.`);let n=0,o=await r.openCursor(null,"next");for(;o&&ne.index-t.index);let s=await Promise.all(i.map(({data:{iv:e,ciphertext:t}})=>b(this.getPort(),e,t,this.pendingRequests))),c=Date.now()-t;return this.debug&&c>200&&console.debug(`getItem for key ${e} took ${c}ms`),s.join("")}catch(t){if(t instanceof f)throw console.error(`Decryption failed for key ${e}:`,t),t;if(t instanceof d)throw console.error(`Database error while getting key ${e}:`,t),t;if(t instanceof h)throw console.error(`Worker initialization error while getting key ${e}:`,t),t;if(t instanceof l)throw console.error(`IDBCache error while getting key ${e}:`,t),t;throw console.error(`Unexpected error while getting key ${e}:`,t),new l("An unexpected error occurred.")}}async setItem(e,t){try{let a=Date.now();if(!this.dbReadyPromise)return;await this.ensureWorkerInitialized();let i=await this.dbReadyPromise,s=await K(`${this.cacheKey}:${e}`),c=Date.now()+this.gcTime,l=await A(i,this.storeName,s),d=new Set(l),u=new Set,h=[],m=[];for(let e=0;e!u.has(e)),p=i.transaction(this.storeName,"readwrite"),w=p.store,y=[];for(let e of m)y.push(w.put(e));for(let{chunkKey:e,encryptedChunk:t}of h)y.push(w.put({...t,key:e,timestamp:c}));for(let e of f)y.push(w.delete(e));await Promise.all(y),await p.done;let b=Date.now()-a;this.debug&&b>200&&console.debug(`setItem for key ${e} took ${b}ms`)}catch(e){if(e instanceof h)throw console.error("Worker port is not initialized:",e),e;if(e instanceof d)throw console.error("Database error in setItem:",e),e;if(e instanceof m)throw console.error("Encryption error in setItem:",e),e;if(e instanceof l)throw console.error("IDBCache error in setItem:",e),e;throw console.error("Unexpected error in setItem:",e),new l("An unexpected error occurred during setItem.")}}async removeItem(e){try{let t=await this.dbReadyPromise,r=await K(`${this.cacheKey}:${e}`),n=await A(t,this.storeName,r),o=t.transaction(this.storeName,"readwrite"),a=o.store,i=n.map(e=>a.delete(e));await Promise.all(i),await o.done}catch(e){if(console.error("Error in removeItem:",e),e instanceof d||e instanceof l)throw e;throw new d("Failed to remove item from the cache.")}}async count(){try{let e=(await this.dbReadyPromise).transaction(this.storeName,"readonly"),t=e.store,r=await t.count();return await e.done,this.debug&&console.debug(`Total entries in cache: ${r}`),r}catch(e){if(console.error("Error in count():",e),e instanceof d)throw e;throw new d("Failed to count items in the cache.")}}async clear(){try{let e=(await this.dbReadyPromise).transaction(this.storeName,"readwrite"),t=e.store;await t.clear(),await e.done,this.debug&&console.debug("All items have been cleared from the cache.")}catch(e){if(console.error("Error in clear:",e),e instanceof d||e instanceof l)throw e;throw new d("Failed to clear the cache.")}}async destroy(e){let{clearData:t=!1}=e||{};try{t&&await this.clear(),void 0!==this.cleanupIntervalId&&clearInterval(this.cleanupIntervalId),this.pendingRequests.forEach((e,t)=>{e.reject(new l("IDBCache instance is being destroyed.")),this.pendingRequests.delete(t)}),this.port&&(this.port.postMessage({type:"destroy"}),this.port.close(),this.port=null),this.worker&&(this.worker.terminate(),this.worker=null),this.workerReadyPromise=null,this.debug&&console.debug("IDBCache instance has been destroyed.")}catch(e){if(console.error("Error in destroy:",e),e instanceof l)throw e;throw new l("Failed to destroy the cache instance.")}}constructor(e){q(this,"dbReadyPromise",void 0),q(this,"storeName",void 0),q(this,"worker",null),q(this,"port",null),q(this,"pendingRequests",void 0),q(this,"workerReadyPromise",null),q(this,"gcTime",void 0),q(this,"cleanupIntervalId",void 0),q(this,"cacheKey",void 0),q(this,"chunkSize",void 0),q(this,"cleanupInterval",void 0),q(this,"pbkdf2Iterations",void 0),q(this,"cacheBuster",void 0),q(this,"debug",void 0),q(this,"maxChunks",void 0);let{cacheKey:t,cacheBuster:r,debug:n=!1,dbName:o="idb-cache",gcTime:a=6048e5,chunkSize:i=25e3,cleanupInterval:s=6e4,pbkdf2Iterations:c=1e5,maxChunks:l}=e;if(this.storeName="cache",this.cacheKey=t,this.cacheBuster=r,this.debug=n,this.gcTime=a,this.chunkSize=i,this.cleanupInterval=s,this.pbkdf2Iterations=c,this.maxChunks=l,this.pendingRequests=new Map,!window.indexedDB)throw new d("IndexedDB is not supported.");if(!_)throw new u("Web Crypto API not available in this environment");this.dbReadyPromise=G(o,this.storeName,1),this.cleanupIntervalId=window.setInterval(async()=>{try{await this.cleanupCache()}catch(e){console.error("Error during cleanup:",e)}},this.cleanupInterval),this.initWorker(t,r).then(()=>{this.cleanupCache().catch(e=>console.error("Initial cleanup failed:",e)),this.flushBustedCacheItems().catch(e=>console.error("Failed to flush old cache items:",e))}).catch(e=>{console.error("Worker initialization failed:",e)})}}({cacheKey:es,cacheBuster:ec,debug:!0});window.idbCacheInstance=el;let ed=()=>{let e=Number.parseInt(new URLSearchParams(window.location.hash.slice(1)).get("size")??"0",10);return!Number.isNaN(e)&&e>0?1024*e:32768},eu=document.getElementById("root");eu&&c.createRoot(eu).render((0,i.jsx)(s.StrictMode,{children:(0,i.jsx)(()=>{let[e,t]=(0,s.useState)(null),[r,n]=(0,s.useState)(null),[o,a]=(0,s.useState)(null),[c,l]=(0,s.useState)(null),[d,u]=(0,s.useState)(null),[h,m]=(0,s.useState)(null),[f,p]=(0,s.useState)(null),[w,y]=(0,s.useState)(ed()),[g,b]=(0,s.useState)(null);(0,s.useEffect)(()=>{let e=new URLSearchParams(window.location.hash.slice(1));e.set("size",String(Math.round(w/1024))),window.location.hash=`#${e.toString()}`},[w]);let k=(0,s.useRef)(Number.parseInt(localStorage.getItem("keyCounter")||"0")||0),[x,v]=(0,s.useState)(()=>Y(`seed-${k.current}`)),I=(0,s.useCallback)(async()=>{let e=Y(`seed-${k.current}`);localStorage.setItem("keyCounter",String(k.current)),k.current+=1,v(e);let r=performance.now(),n=Array.from({length:1},(t,r)=>(function(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",n=`${e}-${r}`;if(Z[n])return Z[n];let o=X().create(r),a=Math.ceil(e),i=Array(a);for(let e=0;ee;)s=s.slice(0,-1);return Z[n]=s,s})(w,`${e}-${r}`));a(performance.now()-r);let o=performance.now();for(let t=0;t<1;t++)await el.setItem(`item-${e}-${t}`,n[t]);l(performance.now()-o),t(Y(n.join("")))},[w]),j=(0,s.useCallback)(async()=>{let e=[],t=performance.now();for(let t=0;t<1;t++){let r=await el.getItem(`item-${x}-${t}`);e.push(r)}u(performance.now()-t),n(e.filter(e=>e).length>0?Y(e.join("")):null)},[x]),C=(0,s.useCallback)(async()=>{let e=performance.now(),t=await el.count();m(performance.now()-e),b(t)},[]),E=(0,s.useCallback)(async()=>{let e=performance.now();await el.clear(),localStorage.removeItem("keyCounter"),p(performance.now()-e)},[]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(ea,{}),(0,i.jsx)("div",{className:"min-h-screen bg-gray-50 p-8",children:(0,i.jsxs)(ee.G,{as:"div",display:"block",width:"820px",margin:"0 auto",children:[(0,i.jsx)(er.X,{level:"h1",margin:"0 0 small 0",children:"@instructure/idb-cache"}),(0,i.jsxs)("form",{children:[(0,i.jsxs)(et.kC,{direction:"column",gap:"small",children:[(0,i.jsx)(et.kC.Item,{children:(0,i.jsxs)(et.kC,{gap:"medium",justifyItems:"space-between",children:[(0,i.jsx)(et.kC.Item,{width:"48%",children:(0,i.jsxs)(et.kC,{direction:"row",alignItems:"end",margin:"xx-small 0",children:[(0,i.jsx)(et.kC.Item,{shouldGrow:!0,children:(0,i.jsx)(eo.o,{renderLabel:"Cache key:",interaction:"disabled",defaultValue:es})}),(0,i.jsx)(et.kC.Item,{children:(0,i.jsx)(J.z,{"aria-label":"Reset cache key",margin:"0 0 0 xxx-small","data-testid":"reset-cacheKey",onClick:()=>{localStorage.removeItem("cacheKey"),localStorage.removeItem("keyCounter"),window.location.reload()},children:"Reset"})})]})}),(0,i.jsx)(et.kC.Item,{width:"48%",children:(0,i.jsxs)(et.kC,{direction:"row",alignItems:"end",margin:"xx-small 0",children:[(0,i.jsx)(et.kC.Item,{shouldGrow:!0,children:(0,i.jsx)(eo.o,{renderLabel:"Cache buster:",interaction:"disabled",defaultValue:ec})}),(0,i.jsx)(et.kC.Item,{children:(0,i.jsx)(J.z,{"aria-label":"Reset cache buster",margin:"0 0 0 xxx-small","data-testid":"reset-cacheBuster",onClick:()=>{localStorage.removeItem("cacheBuster"),localStorage.removeItem("keyCounter"),window.location.reload()},children:"Reset"})})]})})]})}),(0,i.jsxs)(et.kC,{justifyItems:"space-between",children:[(0,i.jsx)(et.kC.Item,{width:"48%",children:(0,i.jsx)(en.Y,{renderLabel:"Size of data (KB):",onChange:e=>{y(Math.max(1024*Number.parseInt(e.target.value,10),1024))},onIncrement:()=>{y(e=>Math.max(e+1024,1024))},onDecrement:()=>{y(e=>Math.max(e-1024,1024))},isRequired:!0,value:Math.round(w/1024)})}),(0,i.jsx)(et.kC.Item,{width:"48%",children:(0,i.jsx)(en.Y,{renderLabel:"Number of chunks:",interaction:"disabled",value:Math.ceil(w/25e3)})})]})]}),(0,i.jsx)(er.X,{level:"h2",margin:"medium 0 small 0",children:"Tests"}),(0,i.jsx)(ee.G,{as:"div",display:"block",margin:"small none",padding:"medium",background:"primary",shadow:"resting",children:(0,i.jsxs)(et.kC,{direction:"column",children:[(0,i.jsx)(J.z,{"data-testid":"set-item-button",color:"primary",onClick:I,children:"setItem"}),(0,i.jsx)(ee.G,{padding:"medium 0 0 0",children:(0,i.jsxs)(et.kC,{children:[(0,i.jsx)(et.kC.Item,{size:"33.3%",children:(0,i.jsx)(Q.j,{renderLabel:"Generate Test Data","data-testid":"generate-time",renderValue:null!==o?`${Math.round(o)} ms`:(0,i.jsx)(ei,{})})}),(0,i.jsx)(et.kC.Item,{shouldGrow:!0,children:(0,i.jsx)(Q.j,{renderLabel:"setItem","data-testid":"set-time",renderValue:null!==c?`${Math.round(c)} ms`:(0,i.jsx)(ei,{})})}),(0,i.jsx)(et.kC.Item,{size:"33.3%",children:(0,i.jsx)(Q.j,{"data-testid":"hash1",renderLabel:"Hash",renderValue:e||(0,i.jsx)(ei,{})})})]})})]})}),(0,i.jsx)(ee.G,{as:"div",display:"block",margin:"small none",padding:"medium",background:"primary",shadow:"resting",children:(0,i.jsxs)(et.kC,{direction:"column",children:[(0,i.jsx)(J.z,{"data-testid":"get-item-button",color:"primary",onClick:j,children:"getItem"}),(0,i.jsx)(ee.G,{padding:"medium 0 0 0",children:(0,i.jsxs)(et.kC,{children:[(0,i.jsx)(et.kC.Item,{size:"33.3%",children:"\xa0"}),(0,i.jsx)(et.kC.Item,{shouldGrow:!0,children:(0,i.jsx)(Q.j,{renderLabel:"getItem","data-testid":"get-time",renderValue:null!==d?`${Math.round(d)} ms`:(0,i.jsx)(ei,{})})}),(0,i.jsx)(et.kC.Item,{size:"33.3%",children:(0,i.jsx)(Q.j,{renderLabel:"Hash","data-testid":"hash2",renderValue:r||(0,i.jsx)(ei,{})})})]})})]})}),(0,i.jsx)(ee.G,{as:"div",display:"block",margin:"small none",padding:"medium",background:"primary",shadow:"resting",children:(0,i.jsxs)(et.kC,{direction:"column",children:[(0,i.jsx)(J.z,{"data-testid":"count-button",color:"primary",onClick:C,children:"count"}),(0,i.jsx)(ee.G,{padding:"medium 0 0 0",children:(0,i.jsxs)(et.kC,{children:[(0,i.jsx)(et.kC.Item,{size:"33.3%",children:"\xa0"}),(0,i.jsx)(et.kC.Item,{shouldGrow:!0,children:(0,i.jsx)(Q.j,{"data-testid":"count-time",renderLabel:"count",renderValue:null!==h?`${Math.round(h)} ms`:(0,i.jsx)(ei,{})})}),(0,i.jsx)(et.kC.Item,{size:"33.3%",children:(0,i.jsx)(Q.j,{renderLabel:"Chunks","data-testid":"count-value",renderValue:"number"==typeof g?g:(0,i.jsx)(ei,{})})})]})})]})}),(0,i.jsx)(ee.G,{as:"div",display:"block",margin:"small 0 0 0",padding:"medium",background:"primary",shadow:"resting",children:(0,i.jsxs)(et.kC,{direction:"column",children:[(0,i.jsx)(J.z,{"data-testid":"clear-button",color:"primary",onClick:E,children:"clear"}),(0,i.jsx)(ee.G,{padding:"medium 0 0 0",children:(0,i.jsxs)(et.kC,{children:[(0,i.jsx)(et.kC.Item,{size:"33.3%",children:"\xa0"}),(0,i.jsx)(et.kC.Item,{shouldGrow:!0,children:(0,i.jsx)(Q.j,{renderLabel:"clear","data-testid":"clear-time",renderValue:null!==f?`${Math.round(f)} ms`:(0,i.jsx)(ei,{})})}),(0,i.jsx)(et.kC.Item,{size:"33.3%",children:"\xa0"})]})})]})})]})]})})]})},{})}))}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var a=t[n]={exports:{}};return e[n](a,a.exports,r),a.exports}r.m=e,r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},(()=>{var e,t=Object.getPrototypeOf?function(e){return Object.getPrototypeOf(e)}:function(e){return e.__proto__};r.t=function(n,o){if(1&o&&(n=this(n)),8&o||"object"==typeof n&&n&&(4&o&&n.__esModule||16&o&&"function"==typeof n.then))return n;var a=Object.create(null);r.r(a);var i={};e=e||[null,t({}),t([]),t(t)];for(var s=2&o&&n;"object"==typeof s&&!~e.indexOf(s);s=t(s))Object.getOwnPropertyNames(s).forEach(function(e){i[e]=function(){return n[e]}});return i.default=function(){return n},r.d(a,i),a}})(),r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e=[];r.O=function(t,n,o,a){if(n){a=a||0;for(var i=e.length;i>0&&e[i-1][2]>a;i--)e[i]=e[i-1];e[i]=[n,o,a];return}for(var s=1/0,i=0;i=a)&&Object.keys(r.O).every(function(e){return r.O[e](n[l])})?n.splice(l--,1):(c=!1,a{var e={980:0};r.O.j=function(t){return 0===e[t]};var t=function(t,n){var o=n[0],a=n[1],i=n[2],s,c,l=0;if(o.some(function(t){return 0!==e[t]})){for(s in a)r.o(a,s)&&(r.m[s]=a[s]);if(i)var d=i(r)}for(t&&t(n);l