@npora/request 1.18.0 → 1.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,6 +17,7 @@ has zero runtime dependencies.
17
17
  | --- | --- |
18
18
  | Send the first request | [Quick start](#quick-start) |
19
19
  | Build a client for an application | [Common workflows](docs/workflows.md) |
20
+ | Refresh authentication tokens | [Authentication workflow](docs/workflows.md#refresh-authentication-tokens) |
20
21
  | Find a client or response API | [API reference](docs/api.md) |
21
22
  | Configure URLs, bodies, timeouts, or parsing | [Configuration reference](docs/configuration.md) |
22
23
  | Add retry, cache, authentication, or observability | [Plugins](#plugins) |
@@ -222,6 +223,11 @@ the stream is consumed. `itemSchema` validates and may transform each item
222
223
  immediately before it is yielded, without buffering the rest of the stream.
223
224
  Failures expose the item index and NDJSON line or SSE event metadata.
224
225
 
226
+ Run `pnpm example:streaming` from this repository for a self-contained local
227
+ demonstration of SSE, validated NDJSON, early termination, cancellation, and
228
+ schema errors. See [streaming workflows](docs/workflows.md#consume-streaming-responses)
229
+ for consumption and error-handling contracts.
230
+
225
231
  Native `FormData`, `Blob`, `ArrayBuffer`, and `ReadableStream` request bodies
226
232
  also work when created by another same-origin window or iframe. Detection does
227
233
  not lock streams, and retry safety and request-size limits remain active.
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./RequestError-B0HIY1zK.js";import{n,r,t as i}from"./isBinaryBody-i4r46MoJ.js";import{t as a}from"./isPromiseLike-BuAv3bAe.js";import{t as o}from"./waitForSignal-iy_PYkkb.js";import{t as s}from"./resolveExtensionConfig-QAFHZVte.js";function normalizeCacheTtl(e,n){let r=e??3e4;if(r!==1/0&&(!Number.isFinite(r)||r<0))throw new t(`Cache ttl must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return r}function normalizeCacheStatus(e,n){let r=e??200;if(!Number.isInteger(r)||r<200||r>599)throw new t(`Cache status must be an integer between 200 and 599`,{code:`CONFIG_ERROR`,config:n});return r}function normalizeStaleIfError(e,n){if(e!==void 0){if(e!==1/0&&(!Number.isFinite(e)||e<0))throw new t(`Cache staleIfError must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return e}}function normalizeStaleWhileRevalidate(e,n){if(e!==void 0){if(e!==1/0&&(!Number.isFinite(e)||e<0))throw new t(`Cache staleWhileRevalidate must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return e}}function normalizeCacheTags(e,n){if(e===void 0)return[];if(typeof e!=`string`&&!Array.isArray(e))throw new t(`Cache tags must be an array of strings`,{code:`CONFIG_ERROR`,config:n});let r=typeof e==`string`?[e]:e;if(r.length>32)throw new t(`Cache tags cannot contain more than 32 values`,{code:`CONFIG_ERROR`,config:n});let i=new Set;for(let e of r){if(typeof e!=`string`||e.length===0||e.length>128)throw new t(`Cache tags must contain 1 to 128 characters`,{code:`CONFIG_ERROR`,config:n});i.add(e)}return[...i]}function isExpired(e){return e!==1/0&&(Number.isNaN(e)||Date.now()>=e)}var MemoryCacheStore=class{constructor(e={}){this.entries=new Map,this.maxEntries=normalizeMaxEntries(e.maxEntries)}get(e){let t=this.entries.get(e);if(t)return this.newestKey!==e&&(this.entries.delete(e),this.entries.set(e,t),this.newestKey=e),t}set(e,t){if(this.maxEntries!==0){for(this.entries.delete(e);this.entries.size>=this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e)}this.entries.set(e,t),this.newestKey=e}}delete(e){this.entries.delete(e),this.newestKey===e&&(this.newestKey=void 0)}invalidateTags(e){let t=new Set(e),n=0;for(let[e,r]of this.entries)r.tags?.some(e=>t.has(e))&&(this.entries.delete(e),n+=1,this.newestKey===e&&(this.newestKey=void 0));return n}clear(){this.entries.clear(),this.newestKey=void 0}},WebStorageCacheStore=class{constructor(e,t={}){this.storage=e,this.prefix=createWebStoragePrefix(t.namespace),this.maxEntries=normalizeMaxEntries(t.maxEntries)}get(e){if(this.maxEntries===0)return;let t=this.prefix+e,n=this.read(t);if(n){try{this.storage.setItem(t,serializeWebStorageEntry(n.entry,Date.now()))}catch{}return n.entry}}set(e,t){if(this.maxEntries===0)return;let n=this.prefix+e,r=this.keys(),i=r.includes(n),a=Math.max(0,r.length-this.maxEntries+ +!i);if(a>0){let e=r.map(e=>({key:e,accessedAt:this.read(e)?.accessedAt??0})).filter(e=>e.key!==n).sort((e,t)=>e.accessedAt-t.accessedAt);for(let t of e.slice(0,a))this.storage.removeItem(t.key)}this.storage.setItem(n,serializeWebStorageEntry(t,Date.now()))}delete(e){this.storage.removeItem(this.prefix+e)}invalidateTags(e){let t=new Set(e),n=0;for(let e of this.keys())this.read(e)?.entry.tags?.some(e=>t.has(e))&&(this.storage.removeItem(e),n+=1);return n}clear(){for(let e of this.keys())this.storage.removeItem(e)}keys(){let e=[];for(let t=0;t<this.storage.length;t+=1){let n=this.storage.key(t);n?.startsWith(this.prefix)&&e.push(n)}return e}read(e){let t=this.storage.getItem(e);if(t!==null)try{return parseWebStorageEntry(t)}catch{this.storage.removeItem(e);return}}};function normalizeMaxEntries(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function createWebStoragePrefix(e=`default`){if(typeof e!=`string`||e.length===0||e.length>128)throw new t(`Web storage cache namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return`@npora/request:${encodeURIComponent(e)}:`}function serializeWebStorageEntry(e,t){return JSON.stringify({version:1,data:e.data,expiresAt:e.expiresAt===1/0?null:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags,accessedAt:t})}function parseWebStorageEntry(e){let t=JSON.parse(e),n=t.expiresAt===null?1/0:t.expiresAt;if(t.version!==1||n!==1/0&&(typeof n!=`number`||!Number.isFinite(n))||typeof t.status!=`number`||!Number.isInteger(t.status)||t.status<200||t.status>599||typeof t.statusText!=`string`||!Array.isArray(t.headers)||typeof t.accessedAt!=`number`||!Number.isFinite(t.accessedAt))throw TypeError(`Invalid web storage cache entry`);let r=t.tags===void 0?void 0:normalizeCacheTags(t.tags);return{entry:{data:t.data,expiresAt:n,status:t.status,statusText:t.statusText,headers:[...new Headers(t.headers).entries()],tags:r&&r.length>0?r:void 0},accessedAt:t.accessedAt}}const c=[];function createCacheKey(e,t,n,r,i){if(t.key)return t.key;let a=e.method??`GET`,o=String(e.url),s=e.responseType??`auto`,l=!e.headers&&!e.query&&!e.searchParams;if(l&&i.key!==void 0&&i.method===a&&i.baseURL===e.baseURL&&i.url===o&&i.responseType===s)return i.key;let u=JSON.stringify({method:a,baseURL:e.baseURL,url:o,query:l?c:normalizeQuery(e.searchParams??e.query),responseType:s,headers:e.headers?normalizeCacheHeaders(new Headers(e.headers),n):r});return l&&(i.method=a,i.baseURL=e.baseURL,i.url=o,i.responseType=s,i.key=u),u}function normalizeCacheHeaders(e,t){let n=[];e?.forEach((e,t)=>{isRequestCacheControlHeader$1(t)||n.push([t,e])});for(let r of t)!isRequestCacheControlHeader$1(r)&&!e?.has(r)&&n.push([r,null]);return n.sort(([e],[t])=>e.localeCompare(t))}function isRequestCacheControlHeader$1(e){return e===`cache-control`||e===`pragma`}function normalizeVaryHeaders(e){return[...new Set(e.map(e=>e.toLowerCase()))]}function normalizeQuery(e){if(!e)return c;if(r(e))return[...e.entries()];let t=[];for(let n of Object.keys(e).sort())appendQueryValue(t,n,e[n]);return t}function appendQueryValue(e,t,n){if(n!==void 0){if(n===null){e.push([t,``]);return}if(Array.isArray(n)){for(let r of n)appendQueryValue(e,t,r);return}e.push([t,String(n)])}}const l={hit:`hits`,miss:`misses`,bypass:`bypasses`,invalidated:`invalidations`,"invalidation-error":`invalidationErrors`,deduplicated:`deduplicated`,revalidated:`revalidations`,"stale-if-error":`staleIfError`,"stale-while-revalidate":`staleWhileRevalidate`,"background-refresh":`backgroundRefreshes`,"background-refresh-success":`backgroundRefreshSuccesses`,"background-refresh-error":`backgroundRefreshErrors`};function createCacheStats(){return{hits:0,misses:0,bypasses:0,invalidations:0,invalidationErrors:0,deduplicated:0,revalidations:0,staleIfError:0,staleWhileRevalidate:0,backgroundRefreshes:0,backgroundRefreshSuccesses:0,backgroundRefreshErrors:0}}function resetCacheStats(e){Object.assign(e,createCacheStats())}function createCacheEventRecorder(e,t){return n=>{if(incrementCacheStat(e,n),t)try{let e=t({type:n,timestamp:Date.now()});a(e)&&Promise.resolve(e).catch(ignoreCacheEventError)}catch{}}}function incrementCacheStat(e,t){let n=l[t];e[n]=Math.min(2**53-1,e[n]+1)}function ignoreCacheEventError(){}const u=[`GET`,`HEAD`],d=[`authorization`,`cookie`,`accept`,`accept-language`];function createCacheState(e){let t=e.store??new MemoryCacheStore({maxEntries:e.maxEntries}),n=new WeakSet,r=new WeakMap,i=new WeakMap,a=new WeakMap,o=new WeakMap,s=new WeakMap,c=new WeakMap,l=new WeakSet,f=new WeakSet,p=new WeakMap,m=new WeakMap,h=new WeakSet,g=new WeakSet,_=new Map,v=new Map,y=new WeakSet,b=new Map,x=new Map,S=new Map,C=new Map,w=createCacheStats(),T=createCacheEventRecorder(w,e.onEvent),E=new Set(e.methods??u),D=normalizeVaryHeaders(e.varyHeaders??d);return{store:t,cacheHits:n,leaders:r,requestGenerations:i,automaticInvalidations:a,unsharedGenerations:o,completedRecords:s,revalidations:c,forcedRevalidations:l,noStoreRequests:f,staleFallbacks:p,refreshLeases:m,cacheFallbacks:h,uncacheableLeaders:g,inFlight:_,rawInFlight:v,rawLeaders:y,backgroundRefreshes:b,keyGenerations:x,keyOperations:S,tagInvalidations:C,stats:w,recordEvent:T,generation:0,methods:E,varyHeaders:D,emptyHeaderValues:normalizeCacheHeaders(void 0,D),keyMemo:{}}}const f={persist:!1,ttl:0};function resolveRequestCachePolicy(e){let t=new Headers(e.headers),n=t.get(`cache-control`),r=!1;if(n)for(let e of n.split(`,`)){let t=e.trim(),n=t.indexOf(`=`),i=(n===-1?t:t.slice(0,n)).trim().toLowerCase();if(i===`no-store`)return`no-store`;if(i===`no-cache`){r=!0;continue}if(i===`max-age`&&n!==-1){let e=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());e&&Number(e[1]??e[2])===0&&(r=!0)}}else t.get(`pragma`)?.split(`,`).some(e=>e.trim().toLowerCase()===`no-cache`)&&(r=!0);return r?`revalidate`:`default`}function resolveResponseCachePolicy(e,t,n,r){let i=e.headers.get(`cache-control`),a,o=!1;if(i)for(let e of i.split(`,`)){let t=e.trim(),n=t.indexOf(`=`),r=(n===-1?t:t.slice(0,n)).trim().toLowerCase();if(r===`no-store`)return f;if(r===`no-cache`){o=!0;continue}if(r!==`max-age`)continue;if(a!==void 0)return f;let i=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());if(!i)return f;a=Number(i[1]??i[2])}if(e.headers.get(`vary`)?.split(`,`).some(e=>{let t=e.trim().toLowerCase();return t===`*`||isRequestCacheControlHeader(t)})||t<=0||a!==void 0&&!Number.isSafeInteger(a))return f;let s=o?0:a===void 0?t:Math.min(t,Math.max(0,(a-parseAge(e.headers.get(`age`)))*1e3));return{ttl:s,persist:s>0||hasResponseValidator$1(e.headers)||resolveStaleIfErrorWindow(e.headers,n)>0||!o&&resolveStaleWhileRevalidateWindow(e.headers,r)>0}}function resolveStaleIfErrorWindow(e,t){return resolveWindow(e,t,`stale-if-error`)}function resolveStaleWhileRevalidateWindow(e,t){return resolveWindow(e,t,`stale-while-revalidate`)}function hasCacheControlDirective(e,t){return e.get(`cache-control`)?.split(`,`).some(e=>{let n=e.indexOf(`=`);return(n===-1?e:e.slice(0,n)).trim().toLowerCase()===t})??!1}function resolveWindow(e,t,n){let r=parseCacheDeltaSeconds(e.get(`cache-control`),n);return t===void 0?r??0:r===void 0?t:Math.min(t,r)}function parseCacheDeltaSeconds(e,t){let n;if(!e)return;for(let r of e.split(`,`)){let e=r.trim(),i=e.indexOf(`=`);if(i===-1||e.slice(0,i).trim().toLowerCase()!==t)continue;if(n!==void 0)return;let a=/^(?:"(\d+)"|(\d+))$/.exec(e.slice(i+1).trim());if(!a)return;n=Number(a[1]??a[2])}if(n===void 0||!Number.isSafeInteger(n))return;let r=n*1e3;return Number.isSafeInteger(r)?r:void 0}function parseAge(e){if(!e||!/^\d+$/.test(e.trim()))return 0;let t=Number(e);return Number.isSafeInteger(t)?t:0}function hasResponseValidator$1(e){return e.has(`etag`)||e.has(`last-modified`)}function isRequestCacheControlHeader(e){return e===`cache-control`||e===`pragma`}function isCacheableRequest(e,t,n){return t.has(e.method??`GET`)&&(!hasRequestBody(e)||!!n.key)&&(!e.parseJson||!!n.key)&&(!e.querySerializer||!!n.key)&&e.responseType!==`stream`&&e.responseType!==`sse`&&e.responseType!==`ndjson`&&e.responseType!==`bytes`&&e.responseType!==`formData`&&e.fetchOptions?.mode!==`no-cors`&&e.fetchOptions?.redirect!==`manual`}function hasRequestBody(e){return e.body!=null||e.json!==void 0||e.form!=null||e.formData!=null}function isAsyncIterable(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}function isSchemaValidationFailure(t){return e(t)&&t.code===`SCHEMA_ERROR`}function canUseStaleIfError(e,t,n,r){try{if(n&&!e.raw||hasConditionalRequestHeaders(t))return!1;let i=resolveStaleIfErrorWindow(new Headers(e.headers),r);return i>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+i}catch{return!1}}function canUseStaleWhileRevalidate(e,t,n,r){try{if(n&&!e.raw)return!1;let i=new Headers(e.headers);if(hasConditionalRequestHeaders(t)||hasCacheControlDirective(i,`no-cache`)||hasCacheControlDirective(i,`must-revalidate`))return!1;let a=resolveStaleWhileRevalidateWindow(i,r);return a>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+a}catch{return!1}}function startBackgroundRefresh(e,t,n,r,i,a){if(t.has(n))return;let o=new AbortController,s={...r,signal:o.signal};t.set(n,o),a(`background-refresh`),Promise.resolve().then(()=>e.dispatch(s,{background:!0,preserveRaw:i})).then(()=>a(`background-refresh-success`),()=>a(`background-refresh-error`)).finally(()=>{t.get(n)===o&&t.delete(n)})}function abortBackgroundRefreshes(e){for(let t of e.values())t.abort(`Cache background refresh stopped`);e.clear()}function isEligibleStaleIfError(t){return e(t)&&(t.code===`NETWORK_ERROR`||t.code===`TIMEOUT_ERROR`||t.code===`HTTP_ERROR`&&t.status!==void 0&&t.status>=500&&t.status<600)}function canRevalidateCacheEntry(e,t,n){try{return n&&!e.raw||hasConditionalRequestHeaders(t)?!1:hasResponseValidator(new Headers(e.headers))}catch{return!1}}function prepareConditionalRevalidation(e,t){let n=new Headers(t.headers),r=n.get(`etag`),i=n.get(`last-modified`);if(!r&&!i)return!1;let a=new Headers(e.headers);r&&a.set(`if-none-match`,r),i&&a.set(`if-modified-since`,i);let o=e.validateStatus,s=e.throwHttpErrors;return e.headers=a,e.throwHttpErrors=void 0,e.validateStatus=e=>e===304||(o?o(e):s===!1||e>=200&&e<300),!0}function hasResponseValidator(e){return e.has(`etag`)||e.has(`last-modified`)}function hasConditionalRequestHeaders(e){let t=new Headers(e.headers);return t.has(`if-none-match`)||t.has(`if-modified-since`)||t.has(`range`)}function createCacheEntry(e,t,n,r){return{data:cloneCacheValue(e.data),expiresAt:t,status:e.status,statusText:e.statusText,headers:[...e.headers.entries()],tags:r?[...r]:void 0,raw:n?cloneResponse(e.raw):void 0}}function createCachedResponse(e,t){return{data:cloneCacheValue(e.data),status:e.status,statusText:e.statusText,headers:new Headers(e.headers),config:t,raw:cloneRawResponse(e)}}function restoreCacheEntry(e,t){try{return createCachedResponse(e,t)}catch{return}}function createRevalidatedResponse(e,t,n){let r=new Headers(e.headers);return t.headers.forEach((e,t)=>{r.set(t,e)}),createCachedResponse({...e,headers:[...r.entries()]},n)}function cloneRawResponse(e){if(e.raw){let t=cloneResponse(e.raw);if(t)return new Response(t.body,{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})}function cloneResponse(e){try{return e.clone()}catch{return}}function cloneCacheValue(e){if(typeof e!=`object`||!e||typeof structuredClone!=`function`)return e;try{return structuredClone(e)}catch{return e}}function createCacheOperations(e){let{keyOperations:t,tagInvalidations:n,recordEvent:r,keyGenerations:i,inFlight:o,rawInFlight:s,backgroundRefreshes:c}=e;function trackKeyOperation(e,n,i,a){let o=Promise.resolve(n),s;return s=o.then(()=>i&&r(i),()=>a&&r(a)).finally(()=>{t.get(e)===s&&t.delete(e)}),t.set(e,s),o}function runKeyOperation(e,n,i=[],o,s){let c=new Set(i),l=t.get(e);if(l&&c.add(l),c.size>0)return trackKeyOperation(e,Promise.all(c).then(n),o,s);let u;try{u=n()}catch(e){throw s&&r(s),e}return a(u)?trackKeyOperation(e,u,o,s):(o&&r(o),u)}function invalidateKeyState(e,t){i.delete(e),o.delete(e),s.delete(e);let n=c.get(e);n&&(c.delete(e),n.abort(t))}function trackTagInvalidation(e,t){let i=Promise.resolve(t),a;a=i.then(()=>r(`invalidated`),()=>r(`invalidation-error`)).finally(()=>{for(let t of e)n.get(t)===a&&n.delete(t)});for(let t of e)n.set(t,a);return i}return{runKeyOperation,invalidateKeyState,trackTagInvalidation}}function createCacheMutations(e){let{store:n,keyGenerations:r,inFlight:i,rawInFlight:o,backgroundRefreshes:c,keyOperations:l,tagInvalidations:u,recordEvent:d,varyHeaders:f,emptyHeaderValues:p,keyMemo:m,stats:h}=e,{runKeyOperation:g,invalidateKeyState:_,trackTagInvalidation:v}=createCacheOperations(e);return{clear(){return e.generation+=1,i.clear(),o.clear(),r.clear(),abortBackgroundRefreshes(c),n.clear()},delete(e){let t=createCacheKey(e,s(e,`cache`)??{},f,p,m);return _(t,`Cache entry invalidated`),g(t,()=>n.delete(t),[],`invalidated`,`invalidation-error`)},set(e,t,r={}){let i=s(e,`cache`)??{},a=createCacheKey(e,i,f,p,m),o=normalizeCacheTtl(r.ttl??i.ttl,e),c=normalizeCacheStatus(r.status,e),l=normalizeCacheTags(r.tags??i.tags,e),d={data:cloneCacheValue(t),expiresAt:o===1/0?o:Date.now()+o,status:c,statusText:r.statusText??(c===200?`OK`:``),headers:[...new Headers(r.headers).entries()],tags:l.length>0?l:void 0},h=l.map(e=>u.get(e)).filter(e=>!!e);return _(a,`Cache entry replaced`),g(a,()=>n.set(a,d),h)},update(e,t){let r=createCacheKey(e,s(e,`cache`)??{},f,p,m);return _(r,`Cache entry updated`),g(r,()=>{let updateEntry=e=>{if(!e)return!1;let i=t(cloneCacheValue(e.data));if(i===void 0){let e=n.delete(r);return!a(e)||Promise.resolve(e).then(()=>!0)}let o=n.set(r,{...e,data:cloneCacheValue(i),raw:void 0});return!a(o)||Promise.resolve(o).then(()=>!0)},e=n.get(r);return a(e)?Promise.resolve(e).then(updateEntry):updateEntry(e)},u.values())},invalidateTags(e){let i=normalizeCacheTags(e);if(i.length===0)throw new t(`Cache tag invalidation requires at least one tag`,{code:`CONFIG_ERROR`});let o=n.invalidateTags;if(!o)throw new t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`});for(let[e,t]of r)i.some(e=>t.tags.has(e))&&_(e,`Cache tags invalidated`);let s=new Set(i.map(e=>u.get(e)).filter(e=>!!e));for(let e of l.values())s.add(e);if(s.size>0)return v(i,Promise.all(s).then(()=>o.call(n,i)));let c;try{c=o.call(n,i)}catch(e){throw d(`invalidation-error`),e}return a(c)?v(i,c):(d(`invalidated`),c)},getStats(){return{...h}},resetStats(){resetCacheStats(h)}}}function acquireCacheGeneration(e,t,n,r){let i=n.get(t);i||(i={activeRequests:0,tags:new Set},n.set(t,i)),i.activeRequests+=1;for(let e of r)i.tags.add(e);return{global:e,key:t,token:i}}function isCurrentCacheGeneration(e,t,n){return e!==void 0&&e.global===t&&n.get(e.key)===e.token}function releaseCacheGeneration(e,t){--e.token.activeRequests,e.token.activeRequests===0&&t.get(e.key)===e.token&&t.delete(e.key)}function createInFlightRequest(e,t,n){return{owner:e,key:t,generation:n}}function getInFlightPromise(e){if(e.promise)return e.promise;let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.catch(()=>{}),e.promise=r,e.resolve=t,e.reject=n,r}function readStore(e,t){try{let n=e.get(t);return a(n)?Promise.resolve(n).catch(()=>void 0):n}catch{return}}function writeStore(e,t,n){try{let r=e.set(t,n);if(a(r))return Promise.resolve(r).catch(ignoreStoreError)}catch{}}function deleteStore(e,t){try{let n=e.delete(t);if(a(n))return Promise.resolve(n).catch(ignoreStoreError)}catch{}}function ignoreStoreError(){}function waitForSharedRecord(e,t){let n=t.signal;return n?n.aborted?Promise.reject(createSharedAbortError(n.reason,t)):new Promise((r,i)=>{let a=!1,cleanup=()=>{try{n.removeEventListener(`abort`,onAbort)}catch{}},resolveOnce=e=>{a||(a=!0,cleanup(),r(e))},rejectOnce=e=>{a||(a=!0,cleanup(),i(e))},onAbort=()=>{rejectOnce(createSharedAbortError(n.reason,t))};try{n.addEventListener(`abort`,onAbort,{once:!0})}catch(e){rejectOnce(e);return}n.aborted&&onAbort(),!a&&e.then(resolveOnce,e=>{rejectOnce(cloneSharedError(e,t))})}):e.catch(e=>{throw cloneSharedError(e,t)})}function createSharedAbortError(e,n){return new t(`Request aborted while waiting for shared response`,{code:`ABORT_ERROR`,config:n,cause:e})}function cloneSharedError(n,r){return e(n)?new t(n.message,{code:n.code,status:n.status,data:n.data,response:n.response,config:r,cause:n}):n}function createCacheResponseHandler(e){let{cacheFallbacks:t,recordEvent:n,cacheHits:r,leaders:i,uncacheableLeaders:c,methods:l,noStoreRequests:u,revalidations:d,varyHeaders:f,emptyHeaderValues:p,keyMemo:m,unsharedGenerations:h,requestGenerations:g,keyGenerations:_,completedRecords:v,store:y}=e;return b=>{if(t.has(b)&&b.fallbackResponse){n(`stale-if-error`),r.add(b),b.cacheHit=!0,i.get(b)?.owner===b&&c.add(b);return}if(r.has(b))return;let x=s(b.config,`cache`);if(!x?.enabled||!b.response||!isCacheableRequest(b.config,l,x)||u.has(b))return;let S=d.get(b);if(b.response.raw.type===`opaque`||b.response.raw.type===`opaqueredirect`){i.get(b)?.owner===b&&c.add(b);return}S&&b.response.status===304&&(n(`revalidated`),b.response=createRevalidatedResponse(S,b.response,b.config));let C=i.get(b),w=C?.key??createCacheKey(b.config,x,f,p,m),T=isCurrentCacheGeneration(C?.generation??h.get(b)??g.get(b),e.generation,_),E=(C?.generation??g.get(b))?.token.tags,D=E&&E.size>0?[...E]:S?.tags;if(isAsyncIterable(b.response.data)){if(c.add(b),!T)return;let e=deleteStore(y,w);return a(e)?b.config.signal?o(()=>e,b.config):e:void 0}let O=normalizeCacheTtl(x.ttl,b.config),k=normalizeStaleIfError(x.staleIfError,b.config),A=normalizeStaleWhileRevalidate(x.staleWhileRevalidate,b.config),j=resolveResponseCachePolicy(b.response,O,k,A),M=j.ttl;if(!j.persist){let e=T?deleteStore(y,w):void 0,t=a(e),n=C;return n?.owner===b&&(n.promise!==void 0||t)?v.set(b,createCacheEntry(b.response,Date.now()+Math.max(0,M),b.preserveRaw,D)):n?.owner===b&&c.add(b),t?b.config.signal?o(()=>e,b.config):e:void 0}let N=createCacheEntry(b.response,Date.now()+M,b.preserveRaw,D);if(v.set(b,N),!T||C?.rawDemanded)return;let P=writeStore(y,w,N);if(a(P))return b.config.signal?o(()=>P,b.config):P}}function createCacheMissHandler(e,t,n,r){let{keyGenerations:i,recordEvent:a,unsharedGenerations:s,rawInFlight:c,inFlight:l,cacheHits:u,store:d,refreshLeases:f,forcedRevalidations:p,rawLeaders:m,leaders:h,revalidations:g}=e,{ownedLeaders:_,ownedRefreshLeases:v}=t;function prepareCacheMiss(y,b,x,S,C){if(!t.active||!isCurrentCacheGeneration(S,e.generation,i))return;if(!(b.dedupe??n.dedupe??!0)){y.background||a(`miss`),s.set(y,S);return}let w=y.preserveRaw?c.get(x):l.get(x)??c.get(x);if(w)return a(`deduplicated`),waitForSharedRecord(getInFlightPromise(w),y.config).then(e=>{e&&(y.response=createCachedResponse(e,y.config),u.add(y),y.cacheHit=!0)});let T=d.acquireRefreshLease;if(T&&!f.has(y)){let e;try{let t=T.call(d,x,y.config.signal);e=y.config.signal?o(()=>t,y.config):t}catch{return f.set(y,{contended:!1,release(){}}),r(y,b,x,C,S)}return e.then(e=>(f.set(y,e),v.add(e),e.contended&&(p.delete(y),a(`deduplicated`)),Promise.resolve(readStore(d,x)).then(e=>r(y,b,x,e,S))),e=>{if(y.config.signal?.aborted)throw e;return f.set(y,{contended:!1,release(){}}),r(y,b,x,C,S)})}if(y.preserveRaw){let e=l.get(x);e&&(e.rawDemanded=!0)}let E=createInFlightRequest(y,x,S);y.preserveRaw?(c.set(x,E),m.add(y)):l.set(x,E),h.set(y,E),_.add(y),y.background||a(`miss`),C&&prepareConditionalRevalidation(y.config,C)&&g.set(y,C)}return prepareCacheMiss}function createCacheRecordHandler(e,t,n,r){let{keyGenerations:i,forcedRevalidations:s,recordEvent:c,cacheHits:l,backgroundRefreshes:u,staleFallbacks:d,store:f}=e;function handleCacheRecord(p,m,h,g,_){if(!(!t.active||!isCurrentCacheGeneration(_,e.generation,i))){if(g){let e=!isExpired(g.expiresAt),t=s.has(p);if(e&&!t){if(p.preserveRaw&&!g.raw)return r(p,m,h,_);let e=restoreCacheEntry(g,p.config);if(e){c(`hit`),p.response=e,l.add(p),p.cacheHit=!0;return}}if(!p.background&&!t&&canUseStaleWhileRevalidate(g,p.config,p.preserveRaw,normalizeStaleWhileRevalidate(m.staleWhileRevalidate,p.config))){let e=restoreCacheEntry(g,p.config);if(e){c(`stale-while-revalidate`),p.response=e,l.add(p),p.cacheHit=!0,startBackgroundRefresh(n,u,h,p.initialConfig,p.preserveRaw,c);return}}if(!p.background&&canUseStaleIfError(g,p.config,p.preserveRaw,normalizeStaleIfError(m.staleIfError,p.config))&&d.set(p,g),canRevalidateCacheEntry(g,p.config,p.preserveRaw)&&restoreCacheEntry(g,p.config))return r(p,m,h,_,g);if(e&&t||p.background)return r(p,m,h,_);let i=deleteStore(f,h);if(a(i))return(p.config.signal?o(()=>i,p.config):Promise.resolve(i)).then(()=>r(p,m,h,_))}return r(p,m,h,_)}}return handleCacheRecord}function createCacheRequestHandler(e,n,r,i){let{store:c,automaticInvalidations:l,methods:u,recordEvent:d,noStoreRequests:f,forcedRevalidations:p,varyHeaders:m,emptyHeaderValues:h,keyMemo:g,keyGenerations:_,requestGenerations:v,keyOperations:y,tagInvalidations:b}=e,x=createCacheRecordHandler(e,n,r,createCacheMissHandler(e,n,i,(...e)=>x(...e)));return n=>{let r=s(n.config,`cache`);if(!r)return;let i=normalizeCacheTags(r.invalidateTags,n.config);if(i.length>0){if(!c.invalidateTags)throw new t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`,config:n.config});l.set(n,i)}if(!r.enabled||!isCacheableRequest(n.config,u,r))return;normalizeCacheTtl(r.ttl,n.config),normalizeStaleIfError(r.staleIfError,n.config),normalizeStaleWhileRevalidate(r.staleWhileRevalidate,n.config);let S=normalizeCacheTags(r.tags,n.config),C=resolveRequestCachePolicy(n.config);if(C===`no-store`){d(`bypass`),f.add(n);return}(C===`revalidate`||n.background)&&p.add(n);let w=createCacheKey(n.config,r,m,h,g),T=acquireCacheGeneration(e.generation,w,_,S);v.set(n,T);let read=()=>{let t=readStore(c,w);return a(t)?(n.config.signal?o(()=>t,n.config):Promise.resolve(t)).then(t=>{if(isCurrentCacheGeneration(T,e.generation,_))return x(n,r,w,t,T)}):x(n,r,w,t,T)},E=new Set,D=y.get(w);D&&E.add(D);for(let e of S){let t=b.get(e);t&&E.add(t)}if(E.size>0){let e=Promise.all(E).then(()=>{});return n.config.signal?o(()=>e,n.config).then(read):e.then(read)}return read()}}function createCacheInstallation(){return{active:!0,ownedLeaders:new Set,ownedRefreshLeases:new Set}}function createCacheErrorHandler(e){let{staleFallbacks:t,cacheFallbacks:n}=e;return e=>{let r=t.get(e);if(!r||!isEligibleStaleIfError(e.error))return;let i=restoreCacheEntry(r,e.config);i&&(n.add(e),e.fallbackResponse=i)}}function createCacheSettledHandler(e,n,r){let{refreshLeases:i,forcedRevalidations:o,noStoreRequests:s,staleFallbacks:c,cacheFallbacks:l,requestGenerations:u,automaticInvalidations:d,keyGenerations:f,leaders:p,revalidations:m,rawLeaders:h,rawInFlight:g,inFlight:_,uncacheableLeaders:v,completedRecords:y}=e,{ownedLeaders:b,ownedRefreshLeases:x}=n;return e=>{let n=i.get(e);n&&(n.release(),x.delete(n)),i.delete(e),o.delete(e),s.delete(e),c.delete(e),l.delete(e);let S=u.get(e),invalidateAfterSuccess=()=>{let t=d.get(e);if(d.delete(e),!(!t||e.background||e.error||!e.response))try{let e=r.invalidateTags(t);if(a(e))return Promise.resolve(e).then(()=>{}).catch(ignoreCacheEventError)}catch{}};S&&(u.delete(e),releaseCacheGeneration(S,f));let C=p.get(e);if(!C)return invalidateAfterSuccess();p.delete(e),b.delete(e),m.delete(e);let w=C.key,T=h.delete(e)?g:_;if(T.get(w)===C&&T.delete(w),v.delete(e))return C.resolve?.(void 0),invalidateAfterSuccess();let E=y.get(e);return y.delete(e),E&&e.response&&(!e.error||isSchemaValidationFailure(e.error))?(C.resolve?.(E),invalidateAfterSuccess()):(C.reject?.(e.error??new t(`Shared request failed`,{code:`NETWORK_ERROR`,config:e.config})),invalidateAfterSuccess())}}function createCacheCleanup(e,n){let{leaders:r,rawLeaders:i,rawInFlight:a,inFlight:o,keyGenerations:s,backgroundRefreshes:c}=e,{ownedLeaders:l,ownedRefreshLeases:u}=n;return()=>{n.active=!1;for(let e of u)e.release();u.clear();for(let e of l){let n=r.get(e);if(r.delete(e),!n)continue;let s=n.key,c=i.delete(e)?a:o;c.get(s)===n&&c.delete(s),n.reject?.(new t(`Cache plugin removed during shared request`,{code:`ABORT_ERROR`}))}l.clear(),s.clear(),abortBackgroundRefreshes(c)}}const p=`entries`,m=`namespace`;var IndexedDBCacheStore=class{constructor(e,t={}){this.namespace=normalizeIndexedDBName(t.namespace,`namespace`,`default`),this.maxEntries=normalizeIndexedDBMaxEntries(t.maxEntries),this.maxBytes=normalizeIndexedDBMaxBytes(t.maxBytes),this.quotaRecovery=normalizeQuotaRecovery(t.quotaRecovery),this.shouldPersist=normalizeIndexedDBAdmissionPolicy(t.shouldPersist),this.onEvent=normalizeIndexedDBEventObserver(t.onEvent),this.schemaVersion=normalizeIndexedDBSchemaVersion(t.schemaVersion),this.databaseName=normalizeIndexedDBName(t.databaseName,`database name`,`@npora/request-cache`),this.factory=e}async get(e){if(this.maxEntries===0||this.maxBytes===0){await this.delete(e);return}let t=(await this.getDatabase()).transaction(p,`readwrite`),n=waitForTransaction(t),r=t.objectStore(p),i=this.createKey(e),a=await waitForRequest(r.get(i)),o=isFutureIndexedDBRecord(a,this.schemaVersion);if(!isValidIndexedDBRecord(a,this.namespace,i,this.schemaVersion)){a!==void 0&&!o&&r.delete(i),await n,a!==void 0&&!o&&this.emitEvent({type:`eviction`,reason:`malformed`,entries:1,estimatedBytes:readIndexedDBRecordSize(a)});return}return a.accessedAt=Date.now(),a.size=readIndexedDBRecordSize(a),r.put(a),await n,toPortableCacheEntry(a)}async set(e,n){if(this.maxEntries===0||this.maxBytes===0){await this.delete(e);return}let r=await this.getDatabase(),i={...toPortableCacheEntry(n),key:this.createKey(e),namespace:this.namespace,accessedAt:Date.now(),schemaVersion:this.schemaVersion};if(i.size=estimateStructuredCloneSize(i),i.size>this.maxBytes){await this.delete(e),this.emitEvent({type:`rejection`,reason:`oversized`,entries:1,estimatedBytes:i.size});return}let a=!this.shouldPersist||await this.shouldPersist(toPortableCacheEntry(i),i.size);if(typeof a!=`boolean`)throw new t(`IndexedDB cache shouldPersist must return a boolean`,{code:`CONFIG_ERROR`});if(!a){await this.delete(e),this.emitEvent({type:`rejection`,reason:`admission-policy`,entries:1,estimatedBytes:i.size});return}try{await this.writeRecord(r,i)}catch(e){if(!this.quotaRecovery||!isQuotaExceededError(e)||!await this.recoverQuota(r))throw e;await this.writeRecord(r,i)}}async delete(e){let t=(await this.getDatabase()).transaction(p,`readwrite`),n=waitForTransaction(t),r=t.objectStore(p),i=this.createKey(e);isFutureIndexedDBRecord(await waitForRequest(r.get(i)),this.schemaVersion)||r.delete(i),await n}async invalidateTags(e){let t=new Set(e),n=0;return await this.visitNamespace(e=>e.tags?.some(e=>t.has(e))?(n+=1,!0):!1),n}async clear(){await this.visitNamespace(()=>!0)}async getUsage(){let e=(await this.getDatabase()).transaction(p,`readonly`),t=waitForTransaction(e),n=e.objectStore(p).index(m).openCursor(this.namespace),r=0,i=0;return await visitCursor(n,e=>{let t=e.value;isValidIndexedDBRecord(t,this.namespace,void 0,this.schemaVersion)&&(r+=1,i=addSizes(i,readIndexedDBRecordSize(t)))}),await t,{entries:r,estimatedBytes:i,maxEntries:this.maxEntries,maxBytes:this.maxBytes,schemaVersion:this.schemaVersion}}async compact(e={}){let t=normalizeCompactionBoundary(e.expiredBefore),n=normalizeCompactionMaxRemovals(e.maxRemovals),r=(await this.getDatabase()).transaction(p,`readwrite`),i=waitForTransaction(r),a=r.objectStore(p).index(m).openCursor(this.namespace),o=new Map,s=0,c=0,l=0,u=!1;return await visitCursor(a,e=>{let r=e.value,i=classifyIndexedDBRecord(r,this.namespace,this.schemaVersion);if(s+=1,i===`malformed`||i===`schema-version`)e.delete(),addCleanupSummary(o,i,r),c+=1,l=addSizes(l,readIndexedDBRecordSize(r));else if(i===`current`&&r.expiresAt<=t){let t=readIndexedDBRecordSize(r);e.delete(),addCleanupSummary(o,`expired`,r),c+=1,l=addSizes(l,t)}if(c>=n)return u=!0,!1}),await i,this.emitCleanupSummaries(o.values()),{scannedEntries:s,removedEntries:c,estimatedBytesFreed:l,expiredBefore:t,hasMore:u}}async close(){let e=this.database;e&&(this.database=void 0,(await e).close())}createKey(e){return this.schemaVersion===1?`${this.namespace}\0${e}`:`${this.namespace}\0@npora-schema:${this.schemaVersion}\0${e}`}async writeRecord(e,t){let n=e.transaction(p,`readwrite`),r=waitForTransaction(n),i=n.objectStore(p),a=new Map;if(isFutureIndexedDBRecord(await waitForRequest(i.get(t.key)),this.schemaVersion)){await r;return}if(i.put(t),this.maxEntries!==1/0||this.maxBytes!==1/0){let e=await waitForRequest(i.index(m).getAll(this.namespace)),n=[];for(let t of e){let e=classifyIndexedDBRecord(t,this.namespace,this.schemaVersion);e===`malformed`||e===`schema-version`?(i.delete(t.key),addCleanupSummary(a,e,t)):e===`current`&&n.push(t)}n.sort((e,n)=>e.key===t.key?1:n.key===t.key?-1:e.accessedAt-n.accessedAt||e.key.localeCompare(n.key));let r=n.reduce((e,t)=>addSizes(e,readIndexedDBRecordSize(t)),0),o=n.length;for(let e of n){if(o<=this.maxEntries&&r<=this.maxBytes)break;i.delete(e.key),addCleanupSummary(a,r>this.maxBytes?`max-bytes`:`max-entries`,e),--o,r=Math.max(0,r-readIndexedDBRecordSize(e))}}await r,this.emitCleanupSummaries(a.values())}async recoverQuota(e){let t=e.transaction(p,`readwrite`),n=waitForTransaction(t),r=t.objectStore(p),i=await waitForRequest(r.index(m).getAll(this.namespace)),a=[],o=new Map,s=!1;for(let e of i){let t=classifyIndexedDBRecord(e,this.namespace,this.schemaVersion);t===`malformed`||t===`schema-version`?(r.delete(e.key),addCleanupSummary(o,t,e),s=!0):t===`current`&&a.push(e)}a.sort((e,t)=>e.accessedAt-t.accessedAt||e.key.localeCompare(t.key));for(let e of a.slice(0,Math.max(1,Math.ceil(a.length/2))))r.delete(e.key),addCleanupSummary(o,`quota-recovery`,e),s=!0;return await n,this.emitCleanupSummaries(o.values()),s}emitCleanupSummaries(e){for(let t of e)this.emitEvent({type:`eviction`,...t})}emitEvent(e){if(this.onEvent)try{Promise.resolve(this.onEvent({...e,timestamp:Date.now()})).catch(()=>{})}catch{}}async visitNamespace(e){let t=(await this.getDatabase()).transaction(p,`readwrite`),n=waitForTransaction(t),r=t.objectStore(p).index(m).openCursor(this.namespace),i=new Map;await visitCursor(r,t=>{let n=t.value,r=classifyIndexedDBRecord(n,this.namespace,this.schemaVersion);(r===`malformed`||r===`schema-version`||r===`current`&&e(n))&&(t.delete(),(r===`malformed`||r===`schema-version`)&&addCleanupSummary(i,r,n))}),await n,this.emitCleanupSummaries(i.values())}getDatabase(){return this.database??(this.database=openCacheDatabase(this.factory,this.databaseName).then(async e=>{try{let t=await pruneOlderSchemaRecords(e,this.namespace,this.schemaVersion);return this.emitCleanupSummaries(t),e}catch(t){throw e.close(),t}})),this.database}};function openCacheDatabase(e,t){return new Promise((n,r)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(p)||e.createObjectStore(p,{keyPath:`key`}).createIndex(m,m,{unique:!1})},i.onerror=()=>r(i.error),i.onsuccess=()=>{let e=i.result;e.onversionchange=()=>e.close(),n(e)}})}function waitForRequest(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)})}function waitForTransaction(e){let t=new Promise((t,n)=>{let rejectWithTransactionError=t=>{n(e.error??readIDBRequestError(t.target)??Error(`IndexedDB transaction failed`))};e.onabort=rejectWithTransactionError,e.onerror=rejectWithTransactionError,e.oncomplete=()=>t()});return t.catch(()=>{}),t}function readIDBRequestError(e){if(!e||!(`error`in e))return null;let t=e.error;return t instanceof DOMException?t:null}function visitCursor(e,t){return new Promise((n,r)=>{e.onerror=()=>r(e.error),e.onsuccess=()=>{let i=e.result;if(!i){n();return}try{if(t(i)===!1){n();return}}catch(t){try{readCursorTransaction(e)?.abort()}catch{}r(t);return}i.continue()}})}function readCursorTransaction(e){let t=e.source;if(t)return`transaction`in t?t.transaction:`objectStore`in t?t.objectStore.transaction:`transaction`in t.source?t.source.transaction:t.source.objectStore.transaction}function toPortableCacheEntry(e){return{data:e.data,expiresAt:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags}}function isValidIndexedDBRecord(e,t,n,r=1){if(!e||typeof e!=`object`)return!1;let i=e;if(!(typeof i.key==`string`&&(n===void 0||i.key===n)&&i.namespace===t&&readIndexedDBSchemaVersion(i)===r&&(i.expiresAt===1/0||Number.isFinite(i.expiresAt))&&Number.isInteger(i.status)&&i.status>=200&&i.status<=599&&typeof i.statusText==`string`&&Array.isArray(i.headers)&&(i.tags===void 0||Array.isArray(i.tags)&&i.tags.length<=32&&i.tags.every(e=>typeof e==`string`&&e.length>0&&e.length<=128))&&Number.isFinite(i.accessedAt)))return!1;try{return new Headers(i.headers),!0}catch{return!1}}function readIndexedDBSchemaVersion(e){if(!e||typeof e!=`object`)return;let t=e.schemaVersion??1;return Number.isSafeInteger(t)&&t>=1&&t<=1e9?t:void 0}function classifyIndexedDBRecord(e,t,n){let r=readIndexedDBSchemaVersion(e);return r===void 0?`malformed`:r>n?`future`:r<n?`schema-version`:isValidIndexedDBRecord(e,t,void 0,n)?`current`:`malformed`}function isFutureIndexedDBRecord(e,t){let n=readIndexedDBSchemaVersion(e);return n!==void 0&&n>t}function readIndexedDBRecordSize(e){let t=e&&typeof e==`object`?e.size:void 0;return Number.isSafeInteger(t)&&t>=0?t:estimateStructuredCloneSize(e)}function estimateStructuredCloneSize(e,t=new WeakSet){if(e==null)return 0;if(typeof e==`string`)return Math.min(2**53-1,e.length*2);if(typeof e==`number`||typeof e==`bigint`)return 8;if(typeof e==`boolean`)return 4;if(typeof e!=`object`)return 0;if(t.has(e)||(t.add(e),e instanceof Date))return 8;if(n(e))return e.size;if(i(e)||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Map){let n=16;for(let[r,i]of e)n=addSizes(n,estimateStructuredCloneSize(r,t),estimateStructuredCloneSize(i,t));return n}if(e instanceof Set){let n=16;for(let r of e)n=addSizes(n,estimateStructuredCloneSize(r,t));return n}let r=Array.isArray(e)?16:32;for(let[n,i]of Object.entries(e))r=addSizes(r,n.length*2,estimateStructuredCloneSize(i,t));return r}function addSizes(...e){let t=0;for(let n of e){if(n>=2**53-1-t)return 2**53-1;t+=n}return t}function addCleanupSummary(e,t,n){let r=e.get(t),i=readIndexedDBRecordSize(n);if(r){r.entries+=1,r.estimatedBytes=addSizes(r.estimatedBytes,i);return}e.set(t,{reason:t,entries:1,estimatedBytes:i})}function isQuotaExceededError(e){return!!(e&&typeof e==`object`&&e.name===`QuotaExceededError`)}async function pruneOlderSchemaRecords(e,t,n){let r=e.transaction(p,`readwrite`),i=waitForTransaction(r),a=r.objectStore(p).index(m).openCursor(t),o=new Map;return await visitCursor(a,e=>{let r=e.value,i=classifyIndexedDBRecord(r,t,n);(i===`malformed`||i===`schema-version`)&&(e.delete(),addCleanupSummary(o,i,r))}),await i,[...o.values()]}function normalizeIndexedDBName(e,n,r){let i=e??r;if(typeof i!=`string`||i.length===0||i.length>128)throw new t(`IndexedDB cache ${n} must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return i}function normalizeIndexedDBMaxEntries(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function normalizeIndexedDBMaxBytes(e){if(e===void 0)return 1/0;if(e===1/0)return e;if(!Number.isSafeInteger(e)||e<0)throw new t(`IndexedDB cache maxBytes must be a non-negative safe integer or Infinity`,{code:`CONFIG_ERROR`});return e}function normalizeQuotaRecovery(e){if(e===void 0)return!0;if(typeof e!=`boolean`)throw new t(`IndexedDB cache quotaRecovery must be a boolean`,{code:`CONFIG_ERROR`});return e}function normalizeIndexedDBEventObserver(e){if(e!==void 0&&typeof e!=`function`)throw new t(`IndexedDB cache onEvent must be a function`,{code:`CONFIG_ERROR`});return e}function normalizeIndexedDBAdmissionPolicy(e){if(e!==void 0&&typeof e!=`function`)throw new t(`IndexedDB cache shouldPersist must be a function`,{code:`CONFIG_ERROR`});return e}function normalizeCompactionBoundary(e){let n=e??Date.now();if(!Number.isFinite(n))throw new t(`IndexedDB cache compact expiredBefore must be finite`,{code:`CONFIG_ERROR`});return n}function normalizeCompactionMaxRemovals(e){if(e===void 0||e===1/0)return 1/0;if(!Number.isSafeInteger(e)||e<1)throw new t(`IndexedDB cache compact maxRemovals must be a positive safe integer or Infinity`,{code:`CONFIG_ERROR`});return e}function normalizeIndexedDBSchemaVersion(e){let n=e??1;if(!Number.isSafeInteger(n)||n<1||n>1e9)throw new t(`IndexedDB cache schemaVersion must be an integer from 1 to 1000000000`,{code:`CONFIG_ERROR`});return n}var TieredCacheStore=class{constructor(e){if(this.leaseReleases=new Set,this.source=`${Date.now()}:${Math.random()}`,this.trackedKeys=new Map,this.trackedKeyCount=0,this.handleMessage=e=>{let t=e.data;if(!isTieredCacheMessage(t)||t.source===this.source)return;if(t.action===`clear`){this.clearPrimary();return}let n=this.trackedKeys.get(t.fingerprint);if(!n){this.clearPrimary();return}this.trackedKeys.delete(t.fingerprint),this.trackedKeyCount-=n.size;for(let e of n)ignoreStoreResult(()=>this.primary.delete(e))},!e||!e.primary||!e.secondary||e.primary===e.secondary)throw new t(`Tiered cache requires distinct primary and secondary stores`,{code:`CONFIG_ERROR`});if(this.primary=e.primary,this.secondary=e.secondary,e.broadcast&&!e.broadcast.channel)throw new t(`Tiered cache broadcast requires a channel`,{code:`CONFIG_ERROR`});if(e.coordination&&!e.coordination.locks)throw new t(`Tiered cache coordination requires a lock manager`,{code:`CONFIG_ERROR`});this.channel=e.broadcast?.channel,this.locks=e.coordination?.locks,this.lockNamespace=normalizeLockNamespace(e.coordination?.namespace),this.maxTrackedKeys=normalizeTrackedKeys(e.broadcast?.maxTrackedKeys),this.locks&&(this.acquireRefreshLease=(e,t)=>this.acquireCoordinatedLease(e,t)),this.channel?.addEventListener(`message`,this.handleMessage)}get(e){let t;try{t=this.primary.get(e)}catch{return this.readSecondary(e)}return a(t)?Promise.resolve(t).then(t=>t?this.remember(e,t):this.readSecondary(e),()=>this.readSecondary(e)):t?this.remember(e,t):this.readSecondary(e)}set(e,t){let writePrimary=()=>{let n;try{n=this.primary.set(e,t)}catch(t){throw this.recoverPrimaryWrite(e),t}return a(n)?Promise.resolve(n).catch(t=>{throw this.recoverPrimaryWrite(e),t}):n},n=this.secondary.set(e,t),r=a(n)?Promise.resolve(n).then(writePrimary):writePrimary();return this.afterSuccess(r,()=>{this.trackKey(e),this.broadcastKey(e)})}delete(e){return this.afterSettled(()=>combineStoreOperations([()=>this.primary.delete(e),()=>this.secondary.delete(e)],()=>void 0),()=>{this.untrackKey(e),this.broadcastKey(e)})}invalidateTags(e){let n=this.primary.invalidateTags,r=this.secondary.invalidateTags;if(!n||!r)throw new t(`Both tiered cache stores must support tag invalidation`,{code:`CONFIG_ERROR`});return this.afterSettled(()=>combineStoreOperations([()=>n.call(this.primary,e),()=>r.call(this.secondary,e)],e=>Math.max(...e)),()=>this.broadcastClear())}clear(){return this.afterSettled(()=>combineStoreOperations([()=>this.primary.clear(),()=>this.secondary.clear()],()=>void 0),()=>this.broadcastClear())}async acquireCoordinatedLease(e,n){let r=`${this.lockNamespace}:${fingerprintCacheKey(e)}`,i=await this.requestLease(r,!0,n);if(i)return i;let a=await this.requestLease(r,!1,n);if(!a)throw new t(`Cache refresh lock was unavailable`,{code:`NETWORK_ERROR`});return await ignoreStoreFailure(()=>this.primary.delete(e)),a}dispose(){this.channel?.removeEventListener(`message`,this.handleMessage);for(let e of this.leaseReleases)e();this.leaseReleases.clear(),this.trackedKeys.clear(),this.trackedKeyCount=0}requestLease(e,t,n){return new Promise((r,i)=>{let a=!1,o=createDeferred(),s={mode:`exclusive`,ifAvailable:t};n&&(s.signal=n),this.locks.request(e,s,async e=>{if(!e){a=!0,r(void 0);return}let n=!0,release=()=>{n&&(n=!1,this.leaseReleases.delete(release),o.resolve())};this.leaseReleases.add(release),a=!0,r({contended:!t,release}),await o.promise}).catch(e=>{a||i(e)})})}readSecondary(e){let promote=t=>{if(t){try{let n=this.primary.set(e,t);if(a(n))return Promise.resolve(n).then(()=>this.remember(e,t),()=>this.remember(e,t))}catch{}return this.remember(e,t)}},t=this.secondary.get(e);return a(t)?Promise.resolve(t).then(promote):promote(t)}remember(e,t){return this.trackKey(e),t}trackKey(e){if(!this.channel)return;let t=fingerprintCacheKey(e),n=this.trackedKeys.get(t);if(n?.has(e)){this.trackedKeys.delete(t),this.trackedKeys.set(t,n);return}for(;this.trackedKeyCount>=this.maxTrackedKeys;){let e=this.trackedKeys.entries().next().value;if(!e)break;this.trackedKeys.delete(e[0]),this.trackedKeyCount-=e[1].size}n??(n=new Set),n.add(e),this.trackedKeys.delete(t),this.trackedKeys.set(t,n),this.trackedKeyCount+=1}untrackKey(e){let t=fingerprintCacheKey(e),n=this.trackedKeys.get(t);n?.delete(e)&&(--this.trackedKeyCount,n.size===0&&this.trackedKeys.delete(t))}broadcastKey(e){this.postMessage({protocol:`npora-cache:1`,source:this.source,action:`delete`,fingerprint:fingerprintCacheKey(e)})}broadcastClear(){this.trackedKeys.clear(),this.trackedKeyCount=0,this.postMessage({protocol:`npora-cache:1`,source:this.source,action:`clear`})}postMessage(e){try{this.channel?.postMessage(e)}catch{}}clearPrimary(){this.trackedKeys.clear(),this.trackedKeyCount=0,ignoreStoreResult(()=>this.primary.clear())}recoverPrimaryWrite(e){this.untrackKey(e),ignoreStoreResult(()=>this.primary.delete(e)),this.broadcastKey(e)}afterSuccess(e,t){return a(e)?Promise.resolve(e).then(e=>(t(),e)):(t(),e)}afterSettled(e,t){let n;try{n=e()}catch(e){throw t(),e}return a(n)?Promise.resolve(n).then(e=>(t(),e),e=>{throw t(),e}):(t(),n)}};function combineStoreOperations(e,t){let n=[],r=[],i,o=!1;for(let t of e)try{let e=t();a(e)?r.push(Promise.resolve(e).then(e=>{n.push(e)},e=>{o||(o=!0,i=e)})):n.push(e)}catch(e){o||(o=!0,i=e)}let finish=()=>{if(o)throw i;return t(n)};return r.length>0?Promise.all(r).then(finish):finish()}function fingerprintCacheKey(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function isTieredCacheMessage(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.protocol===`npora-cache:1`&&typeof t.source==`string`&&(t.action===`clear`||t.action===`delete`&&typeof t.fingerprint==`string`&&t.fingerprint.length<=16)}function normalizeTrackedKeys(e){let n=e??1e3;if(!Number.isInteger(n)||n<1||n>1e5)throw new t(`Tiered cache maxTrackedKeys must be an integer from 1 to 100000`,{code:`CONFIG_ERROR`});return n}function normalizeLockNamespace(e){let n=e??`npora-cache`;if(typeof n!=`string`||n.length<1||n.length>128)throw new t(`Tiered cache lock namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return n}function createDeferred(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}function ignoreStoreResult(e){try{let t=e();a(t)&&Promise.resolve(t).catch(()=>{})}catch{}}async function ignoreStoreFailure(e){try{await e()}catch{}}function cachePlugin(e={}){let t=createCacheState(e),n={name:`cache`,...createCacheMutations(t),install(r){let i=createCacheInstallation();return r.hooks.onRequest(createCacheRequestHandler(t,i,r,e)),r.hooks.onResponse(createCacheResponseHandler(t),{requiresRawResponse:!1}),r.hooks.onError(createCacheErrorHandler(t)),r.hooks.onSettled(createCacheSettledHandler(t,i,n)),createCacheCleanup(t,i)}};return n}export{WebStorageCacheStore as a,MemoryCacheStore as i,TieredCacheStore as n,IndexedDBCacheStore as r,cachePlugin as t};
@@ -0,0 +1 @@
1
+ const e=require("./RequestError-DrCr_lwO.cjs"),t=require("./isBinaryBody-B0414zDU.cjs"),n=require("./isPromiseLike-C8e95Or2.cjs"),r=require("./waitForSignal-D5eX-NMv.cjs"),i=require("./resolveExtensionConfig-BHHfQwjF.cjs");function normalizeCacheTtl(t,n){let r=t??3e4;if(r!==1/0&&(!Number.isFinite(r)||r<0))throw new e.t(`Cache ttl must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return r}function normalizeCacheStatus(t,n){let r=t??200;if(!Number.isInteger(r)||r<200||r>599)throw new e.t(`Cache status must be an integer between 200 and 599`,{code:`CONFIG_ERROR`,config:n});return r}function normalizeStaleIfError(t,n){if(t!==void 0){if(t!==1/0&&(!Number.isFinite(t)||t<0))throw new e.t(`Cache staleIfError must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return t}}function normalizeStaleWhileRevalidate(t,n){if(t!==void 0){if(t!==1/0&&(!Number.isFinite(t)||t<0))throw new e.t(`Cache staleWhileRevalidate must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return t}}function normalizeCacheTags(t,n){if(t===void 0)return[];if(typeof t!=`string`&&!Array.isArray(t))throw new e.t(`Cache tags must be an array of strings`,{code:`CONFIG_ERROR`,config:n});let r=typeof t==`string`?[t]:t;if(r.length>32)throw new e.t(`Cache tags cannot contain more than 32 values`,{code:`CONFIG_ERROR`,config:n});let i=new Set;for(let t of r){if(typeof t!=`string`||t.length===0||t.length>128)throw new e.t(`Cache tags must contain 1 to 128 characters`,{code:`CONFIG_ERROR`,config:n});i.add(t)}return[...i]}function isExpired(e){return e!==1/0&&(Number.isNaN(e)||Date.now()>=e)}var MemoryCacheStore=class{constructor(e={}){this.entries=new Map,this.maxEntries=normalizeMaxEntries(e.maxEntries)}get(e){let t=this.entries.get(e);if(t)return this.newestKey!==e&&(this.entries.delete(e),this.entries.set(e,t),this.newestKey=e),t}set(e,t){if(this.maxEntries!==0){for(this.entries.delete(e);this.entries.size>=this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e)}this.entries.set(e,t),this.newestKey=e}}delete(e){this.entries.delete(e),this.newestKey===e&&(this.newestKey=void 0)}invalidateTags(e){let t=new Set(e),n=0;for(let[e,r]of this.entries)r.tags?.some(e=>t.has(e))&&(this.entries.delete(e),n+=1,this.newestKey===e&&(this.newestKey=void 0));return n}clear(){this.entries.clear(),this.newestKey=void 0}},WebStorageCacheStore=class{constructor(e,t={}){this.storage=e,this.prefix=createWebStoragePrefix(t.namespace),this.maxEntries=normalizeMaxEntries(t.maxEntries)}get(e){if(this.maxEntries===0)return;let t=this.prefix+e,n=this.read(t);if(n){try{this.storage.setItem(t,serializeWebStorageEntry(n.entry,Date.now()))}catch{}return n.entry}}set(e,t){if(this.maxEntries===0)return;let n=this.prefix+e,r=this.keys(),i=r.includes(n),a=Math.max(0,r.length-this.maxEntries+ +!i);if(a>0){let e=r.map(e=>({key:e,accessedAt:this.read(e)?.accessedAt??0})).filter(e=>e.key!==n).sort((e,t)=>e.accessedAt-t.accessedAt);for(let t of e.slice(0,a))this.storage.removeItem(t.key)}this.storage.setItem(n,serializeWebStorageEntry(t,Date.now()))}delete(e){this.storage.removeItem(this.prefix+e)}invalidateTags(e){let t=new Set(e),n=0;for(let e of this.keys())this.read(e)?.entry.tags?.some(e=>t.has(e))&&(this.storage.removeItem(e),n+=1);return n}clear(){for(let e of this.keys())this.storage.removeItem(e)}keys(){let e=[];for(let t=0;t<this.storage.length;t+=1){let n=this.storage.key(t);n?.startsWith(this.prefix)&&e.push(n)}return e}read(e){let t=this.storage.getItem(e);if(t!==null)try{return parseWebStorageEntry(t)}catch{this.storage.removeItem(e);return}}};function normalizeMaxEntries(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function createWebStoragePrefix(t=`default`){if(typeof t!=`string`||t.length===0||t.length>128)throw new e.t(`Web storage cache namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return`@npora/request:${encodeURIComponent(t)}:`}function serializeWebStorageEntry(e,t){return JSON.stringify({version:1,data:e.data,expiresAt:e.expiresAt===1/0?null:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags,accessedAt:t})}function parseWebStorageEntry(e){let t=JSON.parse(e),n=t.expiresAt===null?1/0:t.expiresAt;if(t.version!==1||n!==1/0&&(typeof n!=`number`||!Number.isFinite(n))||typeof t.status!=`number`||!Number.isInteger(t.status)||t.status<200||t.status>599||typeof t.statusText!=`string`||!Array.isArray(t.headers)||typeof t.accessedAt!=`number`||!Number.isFinite(t.accessedAt))throw TypeError(`Invalid web storage cache entry`);let r=t.tags===void 0?void 0:normalizeCacheTags(t.tags);return{entry:{data:t.data,expiresAt:n,status:t.status,statusText:t.statusText,headers:[...new Headers(t.headers).entries()],tags:r&&r.length>0?r:void 0},accessedAt:t.accessedAt}}const a=[];function createCacheKey(e,t,n,r,i){if(t.key)return t.key;let o=e.method??`GET`,s=String(e.url),c=e.responseType??`auto`,l=!e.headers&&!e.query&&!e.searchParams;if(l&&i.key!==void 0&&i.method===o&&i.baseURL===e.baseURL&&i.url===s&&i.responseType===c)return i.key;let u=JSON.stringify({method:o,baseURL:e.baseURL,url:s,query:l?a:normalizeQuery(e.searchParams??e.query),responseType:c,headers:e.headers?normalizeCacheHeaders(new Headers(e.headers),n):r});return l&&(i.method=o,i.baseURL=e.baseURL,i.url=s,i.responseType=c,i.key=u),u}function normalizeCacheHeaders(e,t){let n=[];e?.forEach((e,t)=>{isRequestCacheControlHeader$1(t)||n.push([t,e])});for(let r of t)!isRequestCacheControlHeader$1(r)&&!e?.has(r)&&n.push([r,null]);return n.sort(([e],[t])=>e.localeCompare(t))}function isRequestCacheControlHeader$1(e){return e===`cache-control`||e===`pragma`}function normalizeVaryHeaders(e){return[...new Set(e.map(e=>e.toLowerCase()))]}function normalizeQuery(e){if(!e)return a;if(t.r(e))return[...e.entries()];let n=[];for(let t of Object.keys(e).sort())appendQueryValue(n,t,e[t]);return n}function appendQueryValue(e,t,n){if(n!==void 0){if(n===null){e.push([t,``]);return}if(Array.isArray(n)){for(let r of n)appendQueryValue(e,t,r);return}e.push([t,String(n)])}}const o={hit:`hits`,miss:`misses`,bypass:`bypasses`,invalidated:`invalidations`,"invalidation-error":`invalidationErrors`,deduplicated:`deduplicated`,revalidated:`revalidations`,"stale-if-error":`staleIfError`,"stale-while-revalidate":`staleWhileRevalidate`,"background-refresh":`backgroundRefreshes`,"background-refresh-success":`backgroundRefreshSuccesses`,"background-refresh-error":`backgroundRefreshErrors`};function createCacheStats(){return{hits:0,misses:0,bypasses:0,invalidations:0,invalidationErrors:0,deduplicated:0,revalidations:0,staleIfError:0,staleWhileRevalidate:0,backgroundRefreshes:0,backgroundRefreshSuccesses:0,backgroundRefreshErrors:0}}function resetCacheStats(e){Object.assign(e,createCacheStats())}function createCacheEventRecorder(e,t){return r=>{if(incrementCacheStat(e,r),t)try{let e=t({type:r,timestamp:Date.now()});n.t(e)&&Promise.resolve(e).catch(ignoreCacheEventError)}catch{}}}function incrementCacheStat(e,t){let n=o[t];e[n]=Math.min(2**53-1,e[n]+1)}function ignoreCacheEventError(){}const s=[`GET`,`HEAD`],c=[`authorization`,`cookie`,`accept`,`accept-language`];function createCacheState(e){let t=e.store??new MemoryCacheStore({maxEntries:e.maxEntries}),n=new WeakSet,r=new WeakMap,i=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakSet,f=new WeakSet,p=new WeakMap,m=new WeakMap,h=new WeakSet,g=new WeakSet,_=new Map,v=new Map,y=new WeakSet,b=new Map,x=new Map,S=new Map,C=new Map,w=createCacheStats(),T=createCacheEventRecorder(w,e.onEvent),E=new Set(e.methods??s),D=normalizeVaryHeaders(e.varyHeaders??c);return{store:t,cacheHits:n,leaders:r,requestGenerations:i,automaticInvalidations:a,unsharedGenerations:o,completedRecords:l,revalidations:u,forcedRevalidations:d,noStoreRequests:f,staleFallbacks:p,refreshLeases:m,cacheFallbacks:h,uncacheableLeaders:g,inFlight:_,rawInFlight:v,rawLeaders:y,backgroundRefreshes:b,keyGenerations:x,keyOperations:S,tagInvalidations:C,stats:w,recordEvent:T,generation:0,methods:E,varyHeaders:D,emptyHeaderValues:normalizeCacheHeaders(void 0,D),keyMemo:{}}}const l={persist:!1,ttl:0};function resolveRequestCachePolicy(e){let t=new Headers(e.headers),n=t.get(`cache-control`),r=!1;if(n)for(let e of n.split(`,`)){let t=e.trim(),n=t.indexOf(`=`),i=(n===-1?t:t.slice(0,n)).trim().toLowerCase();if(i===`no-store`)return`no-store`;if(i===`no-cache`){r=!0;continue}if(i===`max-age`&&n!==-1){let e=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());e&&Number(e[1]??e[2])===0&&(r=!0)}}else t.get(`pragma`)?.split(`,`).some(e=>e.trim().toLowerCase()===`no-cache`)&&(r=!0);return r?`revalidate`:`default`}function resolveResponseCachePolicy(e,t,n,r){let i=e.headers.get(`cache-control`),a,o=!1;if(i)for(let e of i.split(`,`)){let t=e.trim(),n=t.indexOf(`=`),r=(n===-1?t:t.slice(0,n)).trim().toLowerCase();if(r===`no-store`)return l;if(r===`no-cache`){o=!0;continue}if(r!==`max-age`)continue;if(a!==void 0)return l;let i=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());if(!i)return l;a=Number(i[1]??i[2])}if(e.headers.get(`vary`)?.split(`,`).some(e=>{let t=e.trim().toLowerCase();return t===`*`||isRequestCacheControlHeader(t)})||t<=0||a!==void 0&&!Number.isSafeInteger(a))return l;let s=o?0:a===void 0?t:Math.min(t,Math.max(0,(a-parseAge(e.headers.get(`age`)))*1e3));return{ttl:s,persist:s>0||hasResponseValidator$1(e.headers)||resolveStaleIfErrorWindow(e.headers,n)>0||!o&&resolveStaleWhileRevalidateWindow(e.headers,r)>0}}function resolveStaleIfErrorWindow(e,t){return resolveWindow(e,t,`stale-if-error`)}function resolveStaleWhileRevalidateWindow(e,t){return resolveWindow(e,t,`stale-while-revalidate`)}function hasCacheControlDirective(e,t){return e.get(`cache-control`)?.split(`,`).some(e=>{let n=e.indexOf(`=`);return(n===-1?e:e.slice(0,n)).trim().toLowerCase()===t})??!1}function resolveWindow(e,t,n){let r=parseCacheDeltaSeconds(e.get(`cache-control`),n);return t===void 0?r??0:r===void 0?t:Math.min(t,r)}function parseCacheDeltaSeconds(e,t){let n;if(!e)return;for(let r of e.split(`,`)){let e=r.trim(),i=e.indexOf(`=`);if(i===-1||e.slice(0,i).trim().toLowerCase()!==t)continue;if(n!==void 0)return;let a=/^(?:"(\d+)"|(\d+))$/.exec(e.slice(i+1).trim());if(!a)return;n=Number(a[1]??a[2])}if(n===void 0||!Number.isSafeInteger(n))return;let r=n*1e3;return Number.isSafeInteger(r)?r:void 0}function parseAge(e){if(!e||!/^\d+$/.test(e.trim()))return 0;let t=Number(e);return Number.isSafeInteger(t)?t:0}function hasResponseValidator$1(e){return e.has(`etag`)||e.has(`last-modified`)}function isRequestCacheControlHeader(e){return e===`cache-control`||e===`pragma`}function isCacheableRequest(e,t,n){return t.has(e.method??`GET`)&&(!hasRequestBody(e)||!!n.key)&&(!e.parseJson||!!n.key)&&(!e.querySerializer||!!n.key)&&e.responseType!==`stream`&&e.responseType!==`sse`&&e.responseType!==`ndjson`&&e.responseType!==`bytes`&&e.responseType!==`formData`&&e.fetchOptions?.mode!==`no-cors`&&e.fetchOptions?.redirect!==`manual`}function hasRequestBody(e){return e.body!=null||e.json!==void 0||e.form!=null||e.formData!=null}function isAsyncIterable(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}function isSchemaValidationFailure(t){return e.n(t)&&t.code===`SCHEMA_ERROR`}function canUseStaleIfError(e,t,n,r){try{if(n&&!e.raw||hasConditionalRequestHeaders(t))return!1;let i=resolveStaleIfErrorWindow(new Headers(e.headers),r);return i>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+i}catch{return!1}}function canUseStaleWhileRevalidate(e,t,n,r){try{if(n&&!e.raw)return!1;let i=new Headers(e.headers);if(hasConditionalRequestHeaders(t)||hasCacheControlDirective(i,`no-cache`)||hasCacheControlDirective(i,`must-revalidate`))return!1;let a=resolveStaleWhileRevalidateWindow(i,r);return a>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+a}catch{return!1}}function startBackgroundRefresh(e,t,n,r,i,a){if(t.has(n))return;let o=new AbortController,s={...r,signal:o.signal};t.set(n,o),a(`background-refresh`),Promise.resolve().then(()=>e.dispatch(s,{background:!0,preserveRaw:i})).then(()=>a(`background-refresh-success`),()=>a(`background-refresh-error`)).finally(()=>{t.get(n)===o&&t.delete(n)})}function abortBackgroundRefreshes(e){for(let t of e.values())t.abort(`Cache background refresh stopped`);e.clear()}function isEligibleStaleIfError(t){return e.n(t)&&(t.code===`NETWORK_ERROR`||t.code===`TIMEOUT_ERROR`||t.code===`HTTP_ERROR`&&t.status!==void 0&&t.status>=500&&t.status<600)}function canRevalidateCacheEntry(e,t,n){try{return n&&!e.raw||hasConditionalRequestHeaders(t)?!1:hasResponseValidator(new Headers(e.headers))}catch{return!1}}function prepareConditionalRevalidation(e,t){let n=new Headers(t.headers),r=n.get(`etag`),i=n.get(`last-modified`);if(!r&&!i)return!1;let a=new Headers(e.headers);r&&a.set(`if-none-match`,r),i&&a.set(`if-modified-since`,i);let o=e.validateStatus,s=e.throwHttpErrors;return e.headers=a,e.throwHttpErrors=void 0,e.validateStatus=e=>e===304||(o?o(e):s===!1||e>=200&&e<300),!0}function hasResponseValidator(e){return e.has(`etag`)||e.has(`last-modified`)}function hasConditionalRequestHeaders(e){let t=new Headers(e.headers);return t.has(`if-none-match`)||t.has(`if-modified-since`)||t.has(`range`)}function createCacheEntry(e,t,n,r){return{data:cloneCacheValue(e.data),expiresAt:t,status:e.status,statusText:e.statusText,headers:[...e.headers.entries()],tags:r?[...r]:void 0,raw:n?cloneResponse(e.raw):void 0}}function createCachedResponse(e,t){return{data:cloneCacheValue(e.data),status:e.status,statusText:e.statusText,headers:new Headers(e.headers),config:t,raw:cloneRawResponse(e)}}function restoreCacheEntry(e,t){try{return createCachedResponse(e,t)}catch{return}}function createRevalidatedResponse(e,t,n){let r=new Headers(e.headers);return t.headers.forEach((e,t)=>{r.set(t,e)}),createCachedResponse({...e,headers:[...r.entries()]},n)}function cloneRawResponse(e){if(e.raw){let t=cloneResponse(e.raw);if(t)return new Response(t.body,{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})}function cloneResponse(e){try{return e.clone()}catch{return}}function cloneCacheValue(e){if(typeof e!=`object`||!e||typeof structuredClone!=`function`)return e;try{return structuredClone(e)}catch{return e}}function createCacheOperations(e){let{keyOperations:t,tagInvalidations:r,recordEvent:i,keyGenerations:a,inFlight:o,rawInFlight:s,backgroundRefreshes:c}=e;function trackKeyOperation(e,n,r,a){let o=Promise.resolve(n),s;return s=o.then(()=>r&&i(r),()=>a&&i(a)).finally(()=>{t.get(e)===s&&t.delete(e)}),t.set(e,s),o}function runKeyOperation(e,r,a=[],o,s){let c=new Set(a),l=t.get(e);if(l&&c.add(l),c.size>0)return trackKeyOperation(e,Promise.all(c).then(r),o,s);let u;try{u=r()}catch(e){throw s&&i(s),e}return n.t(u)?trackKeyOperation(e,u,o,s):(o&&i(o),u)}function invalidateKeyState(e,t){a.delete(e),o.delete(e),s.delete(e);let n=c.get(e);n&&(c.delete(e),n.abort(t))}function trackTagInvalidation(e,t){let n=Promise.resolve(t),a;a=n.then(()=>i(`invalidated`),()=>i(`invalidation-error`)).finally(()=>{for(let t of e)r.get(t)===a&&r.delete(t)});for(let t of e)r.set(t,a);return n}return{runKeyOperation,invalidateKeyState,trackTagInvalidation}}function createCacheMutations(t){let{store:r,keyGenerations:a,inFlight:o,rawInFlight:s,backgroundRefreshes:c,keyOperations:l,tagInvalidations:u,recordEvent:d,varyHeaders:f,emptyHeaderValues:p,keyMemo:m,stats:h}=t,{runKeyOperation:g,invalidateKeyState:_,trackTagInvalidation:v}=createCacheOperations(t);return{clear(){return t.generation+=1,o.clear(),s.clear(),a.clear(),abortBackgroundRefreshes(c),r.clear()},delete(e){let t=createCacheKey(e,i.t(e,`cache`)??{},f,p,m);return _(t,`Cache entry invalidated`),g(t,()=>r.delete(t),[],`invalidated`,`invalidation-error`)},set(e,t,n={}){let a=i.t(e,`cache`)??{},o=createCacheKey(e,a,f,p,m),s=normalizeCacheTtl(n.ttl??a.ttl,e),c=normalizeCacheStatus(n.status,e),l=normalizeCacheTags(n.tags??a.tags,e),d={data:cloneCacheValue(t),expiresAt:s===1/0?s:Date.now()+s,status:c,statusText:n.statusText??(c===200?`OK`:``),headers:[...new Headers(n.headers).entries()],tags:l.length>0?l:void 0},h=l.map(e=>u.get(e)).filter(e=>!!e);return _(o,`Cache entry replaced`),g(o,()=>r.set(o,d),h)},update(e,t){let a=createCacheKey(e,i.t(e,`cache`)??{},f,p,m);return _(a,`Cache entry updated`),g(a,()=>{let updateEntry=e=>{if(!e)return!1;let i=t(cloneCacheValue(e.data));if(i===void 0){let e=r.delete(a);return!n.t(e)||Promise.resolve(e).then(()=>!0)}let o=r.set(a,{...e,data:cloneCacheValue(i),raw:void 0});return!n.t(o)||Promise.resolve(o).then(()=>!0)},e=r.get(a);return n.t(e)?Promise.resolve(e).then(updateEntry):updateEntry(e)},u.values())},invalidateTags(t){let i=normalizeCacheTags(t);if(i.length===0)throw new e.t(`Cache tag invalidation requires at least one tag`,{code:`CONFIG_ERROR`});let o=r.invalidateTags;if(!o)throw new e.t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`});for(let[e,t]of a)i.some(e=>t.tags.has(e))&&_(e,`Cache tags invalidated`);let s=new Set(i.map(e=>u.get(e)).filter(e=>!!e));for(let e of l.values())s.add(e);if(s.size>0)return v(i,Promise.all(s).then(()=>o.call(r,i)));let c;try{c=o.call(r,i)}catch(e){throw d(`invalidation-error`),e}return n.t(c)?v(i,c):(d(`invalidated`),c)},getStats(){return{...h}},resetStats(){resetCacheStats(h)}}}function acquireCacheGeneration(e,t,n,r){let i=n.get(t);i||(i={activeRequests:0,tags:new Set},n.set(t,i)),i.activeRequests+=1;for(let e of r)i.tags.add(e);return{global:e,key:t,token:i}}function isCurrentCacheGeneration(e,t,n){return e!==void 0&&e.global===t&&n.get(e.key)===e.token}function releaseCacheGeneration(e,t){--e.token.activeRequests,e.token.activeRequests===0&&t.get(e.key)===e.token&&t.delete(e.key)}function createInFlightRequest(e,t,n){return{owner:e,key:t,generation:n}}function getInFlightPromise(e){if(e.promise)return e.promise;let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.catch(()=>{}),e.promise=r,e.resolve=t,e.reject=n,r}function readStore(e,t){try{let r=e.get(t);return n.t(r)?Promise.resolve(r).catch(()=>void 0):r}catch{return}}function writeStore(e,t,r){try{let i=e.set(t,r);if(n.t(i))return Promise.resolve(i).catch(ignoreStoreError)}catch{}}function deleteStore(e,t){try{let r=e.delete(t);if(n.t(r))return Promise.resolve(r).catch(ignoreStoreError)}catch{}}function ignoreStoreError(){}function waitForSharedRecord(e,t){let n=t.signal;return n?n.aborted?Promise.reject(createSharedAbortError(n.reason,t)):new Promise((r,i)=>{let a=!1,cleanup=()=>{try{n.removeEventListener(`abort`,onAbort)}catch{}},resolveOnce=e=>{a||(a=!0,cleanup(),r(e))},rejectOnce=e=>{a||(a=!0,cleanup(),i(e))},onAbort=()=>{rejectOnce(createSharedAbortError(n.reason,t))};try{n.addEventListener(`abort`,onAbort,{once:!0})}catch(e){rejectOnce(e);return}n.aborted&&onAbort(),!a&&e.then(resolveOnce,e=>{rejectOnce(cloneSharedError(e,t))})}):e.catch(e=>{throw cloneSharedError(e,t)})}function createSharedAbortError(t,n){return new e.t(`Request aborted while waiting for shared response`,{code:`ABORT_ERROR`,config:n,cause:t})}function cloneSharedError(t,n){return e.n(t)?new e.t(t.message,{code:t.code,status:t.status,data:t.data,response:t.response,config:n,cause:t}):t}function createCacheResponseHandler(e){let{cacheFallbacks:t,recordEvent:a,cacheHits:o,leaders:s,uncacheableLeaders:c,methods:l,noStoreRequests:u,revalidations:d,varyHeaders:f,emptyHeaderValues:p,keyMemo:m,unsharedGenerations:h,requestGenerations:g,keyGenerations:_,completedRecords:v,store:y}=e;return b=>{if(t.has(b)&&b.fallbackResponse){a(`stale-if-error`),o.add(b),b.cacheHit=!0,s.get(b)?.owner===b&&c.add(b);return}if(o.has(b))return;let x=i.t(b.config,`cache`);if(!x?.enabled||!b.response||!isCacheableRequest(b.config,l,x)||u.has(b))return;let S=d.get(b);if(b.response.raw.type===`opaque`||b.response.raw.type===`opaqueredirect`){s.get(b)?.owner===b&&c.add(b);return}S&&b.response.status===304&&(a(`revalidated`),b.response=createRevalidatedResponse(S,b.response,b.config));let C=s.get(b),w=C?.key??createCacheKey(b.config,x,f,p,m),T=isCurrentCacheGeneration(C?.generation??h.get(b)??g.get(b),e.generation,_),E=(C?.generation??g.get(b))?.token.tags,D=E&&E.size>0?[...E]:S?.tags;if(isAsyncIterable(b.response.data)){if(c.add(b),!T)return;let e=deleteStore(y,w);return n.t(e)?b.config.signal?r.t(()=>e,b.config):e:void 0}let O=normalizeCacheTtl(x.ttl,b.config),k=normalizeStaleIfError(x.staleIfError,b.config),A=normalizeStaleWhileRevalidate(x.staleWhileRevalidate,b.config),j=resolveResponseCachePolicy(b.response,O,k,A),M=j.ttl;if(!j.persist){let e=T?deleteStore(y,w):void 0,t=n.t(e),i=C;return i?.owner===b&&(i.promise!==void 0||t)?v.set(b,createCacheEntry(b.response,Date.now()+Math.max(0,M),b.preserveRaw,D)):i?.owner===b&&c.add(b),t?b.config.signal?r.t(()=>e,b.config):e:void 0}let N=createCacheEntry(b.response,Date.now()+M,b.preserveRaw,D);if(v.set(b,N),!T||C?.rawDemanded)return;let P=writeStore(y,w,N);if(n.t(P))return b.config.signal?r.t(()=>P,b.config):P}}function createCacheMissHandler(e,t,n,i){let{keyGenerations:a,recordEvent:o,unsharedGenerations:s,rawInFlight:c,inFlight:l,cacheHits:u,store:d,refreshLeases:f,forcedRevalidations:p,rawLeaders:m,leaders:h,revalidations:g}=e,{ownedLeaders:_,ownedRefreshLeases:v}=t;function prepareCacheMiss(y,b,x,S,C){if(!t.active||!isCurrentCacheGeneration(S,e.generation,a))return;if(!(b.dedupe??n.dedupe??!0)){y.background||o(`miss`),s.set(y,S);return}let w=y.preserveRaw?c.get(x):l.get(x)??c.get(x);if(w)return o(`deduplicated`),waitForSharedRecord(getInFlightPromise(w),y.config).then(e=>{e&&(y.response=createCachedResponse(e,y.config),u.add(y),y.cacheHit=!0)});let T=d.acquireRefreshLease;if(T&&!f.has(y)){let e;try{let t=T.call(d,x,y.config.signal);e=y.config.signal?r.t(()=>t,y.config):t}catch{return f.set(y,{contended:!1,release(){}}),i(y,b,x,C,S)}return e.then(e=>(f.set(y,e),v.add(e),e.contended&&(p.delete(y),o(`deduplicated`)),Promise.resolve(readStore(d,x)).then(e=>i(y,b,x,e,S))),e=>{if(y.config.signal?.aborted)throw e;return f.set(y,{contended:!1,release(){}}),i(y,b,x,C,S)})}if(y.preserveRaw){let e=l.get(x);e&&(e.rawDemanded=!0)}let E=createInFlightRequest(y,x,S);y.preserveRaw?(c.set(x,E),m.add(y)):l.set(x,E),h.set(y,E),_.add(y),y.background||o(`miss`),C&&prepareConditionalRevalidation(y.config,C)&&g.set(y,C)}return prepareCacheMiss}function createCacheRecordHandler(e,t,i,a){let{keyGenerations:o,forcedRevalidations:s,recordEvent:c,cacheHits:l,backgroundRefreshes:u,staleFallbacks:d,store:f}=e;function handleCacheRecord(p,m,h,g,_){if(!(!t.active||!isCurrentCacheGeneration(_,e.generation,o))){if(g){let e=!isExpired(g.expiresAt),t=s.has(p);if(e&&!t){if(p.preserveRaw&&!g.raw)return a(p,m,h,_);let e=restoreCacheEntry(g,p.config);if(e){c(`hit`),p.response=e,l.add(p),p.cacheHit=!0;return}}if(!p.background&&!t&&canUseStaleWhileRevalidate(g,p.config,p.preserveRaw,normalizeStaleWhileRevalidate(m.staleWhileRevalidate,p.config))){let e=restoreCacheEntry(g,p.config);if(e){c(`stale-while-revalidate`),p.response=e,l.add(p),p.cacheHit=!0,startBackgroundRefresh(i,u,h,p.initialConfig,p.preserveRaw,c);return}}if(!p.background&&canUseStaleIfError(g,p.config,p.preserveRaw,normalizeStaleIfError(m.staleIfError,p.config))&&d.set(p,g),canRevalidateCacheEntry(g,p.config,p.preserveRaw)&&restoreCacheEntry(g,p.config))return a(p,m,h,_,g);if(e&&t||p.background)return a(p,m,h,_);let o=deleteStore(f,h);if(n.t(o))return(p.config.signal?r.t(()=>o,p.config):Promise.resolve(o)).then(()=>a(p,m,h,_))}return a(p,m,h,_)}}return handleCacheRecord}function createCacheRequestHandler(t,a,o,s){let{store:c,automaticInvalidations:l,methods:u,recordEvent:d,noStoreRequests:f,forcedRevalidations:p,varyHeaders:m,emptyHeaderValues:h,keyMemo:g,keyGenerations:_,requestGenerations:v,keyOperations:y,tagInvalidations:b}=t,x=createCacheRecordHandler(t,a,o,createCacheMissHandler(t,a,s,(...e)=>x(...e)));return a=>{let o=i.t(a.config,`cache`);if(!o)return;let s=normalizeCacheTags(o.invalidateTags,a.config);if(s.length>0){if(!c.invalidateTags)throw new e.t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`,config:a.config});l.set(a,s)}if(!o.enabled||!isCacheableRequest(a.config,u,o))return;normalizeCacheTtl(o.ttl,a.config),normalizeStaleIfError(o.staleIfError,a.config),normalizeStaleWhileRevalidate(o.staleWhileRevalidate,a.config);let S=normalizeCacheTags(o.tags,a.config),C=resolveRequestCachePolicy(a.config);if(C===`no-store`){d(`bypass`),f.add(a);return}(C===`revalidate`||a.background)&&p.add(a);let w=createCacheKey(a.config,o,m,h,g),T=acquireCacheGeneration(t.generation,w,_,S);v.set(a,T);let read=()=>{let e=readStore(c,w);return n.t(e)?(a.config.signal?r.t(()=>e,a.config):Promise.resolve(e)).then(e=>{if(isCurrentCacheGeneration(T,t.generation,_))return x(a,o,w,e,T)}):x(a,o,w,e,T)},E=new Set,D=y.get(w);D&&E.add(D);for(let e of S){let t=b.get(e);t&&E.add(t)}if(E.size>0){let e=Promise.all(E).then(()=>{});return a.config.signal?r.t(()=>e,a.config).then(read):e.then(read)}return read()}}function createCacheInstallation(){return{active:!0,ownedLeaders:new Set,ownedRefreshLeases:new Set}}function createCacheErrorHandler(e){let{staleFallbacks:t,cacheFallbacks:n}=e;return e=>{let r=t.get(e);if(!r||!isEligibleStaleIfError(e.error))return;let i=restoreCacheEntry(r,e.config);i&&(n.add(e),e.fallbackResponse=i)}}function createCacheSettledHandler(t,r,i){let{refreshLeases:a,forcedRevalidations:o,noStoreRequests:s,staleFallbacks:c,cacheFallbacks:l,requestGenerations:u,automaticInvalidations:d,keyGenerations:f,leaders:p,revalidations:m,rawLeaders:h,rawInFlight:g,inFlight:_,uncacheableLeaders:v,completedRecords:y}=t,{ownedLeaders:b,ownedRefreshLeases:x}=r;return t=>{let r=a.get(t);r&&(r.release(),x.delete(r)),a.delete(t),o.delete(t),s.delete(t),c.delete(t),l.delete(t);let S=u.get(t),invalidateAfterSuccess=()=>{let e=d.get(t);if(d.delete(t),!(!e||t.background||t.error||!t.response))try{let t=i.invalidateTags(e);if(n.t(t))return Promise.resolve(t).then(()=>{}).catch(ignoreCacheEventError)}catch{}};S&&(u.delete(t),releaseCacheGeneration(S,f));let C=p.get(t);if(!C)return invalidateAfterSuccess();p.delete(t),b.delete(t),m.delete(t);let w=C.key,T=h.delete(t)?g:_;if(T.get(w)===C&&T.delete(w),v.delete(t))return C.resolve?.(void 0),invalidateAfterSuccess();let E=y.get(t);return y.delete(t),E&&t.response&&(!t.error||isSchemaValidationFailure(t.error))?(C.resolve?.(E),invalidateAfterSuccess()):(C.reject?.(t.error??new e.t(`Shared request failed`,{code:`NETWORK_ERROR`,config:t.config})),invalidateAfterSuccess())}}function createCacheCleanup(t,n){let{leaders:r,rawLeaders:i,rawInFlight:a,inFlight:o,keyGenerations:s,backgroundRefreshes:c}=t,{ownedLeaders:l,ownedRefreshLeases:u}=n;return()=>{n.active=!1;for(let e of u)e.release();u.clear();for(let t of l){let n=r.get(t);if(r.delete(t),!n)continue;let s=n.key,c=i.delete(t)?a:o;c.get(s)===n&&c.delete(s),n.reject?.(new e.t(`Cache plugin removed during shared request`,{code:`ABORT_ERROR`}))}l.clear(),s.clear(),abortBackgroundRefreshes(c)}}const u=`entries`,d=`namespace`;var IndexedDBCacheStore=class{constructor(e,t={}){this.namespace=normalizeIndexedDBName(t.namespace,`namespace`,`default`),this.maxEntries=normalizeIndexedDBMaxEntries(t.maxEntries),this.maxBytes=normalizeIndexedDBMaxBytes(t.maxBytes),this.quotaRecovery=normalizeQuotaRecovery(t.quotaRecovery),this.shouldPersist=normalizeIndexedDBAdmissionPolicy(t.shouldPersist),this.onEvent=normalizeIndexedDBEventObserver(t.onEvent),this.schemaVersion=normalizeIndexedDBSchemaVersion(t.schemaVersion),this.databaseName=normalizeIndexedDBName(t.databaseName,`database name`,`@npora/request-cache`),this.factory=e}async get(e){if(this.maxEntries===0||this.maxBytes===0){await this.delete(e);return}let t=(await this.getDatabase()).transaction(u,`readwrite`),n=waitForTransaction(t),r=t.objectStore(u),i=this.createKey(e),a=await waitForRequest(r.get(i)),o=isFutureIndexedDBRecord(a,this.schemaVersion);if(!isValidIndexedDBRecord(a,this.namespace,i,this.schemaVersion)){a!==void 0&&!o&&r.delete(i),await n,a!==void 0&&!o&&this.emitEvent({type:`eviction`,reason:`malformed`,entries:1,estimatedBytes:readIndexedDBRecordSize(a)});return}return a.accessedAt=Date.now(),a.size=readIndexedDBRecordSize(a),r.put(a),await n,toPortableCacheEntry(a)}async set(t,n){if(this.maxEntries===0||this.maxBytes===0){await this.delete(t);return}let r=await this.getDatabase(),i={...toPortableCacheEntry(n),key:this.createKey(t),namespace:this.namespace,accessedAt:Date.now(),schemaVersion:this.schemaVersion};if(i.size=estimateStructuredCloneSize(i),i.size>this.maxBytes){await this.delete(t),this.emitEvent({type:`rejection`,reason:`oversized`,entries:1,estimatedBytes:i.size});return}let a=!this.shouldPersist||await this.shouldPersist(toPortableCacheEntry(i),i.size);if(typeof a!=`boolean`)throw new e.t(`IndexedDB cache shouldPersist must return a boolean`,{code:`CONFIG_ERROR`});if(!a){await this.delete(t),this.emitEvent({type:`rejection`,reason:`admission-policy`,entries:1,estimatedBytes:i.size});return}try{await this.writeRecord(r,i)}catch(e){if(!this.quotaRecovery||!isQuotaExceededError(e)||!await this.recoverQuota(r))throw e;await this.writeRecord(r,i)}}async delete(e){let t=(await this.getDatabase()).transaction(u,`readwrite`),n=waitForTransaction(t),r=t.objectStore(u),i=this.createKey(e);isFutureIndexedDBRecord(await waitForRequest(r.get(i)),this.schemaVersion)||r.delete(i),await n}async invalidateTags(e){let t=new Set(e),n=0;return await this.visitNamespace(e=>e.tags?.some(e=>t.has(e))?(n+=1,!0):!1),n}async clear(){await this.visitNamespace(()=>!0)}async getUsage(){let e=(await this.getDatabase()).transaction(u,`readonly`),t=waitForTransaction(e),n=e.objectStore(u).index(d).openCursor(this.namespace),r=0,i=0;return await visitCursor(n,e=>{let t=e.value;isValidIndexedDBRecord(t,this.namespace,void 0,this.schemaVersion)&&(r+=1,i=addSizes(i,readIndexedDBRecordSize(t)))}),await t,{entries:r,estimatedBytes:i,maxEntries:this.maxEntries,maxBytes:this.maxBytes,schemaVersion:this.schemaVersion}}async compact(e={}){let t=normalizeCompactionBoundary(e.expiredBefore),n=normalizeCompactionMaxRemovals(e.maxRemovals),r=(await this.getDatabase()).transaction(u,`readwrite`),i=waitForTransaction(r),a=r.objectStore(u).index(d).openCursor(this.namespace),o=new Map,s=0,c=0,l=0,f=!1;return await visitCursor(a,e=>{let r=e.value,i=classifyIndexedDBRecord(r,this.namespace,this.schemaVersion);if(s+=1,i===`malformed`||i===`schema-version`)e.delete(),addCleanupSummary(o,i,r),c+=1,l=addSizes(l,readIndexedDBRecordSize(r));else if(i===`current`&&r.expiresAt<=t){let t=readIndexedDBRecordSize(r);e.delete(),addCleanupSummary(o,`expired`,r),c+=1,l=addSizes(l,t)}if(c>=n)return f=!0,!1}),await i,this.emitCleanupSummaries(o.values()),{scannedEntries:s,removedEntries:c,estimatedBytesFreed:l,expiredBefore:t,hasMore:f}}async close(){let e=this.database;e&&(this.database=void 0,(await e).close())}createKey(e){return this.schemaVersion===1?`${this.namespace}\0${e}`:`${this.namespace}\0@npora-schema:${this.schemaVersion}\0${e}`}async writeRecord(e,t){let n=e.transaction(u,`readwrite`),r=waitForTransaction(n),i=n.objectStore(u),a=new Map;if(isFutureIndexedDBRecord(await waitForRequest(i.get(t.key)),this.schemaVersion)){await r;return}if(i.put(t),this.maxEntries!==1/0||this.maxBytes!==1/0){let e=await waitForRequest(i.index(d).getAll(this.namespace)),n=[];for(let t of e){let e=classifyIndexedDBRecord(t,this.namespace,this.schemaVersion);e===`malformed`||e===`schema-version`?(i.delete(t.key),addCleanupSummary(a,e,t)):e===`current`&&n.push(t)}n.sort((e,n)=>e.key===t.key?1:n.key===t.key?-1:e.accessedAt-n.accessedAt||e.key.localeCompare(n.key));let r=n.reduce((e,t)=>addSizes(e,readIndexedDBRecordSize(t)),0),o=n.length;for(let e of n){if(o<=this.maxEntries&&r<=this.maxBytes)break;i.delete(e.key),addCleanupSummary(a,r>this.maxBytes?`max-bytes`:`max-entries`,e),--o,r=Math.max(0,r-readIndexedDBRecordSize(e))}}await r,this.emitCleanupSummaries(a.values())}async recoverQuota(e){let t=e.transaction(u,`readwrite`),n=waitForTransaction(t),r=t.objectStore(u),i=await waitForRequest(r.index(d).getAll(this.namespace)),a=[],o=new Map,s=!1;for(let e of i){let t=classifyIndexedDBRecord(e,this.namespace,this.schemaVersion);t===`malformed`||t===`schema-version`?(r.delete(e.key),addCleanupSummary(o,t,e),s=!0):t===`current`&&a.push(e)}a.sort((e,t)=>e.accessedAt-t.accessedAt||e.key.localeCompare(t.key));for(let e of a.slice(0,Math.max(1,Math.ceil(a.length/2))))r.delete(e.key),addCleanupSummary(o,`quota-recovery`,e),s=!0;return await n,this.emitCleanupSummaries(o.values()),s}emitCleanupSummaries(e){for(let t of e)this.emitEvent({type:`eviction`,...t})}emitEvent(e){if(this.onEvent)try{Promise.resolve(this.onEvent({...e,timestamp:Date.now()})).catch(()=>{})}catch{}}async visitNamespace(e){let t=(await this.getDatabase()).transaction(u,`readwrite`),n=waitForTransaction(t),r=t.objectStore(u).index(d).openCursor(this.namespace),i=new Map;await visitCursor(r,t=>{let n=t.value,r=classifyIndexedDBRecord(n,this.namespace,this.schemaVersion);(r===`malformed`||r===`schema-version`||r===`current`&&e(n))&&(t.delete(),(r===`malformed`||r===`schema-version`)&&addCleanupSummary(i,r,n))}),await n,this.emitCleanupSummaries(i.values())}getDatabase(){return this.database??(this.database=openCacheDatabase(this.factory,this.databaseName).then(async e=>{try{let t=await pruneOlderSchemaRecords(e,this.namespace,this.schemaVersion);return this.emitCleanupSummaries(t),e}catch(t){throw e.close(),t}})),this.database}};function openCacheDatabase(e,t){return new Promise((n,r)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(u)||e.createObjectStore(u,{keyPath:`key`}).createIndex(d,d,{unique:!1})},i.onerror=()=>r(i.error),i.onsuccess=()=>{let e=i.result;e.onversionchange=()=>e.close(),n(e)}})}function waitForRequest(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)})}function waitForTransaction(e){let t=new Promise((t,n)=>{let rejectWithTransactionError=t=>{n(e.error??readIDBRequestError(t.target)??Error(`IndexedDB transaction failed`))};e.onabort=rejectWithTransactionError,e.onerror=rejectWithTransactionError,e.oncomplete=()=>t()});return t.catch(()=>{}),t}function readIDBRequestError(e){if(!e||!(`error`in e))return null;let t=e.error;return t instanceof DOMException?t:null}function visitCursor(e,t){return new Promise((n,r)=>{e.onerror=()=>r(e.error),e.onsuccess=()=>{let i=e.result;if(!i){n();return}try{if(t(i)===!1){n();return}}catch(t){try{readCursorTransaction(e)?.abort()}catch{}r(t);return}i.continue()}})}function readCursorTransaction(e){let t=e.source;if(t)return`transaction`in t?t.transaction:`objectStore`in t?t.objectStore.transaction:`transaction`in t.source?t.source.transaction:t.source.objectStore.transaction}function toPortableCacheEntry(e){return{data:e.data,expiresAt:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags}}function isValidIndexedDBRecord(e,t,n,r=1){if(!e||typeof e!=`object`)return!1;let i=e;if(!(typeof i.key==`string`&&(n===void 0||i.key===n)&&i.namespace===t&&readIndexedDBSchemaVersion(i)===r&&(i.expiresAt===1/0||Number.isFinite(i.expiresAt))&&Number.isInteger(i.status)&&i.status>=200&&i.status<=599&&typeof i.statusText==`string`&&Array.isArray(i.headers)&&(i.tags===void 0||Array.isArray(i.tags)&&i.tags.length<=32&&i.tags.every(e=>typeof e==`string`&&e.length>0&&e.length<=128))&&Number.isFinite(i.accessedAt)))return!1;try{return new Headers(i.headers),!0}catch{return!1}}function readIndexedDBSchemaVersion(e){if(!e||typeof e!=`object`)return;let t=e.schemaVersion??1;return Number.isSafeInteger(t)&&t>=1&&t<=1e9?t:void 0}function classifyIndexedDBRecord(e,t,n){let r=readIndexedDBSchemaVersion(e);return r===void 0?`malformed`:r>n?`future`:r<n?`schema-version`:isValidIndexedDBRecord(e,t,void 0,n)?`current`:`malformed`}function isFutureIndexedDBRecord(e,t){let n=readIndexedDBSchemaVersion(e);return n!==void 0&&n>t}function readIndexedDBRecordSize(e){let t=e&&typeof e==`object`?e.size:void 0;return Number.isSafeInteger(t)&&t>=0?t:estimateStructuredCloneSize(e)}function estimateStructuredCloneSize(e,n=new WeakSet){if(e==null)return 0;if(typeof e==`string`)return Math.min(2**53-1,e.length*2);if(typeof e==`number`||typeof e==`bigint`)return 8;if(typeof e==`boolean`)return 4;if(typeof e!=`object`)return 0;if(n.has(e)||(n.add(e),e instanceof Date))return 8;if(t.n(e))return e.size;if(t.t(e)||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Map){let t=16;for(let[r,i]of e)t=addSizes(t,estimateStructuredCloneSize(r,n),estimateStructuredCloneSize(i,n));return t}if(e instanceof Set){let t=16;for(let r of e)t=addSizes(t,estimateStructuredCloneSize(r,n));return t}let r=Array.isArray(e)?16:32;for(let[t,i]of Object.entries(e))r=addSizes(r,t.length*2,estimateStructuredCloneSize(i,n));return r}function addSizes(...e){let t=0;for(let n of e){if(n>=2**53-1-t)return 2**53-1;t+=n}return t}function addCleanupSummary(e,t,n){let r=e.get(t),i=readIndexedDBRecordSize(n);if(r){r.entries+=1,r.estimatedBytes=addSizes(r.estimatedBytes,i);return}e.set(t,{reason:t,entries:1,estimatedBytes:i})}function isQuotaExceededError(e){return!!(e&&typeof e==`object`&&e.name===`QuotaExceededError`)}async function pruneOlderSchemaRecords(e,t,n){let r=e.transaction(u,`readwrite`),i=waitForTransaction(r),a=r.objectStore(u).index(d).openCursor(t),o=new Map;return await visitCursor(a,e=>{let r=e.value,i=classifyIndexedDBRecord(r,t,n);(i===`malformed`||i===`schema-version`)&&(e.delete(),addCleanupSummary(o,i,r))}),await i,[...o.values()]}function normalizeIndexedDBName(t,n,r){let i=t??r;if(typeof i!=`string`||i.length===0||i.length>128)throw new e.t(`IndexedDB cache ${n} must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return i}function normalizeIndexedDBMaxEntries(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function normalizeIndexedDBMaxBytes(t){if(t===void 0)return 1/0;if(t===1/0)return t;if(!Number.isSafeInteger(t)||t<0)throw new e.t(`IndexedDB cache maxBytes must be a non-negative safe integer or Infinity`,{code:`CONFIG_ERROR`});return t}function normalizeQuotaRecovery(t){if(t===void 0)return!0;if(typeof t!=`boolean`)throw new e.t(`IndexedDB cache quotaRecovery must be a boolean`,{code:`CONFIG_ERROR`});return t}function normalizeIndexedDBEventObserver(t){if(t!==void 0&&typeof t!=`function`)throw new e.t(`IndexedDB cache onEvent must be a function`,{code:`CONFIG_ERROR`});return t}function normalizeIndexedDBAdmissionPolicy(t){if(t!==void 0&&typeof t!=`function`)throw new e.t(`IndexedDB cache shouldPersist must be a function`,{code:`CONFIG_ERROR`});return t}function normalizeCompactionBoundary(t){let n=t??Date.now();if(!Number.isFinite(n))throw new e.t(`IndexedDB cache compact expiredBefore must be finite`,{code:`CONFIG_ERROR`});return n}function normalizeCompactionMaxRemovals(t){if(t===void 0||t===1/0)return 1/0;if(!Number.isSafeInteger(t)||t<1)throw new e.t(`IndexedDB cache compact maxRemovals must be a positive safe integer or Infinity`,{code:`CONFIG_ERROR`});return t}function normalizeIndexedDBSchemaVersion(t){let n=t??1;if(!Number.isSafeInteger(n)||n<1||n>1e9)throw new e.t(`IndexedDB cache schemaVersion must be an integer from 1 to 1000000000`,{code:`CONFIG_ERROR`});return n}var TieredCacheStore=class{constructor(t){if(this.leaseReleases=new Set,this.source=`${Date.now()}:${Math.random()}`,this.trackedKeys=new Map,this.trackedKeyCount=0,this.handleMessage=e=>{let t=e.data;if(!isTieredCacheMessage(t)||t.source===this.source)return;if(t.action===`clear`){this.clearPrimary();return}let n=this.trackedKeys.get(t.fingerprint);if(!n){this.clearPrimary();return}this.trackedKeys.delete(t.fingerprint),this.trackedKeyCount-=n.size;for(let e of n)ignoreStoreResult(()=>this.primary.delete(e))},!t||!t.primary||!t.secondary||t.primary===t.secondary)throw new e.t(`Tiered cache requires distinct primary and secondary stores`,{code:`CONFIG_ERROR`});if(this.primary=t.primary,this.secondary=t.secondary,t.broadcast&&!t.broadcast.channel)throw new e.t(`Tiered cache broadcast requires a channel`,{code:`CONFIG_ERROR`});if(t.coordination&&!t.coordination.locks)throw new e.t(`Tiered cache coordination requires a lock manager`,{code:`CONFIG_ERROR`});this.channel=t.broadcast?.channel,this.locks=t.coordination?.locks,this.lockNamespace=normalizeLockNamespace(t.coordination?.namespace),this.maxTrackedKeys=normalizeTrackedKeys(t.broadcast?.maxTrackedKeys),this.locks&&(this.acquireRefreshLease=(e,t)=>this.acquireCoordinatedLease(e,t)),this.channel?.addEventListener(`message`,this.handleMessage)}get(e){let t;try{t=this.primary.get(e)}catch{return this.readSecondary(e)}return n.t(t)?Promise.resolve(t).then(t=>t?this.remember(e,t):this.readSecondary(e),()=>this.readSecondary(e)):t?this.remember(e,t):this.readSecondary(e)}set(e,t){let writePrimary=()=>{let r;try{r=this.primary.set(e,t)}catch(t){throw this.recoverPrimaryWrite(e),t}return n.t(r)?Promise.resolve(r).catch(t=>{throw this.recoverPrimaryWrite(e),t}):r},r=this.secondary.set(e,t),i=n.t(r)?Promise.resolve(r).then(writePrimary):writePrimary();return this.afterSuccess(i,()=>{this.trackKey(e),this.broadcastKey(e)})}delete(e){return this.afterSettled(()=>combineStoreOperations([()=>this.primary.delete(e),()=>this.secondary.delete(e)],()=>void 0),()=>{this.untrackKey(e),this.broadcastKey(e)})}invalidateTags(t){let n=this.primary.invalidateTags,r=this.secondary.invalidateTags;if(!n||!r)throw new e.t(`Both tiered cache stores must support tag invalidation`,{code:`CONFIG_ERROR`});return this.afterSettled(()=>combineStoreOperations([()=>n.call(this.primary,t),()=>r.call(this.secondary,t)],e=>Math.max(...e)),()=>this.broadcastClear())}clear(){return this.afterSettled(()=>combineStoreOperations([()=>this.primary.clear(),()=>this.secondary.clear()],()=>void 0),()=>this.broadcastClear())}async acquireCoordinatedLease(t,n){let r=`${this.lockNamespace}:${fingerprintCacheKey(t)}`,i=await this.requestLease(r,!0,n);if(i)return i;let a=await this.requestLease(r,!1,n);if(!a)throw new e.t(`Cache refresh lock was unavailable`,{code:`NETWORK_ERROR`});return await ignoreStoreFailure(()=>this.primary.delete(t)),a}dispose(){this.channel?.removeEventListener(`message`,this.handleMessage);for(let e of this.leaseReleases)e();this.leaseReleases.clear(),this.trackedKeys.clear(),this.trackedKeyCount=0}requestLease(e,t,n){return new Promise((r,i)=>{let a=!1,o=createDeferred(),s={mode:`exclusive`,ifAvailable:t};n&&(s.signal=n),this.locks.request(e,s,async e=>{if(!e){a=!0,r(void 0);return}let n=!0,release=()=>{n&&(n=!1,this.leaseReleases.delete(release),o.resolve())};this.leaseReleases.add(release),a=!0,r({contended:!t,release}),await o.promise}).catch(e=>{a||i(e)})})}readSecondary(e){let promote=t=>{if(t){try{let r=this.primary.set(e,t);if(n.t(r))return Promise.resolve(r).then(()=>this.remember(e,t),()=>this.remember(e,t))}catch{}return this.remember(e,t)}},t=this.secondary.get(e);return n.t(t)?Promise.resolve(t).then(promote):promote(t)}remember(e,t){return this.trackKey(e),t}trackKey(e){if(!this.channel)return;let t=fingerprintCacheKey(e),n=this.trackedKeys.get(t);if(n?.has(e)){this.trackedKeys.delete(t),this.trackedKeys.set(t,n);return}for(;this.trackedKeyCount>=this.maxTrackedKeys;){let e=this.trackedKeys.entries().next().value;if(!e)break;this.trackedKeys.delete(e[0]),this.trackedKeyCount-=e[1].size}n??(n=new Set),n.add(e),this.trackedKeys.delete(t),this.trackedKeys.set(t,n),this.trackedKeyCount+=1}untrackKey(e){let t=fingerprintCacheKey(e),n=this.trackedKeys.get(t);n?.delete(e)&&(--this.trackedKeyCount,n.size===0&&this.trackedKeys.delete(t))}broadcastKey(e){this.postMessage({protocol:`npora-cache:1`,source:this.source,action:`delete`,fingerprint:fingerprintCacheKey(e)})}broadcastClear(){this.trackedKeys.clear(),this.trackedKeyCount=0,this.postMessage({protocol:`npora-cache:1`,source:this.source,action:`clear`})}postMessage(e){try{this.channel?.postMessage(e)}catch{}}clearPrimary(){this.trackedKeys.clear(),this.trackedKeyCount=0,ignoreStoreResult(()=>this.primary.clear())}recoverPrimaryWrite(e){this.untrackKey(e),ignoreStoreResult(()=>this.primary.delete(e)),this.broadcastKey(e)}afterSuccess(e,t){return n.t(e)?Promise.resolve(e).then(e=>(t(),e)):(t(),e)}afterSettled(e,t){let r;try{r=e()}catch(e){throw t(),e}return n.t(r)?Promise.resolve(r).then(e=>(t(),e),e=>{throw t(),e}):(t(),r)}};function combineStoreOperations(e,t){let r=[],i=[],a,o=!1;for(let t of e)try{let e=t();n.t(e)?i.push(Promise.resolve(e).then(e=>{r.push(e)},e=>{o||(o=!0,a=e)})):r.push(e)}catch(e){o||(o=!0,a=e)}let finish=()=>{if(o)throw a;return t(r)};return i.length>0?Promise.all(i).then(finish):finish()}function fingerprintCacheKey(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function isTieredCacheMessage(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.protocol===`npora-cache:1`&&typeof t.source==`string`&&(t.action===`clear`||t.action===`delete`&&typeof t.fingerprint==`string`&&t.fingerprint.length<=16)}function normalizeTrackedKeys(t){let n=t??1e3;if(!Number.isInteger(n)||n<1||n>1e5)throw new e.t(`Tiered cache maxTrackedKeys must be an integer from 1 to 100000`,{code:`CONFIG_ERROR`});return n}function normalizeLockNamespace(t){let n=t??`npora-cache`;if(typeof n!=`string`||n.length<1||n.length>128)throw new e.t(`Tiered cache lock namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return n}function createDeferred(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}function ignoreStoreResult(e){try{let t=e();n.t(t)&&Promise.resolve(t).catch(()=>{})}catch{}}async function ignoreStoreFailure(e){try{await e()}catch{}}function cachePlugin(e={}){let t=createCacheState(e),n={name:`cache`,...createCacheMutations(t),install(r){let i=createCacheInstallation();return r.hooks.onRequest(createCacheRequestHandler(t,i,r,e)),r.hooks.onResponse(createCacheResponseHandler(t),{requiresRawResponse:!1}),r.hooks.onError(createCacheErrorHandler(t)),r.hooks.onSettled(createCacheSettledHandler(t,i,n)),createCacheCleanup(t,i)}};return n}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return WebStorageCacheStore}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return MemoryCacheStore}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return TieredCacheStore}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return IndexedDBCacheStore}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return cachePlugin}});
@@ -68,6 +68,90 @@ declare class WebStorageCacheStore implements CacheStore {
68
68
  private read;
69
69
  }
70
70
  //#endregion
71
+ //#region src/plugins/cacheTypes.d.ts
72
+ interface CachePluginOptions {
73
+ /**
74
+ * HTTP methods that may be cached.
75
+ *
76
+ * @default GET and HEAD
77
+ */
78
+ methods?: readonly HttpMethod[];
79
+ /**
80
+ * Additional request headers included in the default cache key.
81
+ * All explicitly configured request headers are included automatically.
82
+ *
83
+ * @default authorization, cookie, accept and accept-language
84
+ */
85
+ varyHeaders?: readonly string[];
86
+ /**
87
+ * Cache storage shared by this plugin instance.
88
+ *
89
+ * @default an isolated MemoryCacheStore
90
+ */
91
+ store?: CacheStore;
92
+ /**
93
+ * Maximum entries retained by the default MemoryCacheStore.
94
+ * Ignored when `store` is provided.
95
+ *
96
+ * @default 1000
97
+ */
98
+ maxEntries?: number;
99
+ /**
100
+ * Share one network operation between concurrent equivalent requests.
101
+ *
102
+ * @default true
103
+ */
104
+ dedupe?: boolean;
105
+ /**
106
+ * Observe cache decisions without receiving cache keys, URLs or headers.
107
+ * Callback failures are isolated from requests.
108
+ */
109
+ onEvent?: (event: CacheEvent) => void | Promise<void>;
110
+ }
111
+ interface CachePlugin extends Plugin {
112
+ clear(): MaybePromise$1<void>;
113
+ /** Delete the entry matching an effective request configuration. */
114
+ delete(config: RequestConfig): MaybePromise$1<void>;
115
+ /** Store parsed response data for an effective request configuration. */
116
+ set<T>(config: RequestConfig, data: T, options?: CacheSetOptions): MaybePromise$1<void>;
117
+ /** Update or delete an existing parsed cache value. */
118
+ update<T>(config: RequestConfig, updater: (data: T) => T | undefined): MaybePromise$1<boolean>;
119
+ /** Delete entries carrying any of the supplied tags. */
120
+ invalidateTags(tags: string | readonly string[]): MaybePromise$1<number>;
121
+ getStats(): Readonly<CacheStats>;
122
+ resetStats(): void;
123
+ }
124
+ interface CacheSetOptions {
125
+ /** Freshness lifetime in milliseconds. */
126
+ ttl?: number;
127
+ /** Cached HTTP status. @default 200 */
128
+ status?: number;
129
+ /** Cached HTTP status text. @default OK */
130
+ statusText?: string;
131
+ headers?: HeadersInit;
132
+ /** Tags assigned to the entry. */
133
+ tags?: readonly string[];
134
+ }
135
+ type CacheEventType = 'hit' | 'miss' | 'bypass' | 'invalidated' | 'invalidation-error' | 'deduplicated' | 'revalidated' | 'stale-if-error' | 'stale-while-revalidate' | 'background-refresh' | 'background-refresh-success' | 'background-refresh-error';
136
+ interface CacheEvent {
137
+ type: CacheEventType;
138
+ timestamp: number;
139
+ }
140
+ interface CacheStats {
141
+ hits: number;
142
+ misses: number;
143
+ bypasses: number;
144
+ invalidations: number;
145
+ invalidationErrors: number;
146
+ deduplicated: number;
147
+ revalidations: number;
148
+ staleIfError: number;
149
+ staleWhileRevalidate: number;
150
+ backgroundRefreshes: number;
151
+ backgroundRefreshSuccesses: number;
152
+ backgroundRefreshErrors: number;
153
+ }
154
+ //#endregion
71
155
  //#region src/plugins/indexedDBCacheStore.d.ts
72
156
  interface IndexedDBCacheStoreOptions {
73
157
  /** Database shared by cache namespaces. @default @npora/request-cache */
@@ -212,88 +296,6 @@ declare class TieredCacheStore implements CacheStore {
212
296
  }
213
297
  //#endregion
214
298
  //#region src/plugins/cachePlugin.d.ts
215
- interface CachePluginOptions {
216
- /**
217
- * HTTP methods that may be cached.
218
- *
219
- * @default GET and HEAD
220
- */
221
- methods?: readonly HttpMethod[];
222
- /**
223
- * Additional request headers included in the default cache key.
224
- * All explicitly configured request headers are included automatically.
225
- *
226
- * @default authorization, cookie, accept and accept-language
227
- */
228
- varyHeaders?: readonly string[];
229
- /**
230
- * Cache storage shared by this plugin instance.
231
- *
232
- * @default an isolated MemoryCacheStore
233
- */
234
- store?: CacheStore;
235
- /**
236
- * Maximum entries retained by the default MemoryCacheStore.
237
- * Ignored when `store` is provided.
238
- *
239
- * @default 1000
240
- */
241
- maxEntries?: number;
242
- /**
243
- * Share one network operation between concurrent equivalent requests.
244
- *
245
- * @default true
246
- */
247
- dedupe?: boolean;
248
- /**
249
- * Observe cache decisions without receiving cache keys, URLs or headers.
250
- * Callback failures are isolated from requests.
251
- */
252
- onEvent?: (event: CacheEvent) => void | Promise<void>;
253
- }
254
- interface CachePlugin extends Plugin {
255
- clear(): MaybePromise$1<void>;
256
- /** Delete the entry matching an effective request configuration. */
257
- delete(config: RequestConfig): MaybePromise$1<void>;
258
- /** Store parsed response data for an effective request configuration. */
259
- set<T>(config: RequestConfig, data: T, options?: CacheSetOptions): MaybePromise$1<void>;
260
- /** Update or delete an existing parsed cache value. */
261
- update<T>(config: RequestConfig, updater: (data: T) => T | undefined): MaybePromise$1<boolean>;
262
- /** Delete entries carrying any of the supplied tags. */
263
- invalidateTags(tags: string | readonly string[]): MaybePromise$1<number>;
264
- getStats(): Readonly<CacheStats>;
265
- resetStats(): void;
266
- }
267
- interface CacheSetOptions {
268
- /** Freshness lifetime in milliseconds. */
269
- ttl?: number;
270
- /** Cached HTTP status. @default 200 */
271
- status?: number;
272
- /** Cached HTTP status text. @default OK */
273
- statusText?: string;
274
- headers?: HeadersInit;
275
- /** Tags assigned to the entry. */
276
- tags?: readonly string[];
277
- }
278
- type CacheEventType = 'hit' | 'miss' | 'bypass' | 'invalidated' | 'invalidation-error' | 'deduplicated' | 'revalidated' | 'stale-if-error' | 'stale-while-revalidate' | 'background-refresh' | 'background-refresh-success' | 'background-refresh-error';
279
- interface CacheEvent {
280
- type: CacheEventType;
281
- timestamp: number;
282
- }
283
- interface CacheStats {
284
- hits: number;
285
- misses: number;
286
- bypasses: number;
287
- invalidations: number;
288
- invalidationErrors: number;
289
- deduplicated: number;
290
- revalidations: number;
291
- staleIfError: number;
292
- staleWhileRevalidate: number;
293
- backgroundRefreshes: number;
294
- backgroundRefreshSuccesses: number;
295
- backgroundRefreshErrors: number;
296
- }
297
299
  declare function cachePlugin(options?: CachePluginOptions): CachePlugin;
298
300
  //#endregion
299
- export { WebStorageCacheStore as C, MemoryCacheStoreOptions as S, IndexedDBCacheUsage as _, CacheSetOptions as a, CacheStore as b, TieredCacheBroadcastOptions as c, TieredCacheStoreOptions as d, IndexedDBCacheCompactionOptions as f, IndexedDBCacheStoreOptions as g, IndexedDBCacheStoreEvent as h, CachePluginOptions as i, TieredCacheCoordinationOptions as l, IndexedDBCacheStore as m, CacheEventType as n, CacheStats as o, IndexedDBCacheCompactionResult as p, CachePlugin as r, cachePlugin as s, CacheEvent as t, TieredCacheStore as u, CacheEntry as v, WebStorageCacheStoreOptions as w, MemoryCacheStore as x, CacheRefreshLease as y };
301
+ export { WebStorageCacheStore as C, MemoryCacheStoreOptions as S, CacheStats as _, TieredCacheStoreOptions as a, CacheStore as b, IndexedDBCacheStore as c, IndexedDBCacheUsage as d, CacheEvent as f, CacheSetOptions as g, CachePluginOptions as h, TieredCacheStore as i, IndexedDBCacheStoreEvent as l, CachePlugin as m, TieredCacheBroadcastOptions as n, IndexedDBCacheCompactionOptions as o, CacheEventType as p, TieredCacheCoordinationOptions as r, IndexedDBCacheCompactionResult as s, cachePlugin as t, IndexedDBCacheStoreOptions as u, CacheEntry as v, WebStorageCacheStoreOptions as w, MemoryCacheStore as x, CacheRefreshLease as y };
@@ -68,6 +68,90 @@ declare class WebStorageCacheStore implements CacheStore {
68
68
  private read;
69
69
  }
70
70
  //#endregion
71
+ //#region src/plugins/cacheTypes.d.ts
72
+ interface CachePluginOptions {
73
+ /**
74
+ * HTTP methods that may be cached.
75
+ *
76
+ * @default GET and HEAD
77
+ */
78
+ methods?: readonly HttpMethod[];
79
+ /**
80
+ * Additional request headers included in the default cache key.
81
+ * All explicitly configured request headers are included automatically.
82
+ *
83
+ * @default authorization, cookie, accept and accept-language
84
+ */
85
+ varyHeaders?: readonly string[];
86
+ /**
87
+ * Cache storage shared by this plugin instance.
88
+ *
89
+ * @default an isolated MemoryCacheStore
90
+ */
91
+ store?: CacheStore;
92
+ /**
93
+ * Maximum entries retained by the default MemoryCacheStore.
94
+ * Ignored when `store` is provided.
95
+ *
96
+ * @default 1000
97
+ */
98
+ maxEntries?: number;
99
+ /**
100
+ * Share one network operation between concurrent equivalent requests.
101
+ *
102
+ * @default true
103
+ */
104
+ dedupe?: boolean;
105
+ /**
106
+ * Observe cache decisions without receiving cache keys, URLs or headers.
107
+ * Callback failures are isolated from requests.
108
+ */
109
+ onEvent?: (event: CacheEvent) => void | Promise<void>;
110
+ }
111
+ interface CachePlugin extends Plugin {
112
+ clear(): MaybePromise$1<void>;
113
+ /** Delete the entry matching an effective request configuration. */
114
+ delete(config: RequestConfig): MaybePromise$1<void>;
115
+ /** Store parsed response data for an effective request configuration. */
116
+ set<T>(config: RequestConfig, data: T, options?: CacheSetOptions): MaybePromise$1<void>;
117
+ /** Update or delete an existing parsed cache value. */
118
+ update<T>(config: RequestConfig, updater: (data: T) => T | undefined): MaybePromise$1<boolean>;
119
+ /** Delete entries carrying any of the supplied tags. */
120
+ invalidateTags(tags: string | readonly string[]): MaybePromise$1<number>;
121
+ getStats(): Readonly<CacheStats>;
122
+ resetStats(): void;
123
+ }
124
+ interface CacheSetOptions {
125
+ /** Freshness lifetime in milliseconds. */
126
+ ttl?: number;
127
+ /** Cached HTTP status. @default 200 */
128
+ status?: number;
129
+ /** Cached HTTP status text. @default OK */
130
+ statusText?: string;
131
+ headers?: HeadersInit;
132
+ /** Tags assigned to the entry. */
133
+ tags?: readonly string[];
134
+ }
135
+ type CacheEventType = 'hit' | 'miss' | 'bypass' | 'invalidated' | 'invalidation-error' | 'deduplicated' | 'revalidated' | 'stale-if-error' | 'stale-while-revalidate' | 'background-refresh' | 'background-refresh-success' | 'background-refresh-error';
136
+ interface CacheEvent {
137
+ type: CacheEventType;
138
+ timestamp: number;
139
+ }
140
+ interface CacheStats {
141
+ hits: number;
142
+ misses: number;
143
+ bypasses: number;
144
+ invalidations: number;
145
+ invalidationErrors: number;
146
+ deduplicated: number;
147
+ revalidations: number;
148
+ staleIfError: number;
149
+ staleWhileRevalidate: number;
150
+ backgroundRefreshes: number;
151
+ backgroundRefreshSuccesses: number;
152
+ backgroundRefreshErrors: number;
153
+ }
154
+ //#endregion
71
155
  //#region src/plugins/indexedDBCacheStore.d.ts
72
156
  interface IndexedDBCacheStoreOptions {
73
157
  /** Database shared by cache namespaces. @default @npora/request-cache */
@@ -212,88 +296,6 @@ declare class TieredCacheStore implements CacheStore {
212
296
  }
213
297
  //#endregion
214
298
  //#region src/plugins/cachePlugin.d.ts
215
- interface CachePluginOptions {
216
- /**
217
- * HTTP methods that may be cached.
218
- *
219
- * @default GET and HEAD
220
- */
221
- methods?: readonly HttpMethod[];
222
- /**
223
- * Additional request headers included in the default cache key.
224
- * All explicitly configured request headers are included automatically.
225
- *
226
- * @default authorization, cookie, accept and accept-language
227
- */
228
- varyHeaders?: readonly string[];
229
- /**
230
- * Cache storage shared by this plugin instance.
231
- *
232
- * @default an isolated MemoryCacheStore
233
- */
234
- store?: CacheStore;
235
- /**
236
- * Maximum entries retained by the default MemoryCacheStore.
237
- * Ignored when `store` is provided.
238
- *
239
- * @default 1000
240
- */
241
- maxEntries?: number;
242
- /**
243
- * Share one network operation between concurrent equivalent requests.
244
- *
245
- * @default true
246
- */
247
- dedupe?: boolean;
248
- /**
249
- * Observe cache decisions without receiving cache keys, URLs or headers.
250
- * Callback failures are isolated from requests.
251
- */
252
- onEvent?: (event: CacheEvent) => void | Promise<void>;
253
- }
254
- interface CachePlugin extends Plugin {
255
- clear(): MaybePromise$1<void>;
256
- /** Delete the entry matching an effective request configuration. */
257
- delete(config: RequestConfig): MaybePromise$1<void>;
258
- /** Store parsed response data for an effective request configuration. */
259
- set<T>(config: RequestConfig, data: T, options?: CacheSetOptions): MaybePromise$1<void>;
260
- /** Update or delete an existing parsed cache value. */
261
- update<T>(config: RequestConfig, updater: (data: T) => T | undefined): MaybePromise$1<boolean>;
262
- /** Delete entries carrying any of the supplied tags. */
263
- invalidateTags(tags: string | readonly string[]): MaybePromise$1<number>;
264
- getStats(): Readonly<CacheStats>;
265
- resetStats(): void;
266
- }
267
- interface CacheSetOptions {
268
- /** Freshness lifetime in milliseconds. */
269
- ttl?: number;
270
- /** Cached HTTP status. @default 200 */
271
- status?: number;
272
- /** Cached HTTP status text. @default OK */
273
- statusText?: string;
274
- headers?: HeadersInit;
275
- /** Tags assigned to the entry. */
276
- tags?: readonly string[];
277
- }
278
- type CacheEventType = 'hit' | 'miss' | 'bypass' | 'invalidated' | 'invalidation-error' | 'deduplicated' | 'revalidated' | 'stale-if-error' | 'stale-while-revalidate' | 'background-refresh' | 'background-refresh-success' | 'background-refresh-error';
279
- interface CacheEvent {
280
- type: CacheEventType;
281
- timestamp: number;
282
- }
283
- interface CacheStats {
284
- hits: number;
285
- misses: number;
286
- bypasses: number;
287
- invalidations: number;
288
- invalidationErrors: number;
289
- deduplicated: number;
290
- revalidations: number;
291
- staleIfError: number;
292
- staleWhileRevalidate: number;
293
- backgroundRefreshes: number;
294
- backgroundRefreshSuccesses: number;
295
- backgroundRefreshErrors: number;
296
- }
297
299
  declare function cachePlugin(options?: CachePluginOptions): CachePlugin;
298
300
  //#endregion
299
- export { WebStorageCacheStore as C, MemoryCacheStoreOptions as S, IndexedDBCacheUsage as _, CacheSetOptions as a, CacheStore as b, TieredCacheBroadcastOptions as c, TieredCacheStoreOptions as d, IndexedDBCacheCompactionOptions as f, IndexedDBCacheStoreOptions as g, IndexedDBCacheStoreEvent as h, CachePluginOptions as i, TieredCacheCoordinationOptions as l, IndexedDBCacheStore as m, CacheEventType as n, CacheStats as o, IndexedDBCacheCompactionResult as p, CachePlugin as r, cachePlugin as s, CacheEvent as t, TieredCacheStore as u, CacheEntry as v, WebStorageCacheStoreOptions as w, MemoryCacheStore as x, CacheRefreshLease as y };
301
+ export { WebStorageCacheStore as C, MemoryCacheStoreOptions as S, CacheStats as _, TieredCacheStoreOptions as a, CacheStore as b, IndexedDBCacheStore as c, IndexedDBCacheUsage as d, CacheEvent as f, CacheSetOptions as g, CachePluginOptions as h, TieredCacheStore as i, IndexedDBCacheStoreEvent as l, CachePlugin as m, TieredCacheBroadcastOptions as n, IndexedDBCacheCompactionOptions as o, CacheEventType as p, TieredCacheCoordinationOptions as r, IndexedDBCacheCompactionResult as s, cachePlugin as t, IndexedDBCacheStoreOptions as u, CacheEntry as v, WebStorageCacheStoreOptions as w, MemoryCacheStore as x, CacheRefreshLease as y };
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./RequestError-DrCr_lwO.cjs"),t=require("./validateResponseStatus-CYU2N49m.cjs"),n=require("./createClient-ICkQQqcE.cjs"),r=require("./testing.cjs"),i=require("./PluginError-DT3VnlUB.cjs"),a=require("./plugins/auth.cjs"),o=require("./cachePlugin-ComdU-Tb.cjs"),s=require("./plugins/circuit-breaker.cjs"),c=require("./plugins/concurrency.cjs"),l=require("./plugins/download.cjs"),u=require("./plugins/logger.cjs"),d=require("./plugins/opentelemetry.cjs"),f=require("./plugins/opentelemetry-metrics.cjs"),p=require("./rateLimitPlugin-CtwD8U0P.cjs"),m=require("./plugins/retry.cjs"),h=require("./plugins/upload.cjs");require("./plugins.cjs"),exports.Client=n.n,exports.FetchAdapter=n.i,exports.IndexedDBCacheStore=o.r,exports.InterceptorManager=n.r,exports.MemoryCacheStore=o.i,exports.MockAdapter=r.MockAdapter,exports.PluginError=i.t,exports.RequestError=e.t,exports.SchemaValidationError=t.d,exports.TieredCacheStore=o.n,exports.WebStorageCacheStore=o.a,exports.authPlugin=a.authPlugin,exports.cachePlugin=o.t,exports.circuitBreakerPlugin=s.circuitBreakerPlugin,exports.concurrencyPlugin=c.concurrencyPlugin,exports.createClient=n.t,exports.downloadPlugin=l.downloadPlugin,exports.isRequestError=e.n,exports.isSchemaValidationError=t.f,exports.loggerPlugin=u.loggerPlugin,exports.openTelemetryMetricsPlugin=f.openTelemetryMetricsPlugin,exports.openTelemetryPlugin=d.openTelemetryPlugin,exports.rateLimitPlugin=p.t,exports.retryPlugin=m.retryPlugin,exports.uploadPlugin=h.uploadPlugin;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./RequestError-DrCr_lwO.cjs"),t=require("./validateResponseStatus-CYU2N49m.cjs"),n=require("./createClient-ICkQQqcE.cjs"),r=require("./testing.cjs"),i=require("./PluginError-DT3VnlUB.cjs"),a=require("./plugins/auth.cjs"),o=require("./cachePlugin-BPpjDaM9.cjs"),s=require("./plugins/circuit-breaker.cjs"),c=require("./plugins/concurrency.cjs"),l=require("./plugins/download.cjs"),u=require("./plugins/logger.cjs"),d=require("./plugins/opentelemetry.cjs"),f=require("./plugins/opentelemetry-metrics.cjs"),p=require("./rateLimitPlugin-CtwD8U0P.cjs"),m=require("./plugins/retry.cjs"),h=require("./plugins/upload.cjs");require("./plugins.cjs"),exports.Client=n.n,exports.FetchAdapter=n.i,exports.IndexedDBCacheStore=o.r,exports.InterceptorManager=n.r,exports.MemoryCacheStore=o.i,exports.MockAdapter=r.MockAdapter,exports.PluginError=i.t,exports.RequestError=e.t,exports.SchemaValidationError=t.d,exports.TieredCacheStore=o.n,exports.WebStorageCacheStore=o.a,exports.authPlugin=a.authPlugin,exports.cachePlugin=o.t,exports.circuitBreakerPlugin=s.circuitBreakerPlugin,exports.concurrencyPlugin=c.concurrencyPlugin,exports.createClient=n.t,exports.downloadPlugin=l.downloadPlugin,exports.isRequestError=e.n,exports.isSchemaValidationError=t.f,exports.loggerPlugin=u.loggerPlugin,exports.openTelemetryMetricsPlugin=f.openTelemetryMetricsPlugin,exports.openTelemetryPlugin=d.openTelemetryPlugin,exports.rateLimitPlugin=p.t,exports.retryPlugin=m.retryPlugin,exports.uploadPlugin=h.uploadPlugin;
package/dist/index.d.cts CHANGED
@@ -5,7 +5,7 @@ import { a as MockReplyHandler, c as MockRoute, i as MockReply, l as MockURLMatc
5
5
  import { a as PluginInterceptorManager, c as InterceptorOptions, i as PluginHookManager, n as PluginCleanup, o as Interceptor, r as PluginContext, s as InterceptorManager, t as Plugin } from "./Plugin-DYSeSZ6O.cjs";
6
6
  import { n as PluginErrorCode, r as PluginErrorOptions, t as PluginError } from "./PluginError-DVP3pUt_.cjs";
7
7
  import { n as AuthTokenStorage, r as authPlugin, t as AuthPluginOptions } from "./authPlugin-DpE4afbz.cjs";
8
- import { C as WebStorageCacheStore, S as MemoryCacheStoreOptions, _ as IndexedDBCacheUsage, a as CacheSetOptions, b as CacheStore, c as TieredCacheBroadcastOptions, d as TieredCacheStoreOptions, f as IndexedDBCacheCompactionOptions, g as IndexedDBCacheStoreOptions, h as IndexedDBCacheStoreEvent, i as CachePluginOptions, l as TieredCacheCoordinationOptions, m as IndexedDBCacheStore, n as CacheEventType, o as CacheStats, p as IndexedDBCacheCompactionResult, r as CachePlugin, s as cachePlugin, t as CacheEvent, u as TieredCacheStore, v as CacheEntry, w as WebStorageCacheStoreOptions, x as MemoryCacheStore, y as CacheRefreshLease } from "./cachePlugin-BMcLP92z.cjs";
8
+ import { C as WebStorageCacheStore, S as MemoryCacheStoreOptions, _ as CacheStats, a as TieredCacheStoreOptions, b as CacheStore, c as IndexedDBCacheStore, d as IndexedDBCacheUsage, f as CacheEvent, g as CacheSetOptions, h as CachePluginOptions, i as TieredCacheStore, l as IndexedDBCacheStoreEvent, m as CachePlugin, n as TieredCacheBroadcastOptions, o as IndexedDBCacheCompactionOptions, p as CacheEventType, r as TieredCacheCoordinationOptions, s as IndexedDBCacheCompactionResult, t as cachePlugin, u as IndexedDBCacheStoreOptions, v as CacheEntry, w as WebStorageCacheStoreOptions, x as MemoryCacheStore, y as CacheRefreshLease } from "./cachePlugin-CukS_jh1.cjs";
9
9
  import { n as CircuitBreakerPluginOptions, r as circuitBreakerPlugin, t as CircuitBreakerPlugin } from "./circuitBreakerPlugin-tbwS-j5u.cjs";
10
10
  import { i as concurrencyPlugin, n as ConcurrencyPluginOptions, r as ConcurrencyState, t as ConcurrencyPlugin } from "./concurrencyPlugin-Dvsgel94.cjs";
11
11
  import { n as DownloadTransport, r as downloadPlugin, t as DownloadPluginOptions } from "./downloadPlugin-DJDuMLwT.cjs";
@@ -15,4 +15,4 @@ import { a as OpenTelemetryMetricsPluginOptions, i as OpenTelemetryMetricAttribu
15
15
  import { i as rateLimitPlugin, n as RateLimitPluginOptions, r as RateLimitState, t as RateLimitPlugin } from "./rateLimitPlugin-KOSUTbvE.cjs";
16
16
  import { t as retryPlugin } from "./retryPlugin-Ir1VPUHq.cjs";
17
17
  import { t as uploadPlugin } from "./uploadPlugin-CAHUGiz4.cjs";
18
- export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, type CacheEntry, CacheEvent, CacheEventType, CacheOptions, CachePlugin, CachePluginOptions, type CacheRefreshLease, CacheSetOptions, CacheStats, type CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadOutput, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchFunction, FetchOptions, HttpMethod, type IndexedDBCacheCompactionOptions, type IndexedDBCacheCompactionResult, IndexedDBCacheStore, type IndexedDBCacheStoreEvent, type IndexedDBCacheStoreOptions, type IndexedDBCacheUsage, Interceptor, InterceptorManager, InterceptorOptions, JsonParser, JsonParserContext, JsonStringifier, LoggerEntry, LoggerOptions, MemoryCacheOptions, MemoryCacheStore, type MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, OpenTelemetryAttributeValue, OpenTelemetryContextApi, OpenTelemetryCounter, OpenTelemetryHeaderSetter, OpenTelemetryHistogram, OpenTelemetryMeter, OpenTelemetryMetricAttributes, OpenTelemetryMetricsOptions, OpenTelemetryMetricsPluginOptions, OpenTelemetryOptions, OpenTelemetryPluginOptions, OpenTelemetryPropagationApi, OpenTelemetrySpan, OpenTelemetryTraceApi, OpenTelemetryTracer, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QuerySerializer, QueryValue, RateLimitOptions, RateLimitPlugin, RateLimitPluginOptions, RateLimitState, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestInputConfig, RequestLogEntry, RequestLogger, RequestURL, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, StreamingSchemaLocation, type TieredCacheBroadcastOptions, type TieredCacheCoordinationOptions, TieredCacheStore, type TieredCacheStoreOptions, TransferProgress, UploadData, UploadOptions, UploadProgress, WebStorageCacheStore, type WebStorageCacheStoreOptions, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, isRequestError, isSchemaValidationError, loggerPlugin, openTelemetryMetricsPlugin, openTelemetryPlugin, rateLimitPlugin, retryPlugin, uploadPlugin };
18
+ export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, type CacheEntry, type CacheEvent, type CacheEventType, CacheOptions, type CachePlugin, type CachePluginOptions, type CacheRefreshLease, type CacheSetOptions, type CacheStats, type CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadOutput, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchFunction, FetchOptions, HttpMethod, type IndexedDBCacheCompactionOptions, type IndexedDBCacheCompactionResult, IndexedDBCacheStore, type IndexedDBCacheStoreEvent, type IndexedDBCacheStoreOptions, type IndexedDBCacheUsage, Interceptor, InterceptorManager, InterceptorOptions, JsonParser, JsonParserContext, JsonStringifier, LoggerEntry, LoggerOptions, MemoryCacheOptions, MemoryCacheStore, type MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, OpenTelemetryAttributeValue, OpenTelemetryContextApi, OpenTelemetryCounter, OpenTelemetryHeaderSetter, OpenTelemetryHistogram, OpenTelemetryMeter, OpenTelemetryMetricAttributes, OpenTelemetryMetricsOptions, OpenTelemetryMetricsPluginOptions, OpenTelemetryOptions, OpenTelemetryPluginOptions, OpenTelemetryPropagationApi, OpenTelemetrySpan, OpenTelemetryTraceApi, OpenTelemetryTracer, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QuerySerializer, QueryValue, RateLimitOptions, RateLimitPlugin, RateLimitPluginOptions, RateLimitState, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestInputConfig, RequestLogEntry, RequestLogger, RequestURL, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, StreamingSchemaLocation, type TieredCacheBroadcastOptions, type TieredCacheCoordinationOptions, TieredCacheStore, type TieredCacheStoreOptions, TransferProgress, UploadData, UploadOptions, UploadProgress, WebStorageCacheStore, type WebStorageCacheStoreOptions, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, isRequestError, isSchemaValidationError, loggerPlugin, openTelemetryMetricsPlugin, openTelemetryPlugin, rateLimitPlugin, retryPlugin, uploadPlugin };
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ import { a as MockReplyHandler, c as MockRoute, i as MockReply, l as MockURLMatc
5
5
  import { a as PluginInterceptorManager, c as InterceptorOptions, i as PluginHookManager, n as PluginCleanup, o as Interceptor, r as PluginContext, s as InterceptorManager, t as Plugin } from "./Plugin-C5P_tBXo.js";
6
6
  import { n as PluginErrorCode, r as PluginErrorOptions, t as PluginError } from "./PluginError-DVP3pUt_.js";
7
7
  import { n as AuthTokenStorage, r as authPlugin, t as AuthPluginOptions } from "./authPlugin-USKx_XNX.js";
8
- import { C as WebStorageCacheStore, S as MemoryCacheStoreOptions, _ as IndexedDBCacheUsage, a as CacheSetOptions, b as CacheStore, c as TieredCacheBroadcastOptions, d as TieredCacheStoreOptions, f as IndexedDBCacheCompactionOptions, g as IndexedDBCacheStoreOptions, h as IndexedDBCacheStoreEvent, i as CachePluginOptions, l as TieredCacheCoordinationOptions, m as IndexedDBCacheStore, n as CacheEventType, o as CacheStats, p as IndexedDBCacheCompactionResult, r as CachePlugin, s as cachePlugin, t as CacheEvent, u as TieredCacheStore, v as CacheEntry, w as WebStorageCacheStoreOptions, x as MemoryCacheStore, y as CacheRefreshLease } from "./cachePlugin-D5iyPREK.js";
8
+ import { C as WebStorageCacheStore, S as MemoryCacheStoreOptions, _ as CacheStats, a as TieredCacheStoreOptions, b as CacheStore, c as IndexedDBCacheStore, d as IndexedDBCacheUsage, f as CacheEvent, g as CacheSetOptions, h as CachePluginOptions, i as TieredCacheStore, l as IndexedDBCacheStoreEvent, m as CachePlugin, n as TieredCacheBroadcastOptions, o as IndexedDBCacheCompactionOptions, p as CacheEventType, r as TieredCacheCoordinationOptions, s as IndexedDBCacheCompactionResult, t as cachePlugin, u as IndexedDBCacheStoreOptions, v as CacheEntry, w as WebStorageCacheStoreOptions, x as MemoryCacheStore, y as CacheRefreshLease } from "./cachePlugin-ByLau-mj.js";
9
9
  import { n as CircuitBreakerPluginOptions, r as circuitBreakerPlugin, t as CircuitBreakerPlugin } from "./circuitBreakerPlugin-D12NHWon.js";
10
10
  import { i as concurrencyPlugin, n as ConcurrencyPluginOptions, r as ConcurrencyState, t as ConcurrencyPlugin } from "./concurrencyPlugin-W84oJyJP.js";
11
11
  import { n as DownloadTransport, r as downloadPlugin, t as DownloadPluginOptions } from "./downloadPlugin-DjCZgsVL.js";
@@ -15,4 +15,4 @@ import { a as OpenTelemetryMetricsPluginOptions, i as OpenTelemetryMetricAttribu
15
15
  import { i as rateLimitPlugin, n as RateLimitPluginOptions, r as RateLimitState, t as RateLimitPlugin } from "./rateLimitPlugin-cU0qI8TH.js";
16
16
  import { t as retryPlugin } from "./retryPlugin-Df4T3WEv.js";
17
17
  import { t as uploadPlugin } from "./uploadPlugin-C8CgYCKh.js";
18
- export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, type CacheEntry, CacheEvent, CacheEventType, CacheOptions, CachePlugin, CachePluginOptions, type CacheRefreshLease, CacheSetOptions, CacheStats, type CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadOutput, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchFunction, FetchOptions, HttpMethod, type IndexedDBCacheCompactionOptions, type IndexedDBCacheCompactionResult, IndexedDBCacheStore, type IndexedDBCacheStoreEvent, type IndexedDBCacheStoreOptions, type IndexedDBCacheUsage, Interceptor, InterceptorManager, InterceptorOptions, JsonParser, JsonParserContext, JsonStringifier, LoggerEntry, LoggerOptions, MemoryCacheOptions, MemoryCacheStore, type MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, OpenTelemetryAttributeValue, OpenTelemetryContextApi, OpenTelemetryCounter, OpenTelemetryHeaderSetter, OpenTelemetryHistogram, OpenTelemetryMeter, OpenTelemetryMetricAttributes, OpenTelemetryMetricsOptions, OpenTelemetryMetricsPluginOptions, OpenTelemetryOptions, OpenTelemetryPluginOptions, OpenTelemetryPropagationApi, OpenTelemetrySpan, OpenTelemetryTraceApi, OpenTelemetryTracer, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QuerySerializer, QueryValue, RateLimitOptions, RateLimitPlugin, RateLimitPluginOptions, RateLimitState, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestInputConfig, RequestLogEntry, RequestLogger, RequestURL, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, StreamingSchemaLocation, type TieredCacheBroadcastOptions, type TieredCacheCoordinationOptions, TieredCacheStore, type TieredCacheStoreOptions, TransferProgress, UploadData, UploadOptions, UploadProgress, WebStorageCacheStore, type WebStorageCacheStoreOptions, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, isRequestError, isSchemaValidationError, loggerPlugin, openTelemetryMetricsPlugin, openTelemetryPlugin, rateLimitPlugin, retryPlugin, uploadPlugin };
18
+ export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, type CacheEntry, type CacheEvent, type CacheEventType, CacheOptions, type CachePlugin, type CachePluginOptions, type CacheRefreshLease, type CacheSetOptions, type CacheStats, type CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadOutput, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchFunction, FetchOptions, HttpMethod, type IndexedDBCacheCompactionOptions, type IndexedDBCacheCompactionResult, IndexedDBCacheStore, type IndexedDBCacheStoreEvent, type IndexedDBCacheStoreOptions, type IndexedDBCacheUsage, Interceptor, InterceptorManager, InterceptorOptions, JsonParser, JsonParserContext, JsonStringifier, LoggerEntry, LoggerOptions, MemoryCacheOptions, MemoryCacheStore, type MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, OpenTelemetryAttributeValue, OpenTelemetryContextApi, OpenTelemetryCounter, OpenTelemetryHeaderSetter, OpenTelemetryHistogram, OpenTelemetryMeter, OpenTelemetryMetricAttributes, OpenTelemetryMetricsOptions, OpenTelemetryMetricsPluginOptions, OpenTelemetryOptions, OpenTelemetryPluginOptions, OpenTelemetryPropagationApi, OpenTelemetrySpan, OpenTelemetryTraceApi, OpenTelemetryTracer, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QuerySerializer, QueryValue, RateLimitOptions, RateLimitPlugin, RateLimitPluginOptions, RateLimitState, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestInputConfig, RequestLogEntry, RequestLogger, RequestURL, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, StreamingSchemaLocation, type TieredCacheBroadcastOptions, type TieredCacheCoordinationOptions, TieredCacheStore, type TieredCacheStoreOptions, TransferProgress, UploadData, UploadOptions, UploadProgress, WebStorageCacheStore, type WebStorageCacheStoreOptions, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, isRequestError, isSchemaValidationError, loggerPlugin, openTelemetryMetricsPlugin, openTelemetryPlugin, rateLimitPlugin, retryPlugin, uploadPlugin };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{n as e,t}from"./RequestError-B0HIY1zK.js";import{d as n,f as r}from"./validateResponseStatus-JYSqdThE.js";import{i,n as a,r as o,t as s}from"./createClient-BJInwX7D.js";import{MockAdapter as c}from"./testing.js";import{t as l}from"./PluginError-CcuPSIRv.js";import{authPlugin as u}from"./plugins/auth.js";import{a as d,i as f,n as p,r as m,t as h}from"./cachePlugin-kcIdZe02.js";import{circuitBreakerPlugin as g}from"./plugins/circuit-breaker.js";import{concurrencyPlugin as _}from"./plugins/concurrency.js";import{downloadPlugin as v}from"./plugins/download.js";import{loggerPlugin as y}from"./plugins/logger.js";import{openTelemetryPlugin as b}from"./plugins/opentelemetry.js";import{openTelemetryMetricsPlugin as x}from"./plugins/opentelemetry-metrics.js";import{t as S}from"./rateLimitPlugin-EyoriWyF.js";import{retryPlugin as C}from"./plugins/retry.js";import{uploadPlugin as w}from"./plugins/upload.js";import"./plugins.js";export{a as Client,i as FetchAdapter,m as IndexedDBCacheStore,o as InterceptorManager,f as MemoryCacheStore,c as MockAdapter,l as PluginError,t as RequestError,n as SchemaValidationError,p as TieredCacheStore,d as WebStorageCacheStore,u as authPlugin,h as cachePlugin,g as circuitBreakerPlugin,_ as concurrencyPlugin,s as createClient,v as downloadPlugin,e as isRequestError,r as isSchemaValidationError,y as loggerPlugin,x as openTelemetryMetricsPlugin,b as openTelemetryPlugin,S as rateLimitPlugin,C as retryPlugin,w as uploadPlugin};
1
+ import{n as e,t}from"./RequestError-B0HIY1zK.js";import{d as n,f as r}from"./validateResponseStatus-JYSqdThE.js";import{i,n as a,r as o,t as s}from"./createClient-BJInwX7D.js";import{MockAdapter as c}from"./testing.js";import{t as l}from"./PluginError-CcuPSIRv.js";import{authPlugin as u}from"./plugins/auth.js";import{a as d,i as f,n as p,r as m,t as h}from"./cachePlugin-BLWjTpTf.js";import{circuitBreakerPlugin as g}from"./plugins/circuit-breaker.js";import{concurrencyPlugin as _}from"./plugins/concurrency.js";import{downloadPlugin as v}from"./plugins/download.js";import{loggerPlugin as y}from"./plugins/logger.js";import{openTelemetryPlugin as b}from"./plugins/opentelemetry.js";import{openTelemetryMetricsPlugin as x}from"./plugins/opentelemetry-metrics.js";import{t as S}from"./rateLimitPlugin-EyoriWyF.js";import{retryPlugin as C}from"./plugins/retry.js";import{uploadPlugin as w}from"./plugins/upload.js";import"./plugins.js";export{a as Client,i as FetchAdapter,m as IndexedDBCacheStore,o as InterceptorManager,f as MemoryCacheStore,c as MockAdapter,l as PluginError,t as RequestError,n as SchemaValidationError,p as TieredCacheStore,d as WebStorageCacheStore,u as authPlugin,h as cachePlugin,g as circuitBreakerPlugin,_ as concurrencyPlugin,s as createClient,v as downloadPlugin,e as isRequestError,r as isSchemaValidationError,y as loggerPlugin,x as openTelemetryMetricsPlugin,b as openTelemetryPlugin,S as rateLimitPlugin,C as retryPlugin,w as uploadPlugin};
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../cachePlugin-ComdU-Tb.cjs");exports.IndexedDBCacheStore=e.r,exports.MemoryCacheStore=e.i,exports.TieredCacheStore=e.n,exports.WebStorageCacheStore=e.a,exports.cachePlugin=e.t;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../cachePlugin-BPpjDaM9.cjs");exports.IndexedDBCacheStore=e.r,exports.MemoryCacheStore=e.i,exports.TieredCacheStore=e.n,exports.WebStorageCacheStore=e.a,exports.cachePlugin=e.t;
@@ -1,2 +1,2 @@
1
- import { C as WebStorageCacheStore, S as MemoryCacheStoreOptions, _ as IndexedDBCacheUsage, a as CacheSetOptions, b as CacheStore, c as TieredCacheBroadcastOptions, d as TieredCacheStoreOptions, f as IndexedDBCacheCompactionOptions, g as IndexedDBCacheStoreOptions, h as IndexedDBCacheStoreEvent, i as CachePluginOptions, l as TieredCacheCoordinationOptions, m as IndexedDBCacheStore, n as CacheEventType, o as CacheStats, p as IndexedDBCacheCompactionResult, r as CachePlugin, s as cachePlugin, t as CacheEvent, u as TieredCacheStore, v as CacheEntry, w as WebStorageCacheStoreOptions, x as MemoryCacheStore, y as CacheRefreshLease } from "../cachePlugin-BMcLP92z.cjs";
2
- export { type CacheEntry, CacheEvent, CacheEventType, CachePlugin, CachePluginOptions, type CacheRefreshLease, CacheSetOptions, CacheStats, type CacheStore, type IndexedDBCacheCompactionOptions, type IndexedDBCacheCompactionResult, IndexedDBCacheStore, type IndexedDBCacheStoreEvent, type IndexedDBCacheStoreOptions, type IndexedDBCacheUsage, MemoryCacheStore, type MemoryCacheStoreOptions, type TieredCacheBroadcastOptions, type TieredCacheCoordinationOptions, TieredCacheStore, type TieredCacheStoreOptions, WebStorageCacheStore, type WebStorageCacheStoreOptions, cachePlugin };
1
+ import { C as WebStorageCacheStore, S as MemoryCacheStoreOptions, _ as CacheStats, a as TieredCacheStoreOptions, b as CacheStore, c as IndexedDBCacheStore, d as IndexedDBCacheUsage, f as CacheEvent, g as CacheSetOptions, h as CachePluginOptions, i as TieredCacheStore, l as IndexedDBCacheStoreEvent, m as CachePlugin, n as TieredCacheBroadcastOptions, o as IndexedDBCacheCompactionOptions, p as CacheEventType, r as TieredCacheCoordinationOptions, s as IndexedDBCacheCompactionResult, t as cachePlugin, u as IndexedDBCacheStoreOptions, v as CacheEntry, w as WebStorageCacheStoreOptions, x as MemoryCacheStore, y as CacheRefreshLease } from "../cachePlugin-CukS_jh1.cjs";
2
+ export { type CacheEntry, type CacheEvent, type CacheEventType, type CachePlugin, type CachePluginOptions, type CacheRefreshLease, type CacheSetOptions, type CacheStats, type CacheStore, type IndexedDBCacheCompactionOptions, type IndexedDBCacheCompactionResult, IndexedDBCacheStore, type IndexedDBCacheStoreEvent, type IndexedDBCacheStoreOptions, type IndexedDBCacheUsage, MemoryCacheStore, type MemoryCacheStoreOptions, type TieredCacheBroadcastOptions, type TieredCacheCoordinationOptions, TieredCacheStore, type TieredCacheStoreOptions, WebStorageCacheStore, type WebStorageCacheStoreOptions, cachePlugin };
@@ -1,2 +1,2 @@
1
- import { C as WebStorageCacheStore, S as MemoryCacheStoreOptions, _ as IndexedDBCacheUsage, a as CacheSetOptions, b as CacheStore, c as TieredCacheBroadcastOptions, d as TieredCacheStoreOptions, f as IndexedDBCacheCompactionOptions, g as IndexedDBCacheStoreOptions, h as IndexedDBCacheStoreEvent, i as CachePluginOptions, l as TieredCacheCoordinationOptions, m as IndexedDBCacheStore, n as CacheEventType, o as CacheStats, p as IndexedDBCacheCompactionResult, r as CachePlugin, s as cachePlugin, t as CacheEvent, u as TieredCacheStore, v as CacheEntry, w as WebStorageCacheStoreOptions, x as MemoryCacheStore, y as CacheRefreshLease } from "../cachePlugin-D5iyPREK.js";
2
- export { type CacheEntry, CacheEvent, CacheEventType, CachePlugin, CachePluginOptions, type CacheRefreshLease, CacheSetOptions, CacheStats, type CacheStore, type IndexedDBCacheCompactionOptions, type IndexedDBCacheCompactionResult, IndexedDBCacheStore, type IndexedDBCacheStoreEvent, type IndexedDBCacheStoreOptions, type IndexedDBCacheUsage, MemoryCacheStore, type MemoryCacheStoreOptions, type TieredCacheBroadcastOptions, type TieredCacheCoordinationOptions, TieredCacheStore, type TieredCacheStoreOptions, WebStorageCacheStore, type WebStorageCacheStoreOptions, cachePlugin };
1
+ import { C as WebStorageCacheStore, S as MemoryCacheStoreOptions, _ as CacheStats, a as TieredCacheStoreOptions, b as CacheStore, c as IndexedDBCacheStore, d as IndexedDBCacheUsage, f as CacheEvent, g as CacheSetOptions, h as CachePluginOptions, i as TieredCacheStore, l as IndexedDBCacheStoreEvent, m as CachePlugin, n as TieredCacheBroadcastOptions, o as IndexedDBCacheCompactionOptions, p as CacheEventType, r as TieredCacheCoordinationOptions, s as IndexedDBCacheCompactionResult, t as cachePlugin, u as IndexedDBCacheStoreOptions, v as CacheEntry, w as WebStorageCacheStoreOptions, x as MemoryCacheStore, y as CacheRefreshLease } from "../cachePlugin-ByLau-mj.js";
2
+ export { type CacheEntry, type CacheEvent, type CacheEventType, type CachePlugin, type CachePluginOptions, type CacheRefreshLease, type CacheSetOptions, type CacheStats, type CacheStore, type IndexedDBCacheCompactionOptions, type IndexedDBCacheCompactionResult, IndexedDBCacheStore, type IndexedDBCacheStoreEvent, type IndexedDBCacheStoreOptions, type IndexedDBCacheUsage, MemoryCacheStore, type MemoryCacheStoreOptions, type TieredCacheBroadcastOptions, type TieredCacheCoordinationOptions, TieredCacheStore, type TieredCacheStoreOptions, WebStorageCacheStore, type WebStorageCacheStoreOptions, cachePlugin };
@@ -1 +1 @@
1
- import{a as e,i as t,n,r,t as i}from"../cachePlugin-kcIdZe02.js";export{r as IndexedDBCacheStore,t as MemoryCacheStore,n as TieredCacheStore,e as WebStorageCacheStore,i as cachePlugin};
1
+ import{a as e,i as t,n,r,t as i}from"../cachePlugin-BLWjTpTf.js";export{r as IndexedDBCacheStore,t as MemoryCacheStore,n as TieredCacheStore,e as WebStorageCacheStore,i as cachePlugin};
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../RequestError-DrCr_lwO.cjs"),t=require("../resolveExtensionConfig-BHHfQwjF.cjs"),n=new Set([`GET`,`HEAD`]);function memoryCachePlugin(n={}){let r=n.maxEntries??100;if(!Number.isSafeInteger(r)||r<1)throw new e.t(`Memory cache maxEntries must be a positive integer`,{code:`CONFIG_ERROR`});let i=new Map,a=new WeakSet;return{name:`memory-cache`,conflicts:[`cache`],clear(){i.clear()},install(e){e.hooks.onTransport(e=>{let r=e.config,o=t.t(r,`memoryCache`);if(!o?.enabled||e.response||!cacheableRequest(r,o)||(cacheTtl(o.ttl??n.ttl,r),!requestAllowsCache(r)))return;let s=cacheKey(r,o),c=i.get(s);if(!c)return;if(Date.now()>=c.expiresAt){i.delete(s);return}let l=restoreEntry(c,r,e.preserveRaw);if(!l){i.delete(s);return}i.delete(s),i.set(s,c),a.add(e),e.response=l,e.cacheHit=!0}),e.hooks.onResponse(e=>{if(a.delete(e))return;let o=e.config,s=t.t(o,`memoryCache`),c=e.response;if(!s?.enabled||!c||!cacheableRequest(o,s)||!requestAllowsCache(o)||c.status<200||c.status>=300||c.raw.type===`opaque`||c.raw.type===`opaqueredirect`||isAsyncIterable(c.data))return;let l=cacheResponseTtl(c,cacheTtl(s.ttl??n.ttl,o));if(l<=0)return;let u=cacheKey(o,s),d=snapshotResponse(c,Date.now()+l,e.preserveRaw);d&&(i.delete(u),i.set(u,d),i.size>r&&i.delete(i.keys().next().value))},{requiresRawResponse:!1})}}}function cacheableRequest(e,t){return n.has(e.method??`GET`)&&e.body==null&&e.json===void 0&&e.form==null&&e.formData==null&&(!e.parseJson||!!t.key)&&(!e.querySerializer||!!t.key)&&e.responseType!==`stream`&&e.responseType!==`sse`&&e.responseType!==`ndjson`&&e.responseType!==`bytes`&&e.responseType!==`formData`&&e.fetchOptions?.mode!==`no-cors`&&e.fetchOptions?.redirect!==`manual`&&(e.fetchOptions?.credentials===`omit`||!!t.key)}function cacheTtl(t,n){let r=t??3e4;if(r!==1/0&&(!Number.isFinite(r)||r<0))throw new e.t(`Memory cache ttl must be non-negative`,{code:`CONFIG_ERROR`,config:n});return r}function requestAllowsCache(e){let t=new Headers(e.headers);return!t.has(`cache-control`)&&!t.has(`pragma`)}function cacheResponseTtl(e,t){if(e.headers.has(`vary`))return 0;let n=e.headers.get(`cache-control`),r;if(n)for(let e of n.split(`,`)){let t=e.trim().toLowerCase(),n=t.split(`=`,1)[0];if(n===`no-store`||n===`no-cache`||t.startsWith(`max-age=`)&&(r!==void 0||!/^max-age=\d+$/.test(t)||(r=Number(t.slice(8)),!Number.isSafeInteger(r))))return 0}if(r===void 0)return t;let i=e.headers.get(`age`),a=i&&/^\d+$/.test(i)?Number(i):0;return Math.min(t,Math.max(0,r-a)*1e3)}function cacheKey(e,t){if(t.key)return t.key;let n=new Headers(e.headers),r=[];n.forEach((e,t)=>{t!==`cache-control`&&t!==`pragma`&&r.push([t,e])}),r.sort(([e],[t])=>e.localeCompare(t));let i=[];if(e.searchParams)i.push(...e.searchParams.entries());else if(e.query)for(let t of Object.keys(e.query).sort())appendQuery(i,t,e.query[t]);return JSON.stringify({method:e.method??`GET`,baseURL:e.baseURL,url:String(e.url),responseType:e.responseType??`auto`,query:i,headers:r})}function appendQuery(e,t,n){if(n!==void 0){if(Array.isArray(n)){for(let r of n)appendQuery(e,t,r);return}e.push([t,n===null?``:String(n)])}}function snapshotResponse(e,t,n){let r=cloneData(e.data);if(!r)return;let i=n?tryClone(e.raw):void 0;if(!(n&&!i))return{data:r.value,expiresAt:t,status:e.status,statusText:e.statusText,headers:[...e.headers.entries()],raw:i}}function restoreEntry(e,t,n){try{if(n&&!e.raw)return;let r=cloneData(e.data);if(!r)return;let i=e.raw&&tryClone(e.raw);if(n&&!i)return;let a=new Response(i?.body??null,{status:e.status,statusText:e.statusText,headers:e.headers});return{data:r.value,status:e.status,statusText:e.statusText,headers:new Headers(e.headers),config:t,raw:a}}catch{return}}function tryClone(e){try{return e.clone()}catch{return}}function cloneData(e){if(typeof e!=`object`||!e)return{value:e};if(typeof structuredClone==`function`)try{return{value:structuredClone(e)}}catch{return}}function isAsyncIterable(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}exports.memoryCachePlugin=memoryCachePlugin;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../RequestError-DrCr_lwO.cjs"),t=require("../resolveExtensionConfig-BHHfQwjF.cjs"),n=new Set([`GET`,`HEAD`]);function memoryCachePlugin(n={}){let r=n.maxEntries??100;if(!Number.isSafeInteger(r)||r<1)throw new e.t(`Memory cache maxEntries must be a positive integer`,{code:`CONFIG_ERROR`});let i=new Map,a=new WeakSet;return{name:`memory-cache`,conflicts:[`cache`],clear(){i.clear()},install(e){e.hooks.onTransport(e=>{let r=e.config,o=t.t(r,`memoryCache`);if(!o?.enabled||e.response||!cacheableRequest(r,o)||(cacheTtl(o.ttl??n.ttl,r),!requestAllowsCache(r)))return;let s=cacheKey(r,o),c=i.get(s);if(!c)return;if(Date.now()>=c.expiresAt){i.delete(s);return}let l=restoreEntry(c,r,e.preserveRaw);if(!l){i.delete(s);return}i.delete(s),i.set(s,c),a.add(e),e.response=l,e.cacheHit=!0}),e.hooks.onResponse(e=>{if(a.delete(e))return;let o=e.config,s=t.t(o,`memoryCache`),c=e.response;if(!s?.enabled||!c||!cacheableRequest(o,s)||!requestAllowsCache(o)||c.status<200||c.status>=300||c.status===206||c.raw.type===`opaque`||c.raw.type===`opaqueredirect`||isAsyncIterable(c.data))return;let l=cacheResponseTtl(c,cacheTtl(s.ttl??n.ttl,o));if(l<=0)return;let u=cacheKey(o,s),d=snapshotResponse(c,Date.now()+l,e.preserveRaw);d&&(i.delete(u),i.set(u,d),i.size>r&&i.delete(i.keys().next().value))},{requiresRawResponse:!1})}}}function cacheableRequest(e,t){return n.has(e.method??`GET`)&&e.body==null&&e.json===void 0&&e.form==null&&e.formData==null&&(!e.parseJson||!!t.key)&&(!e.querySerializer||!!t.key)&&e.responseType!==`stream`&&e.responseType!==`sse`&&e.responseType!==`ndjson`&&e.responseType!==`bytes`&&e.responseType!==`formData`&&e.fetchOptions?.cache===void 0&&e.fetchOptions?.integrity===void 0&&e.fetchOptions?.referrer===void 0&&e.fetchOptions?.referrerPolicy===void 0&&e.fetchOptions?.mode===void 0&&(e.fetchOptions?.redirect===void 0||e.fetchOptions.redirect===`follow`)&&(e.fetchOptions?.credentials===`omit`||!!t.key)}function cacheTtl(t,n){let r=t??3e4;if(r!==1/0&&(!Number.isFinite(r)||r<0))throw new e.t(`Memory cache ttl must be non-negative`,{code:`CONFIG_ERROR`,config:n});return r}function requestAllowsCache(e){let t=new Headers(e.headers);return!t.has(`cache-control`)&&!t.has(`pragma`)}function cacheResponseTtl(e,t){if(e.headers.has(`vary`))return 0;let n=e.headers.get(`cache-control`),r;if(n)for(let e of n.split(`,`)){let t=e.trim().toLowerCase(),n=t.split(`=`,1)[0];if(n===`no-store`||n===`no-cache`||t.startsWith(`max-age=`)&&(r!==void 0||!/^max-age=\d+$/.test(t)||(r=Number(t.slice(8)),!Number.isSafeInteger(r))))return 0}if(r===void 0)return t;let i=e.headers.get(`age`),a=i&&/^\d+$/.test(i)?Number(i):0;return Math.min(t,Math.max(0,r-a)*1e3)}function cacheKey(e,t){if(t.key)return t.key;let n=new Headers(e.headers),r=[];n.forEach((e,t)=>{t!==`cache-control`&&t!==`pragma`&&r.push([t,e])}),r.sort(([e],[t])=>e.localeCompare(t));let i=[];if(e.searchParams)i.push(...e.searchParams.entries());else if(e.query)for(let t of Object.keys(e.query).sort())appendQuery(i,t,e.query[t]);return JSON.stringify({method:e.method??`GET`,baseURL:e.baseURL,url:String(e.url),responseType:e.responseType??`auto`,query:i,headers:r})}function appendQuery(e,t,n){if(n!==void 0){if(Array.isArray(n)){for(let r of n)appendQuery(e,t,r);return}e.push([t,n===null?``:String(n)])}}function snapshotResponse(e,t,n){let r=cloneData(e.data);if(!r)return;let i=n?tryClone(e.raw):void 0;if(!(n&&!i))return{data:r.value,expiresAt:t,status:e.status,statusText:e.statusText,headers:[...e.headers.entries()],raw:i}}function restoreEntry(e,t,n){try{if(n&&!e.raw)return;let r=cloneData(e.data);if(!r)return;let i=e.raw&&tryClone(e.raw);if(n&&!i)return;let a=new Response(i?.body??null,{status:e.status,statusText:e.statusText,headers:e.headers});return{data:r.value,status:e.status,statusText:e.statusText,headers:new Headers(e.headers),config:t,raw:a}}catch{return}}function tryClone(e){try{return e.clone()}catch{return}}function cloneData(e){if(typeof e!=`object`||!e)return{value:e};if(typeof structuredClone==`function`)try{return{value:structuredClone(e)}}catch{return}}function isAsyncIterable(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}exports.memoryCachePlugin=memoryCachePlugin;
@@ -1 +1 @@
1
- import{t as e}from"../RequestError-B0HIY1zK.js";import{t}from"../resolveExtensionConfig-QAFHZVte.js";const n=new Set([`GET`,`HEAD`]);function memoryCachePlugin(n={}){let r=n.maxEntries??100;if(!Number.isSafeInteger(r)||r<1)throw new e(`Memory cache maxEntries must be a positive integer`,{code:`CONFIG_ERROR`});let i=new Map,a=new WeakSet;return{name:`memory-cache`,conflicts:[`cache`],clear(){i.clear()},install(e){e.hooks.onTransport(e=>{let r=e.config,o=t(r,`memoryCache`);if(!o?.enabled||e.response||!cacheableRequest(r,o)||(cacheTtl(o.ttl??n.ttl,r),!requestAllowsCache(r)))return;let s=cacheKey(r,o),c=i.get(s);if(!c)return;if(Date.now()>=c.expiresAt){i.delete(s);return}let l=restoreEntry(c,r,e.preserveRaw);if(!l){i.delete(s);return}i.delete(s),i.set(s,c),a.add(e),e.response=l,e.cacheHit=!0}),e.hooks.onResponse(e=>{if(a.delete(e))return;let o=e.config,s=t(o,`memoryCache`),c=e.response;if(!s?.enabled||!c||!cacheableRequest(o,s)||!requestAllowsCache(o)||c.status<200||c.status>=300||c.raw.type===`opaque`||c.raw.type===`opaqueredirect`||isAsyncIterable(c.data))return;let l=cacheResponseTtl(c,cacheTtl(s.ttl??n.ttl,o));if(l<=0)return;let u=cacheKey(o,s),d=snapshotResponse(c,Date.now()+l,e.preserveRaw);d&&(i.delete(u),i.set(u,d),i.size>r&&i.delete(i.keys().next().value))},{requiresRawResponse:!1})}}}function cacheableRequest(e,t){return n.has(e.method??`GET`)&&e.body==null&&e.json===void 0&&e.form==null&&e.formData==null&&(!e.parseJson||!!t.key)&&(!e.querySerializer||!!t.key)&&e.responseType!==`stream`&&e.responseType!==`sse`&&e.responseType!==`ndjson`&&e.responseType!==`bytes`&&e.responseType!==`formData`&&e.fetchOptions?.mode!==`no-cors`&&e.fetchOptions?.redirect!==`manual`&&(e.fetchOptions?.credentials===`omit`||!!t.key)}function cacheTtl(t,n){let r=t??3e4;if(r!==1/0&&(!Number.isFinite(r)||r<0))throw new e(`Memory cache ttl must be non-negative`,{code:`CONFIG_ERROR`,config:n});return r}function requestAllowsCache(e){let t=new Headers(e.headers);return!t.has(`cache-control`)&&!t.has(`pragma`)}function cacheResponseTtl(e,t){if(e.headers.has(`vary`))return 0;let n=e.headers.get(`cache-control`),r;if(n)for(let e of n.split(`,`)){let t=e.trim().toLowerCase(),n=t.split(`=`,1)[0];if(n===`no-store`||n===`no-cache`||t.startsWith(`max-age=`)&&(r!==void 0||!/^max-age=\d+$/.test(t)||(r=Number(t.slice(8)),!Number.isSafeInteger(r))))return 0}if(r===void 0)return t;let i=e.headers.get(`age`),a=i&&/^\d+$/.test(i)?Number(i):0;return Math.min(t,Math.max(0,r-a)*1e3)}function cacheKey(e,t){if(t.key)return t.key;let n=new Headers(e.headers),r=[];n.forEach((e,t)=>{t!==`cache-control`&&t!==`pragma`&&r.push([t,e])}),r.sort(([e],[t])=>e.localeCompare(t));let i=[];if(e.searchParams)i.push(...e.searchParams.entries());else if(e.query)for(let t of Object.keys(e.query).sort())appendQuery(i,t,e.query[t]);return JSON.stringify({method:e.method??`GET`,baseURL:e.baseURL,url:String(e.url),responseType:e.responseType??`auto`,query:i,headers:r})}function appendQuery(e,t,n){if(n!==void 0){if(Array.isArray(n)){for(let r of n)appendQuery(e,t,r);return}e.push([t,n===null?``:String(n)])}}function snapshotResponse(e,t,n){let r=cloneData(e.data);if(!r)return;let i=n?tryClone(e.raw):void 0;if(!(n&&!i))return{data:r.value,expiresAt:t,status:e.status,statusText:e.statusText,headers:[...e.headers.entries()],raw:i}}function restoreEntry(e,t,n){try{if(n&&!e.raw)return;let r=cloneData(e.data);if(!r)return;let i=e.raw&&tryClone(e.raw);if(n&&!i)return;let a=new Response(i?.body??null,{status:e.status,statusText:e.statusText,headers:e.headers});return{data:r.value,status:e.status,statusText:e.statusText,headers:new Headers(e.headers),config:t,raw:a}}catch{return}}function tryClone(e){try{return e.clone()}catch{return}}function cloneData(e){if(typeof e!=`object`||!e)return{value:e};if(typeof structuredClone==`function`)try{return{value:structuredClone(e)}}catch{return}}function isAsyncIterable(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}export{memoryCachePlugin};
1
+ import{t as e}from"../RequestError-B0HIY1zK.js";import{t}from"../resolveExtensionConfig-QAFHZVte.js";const n=new Set([`GET`,`HEAD`]);function memoryCachePlugin(n={}){let r=n.maxEntries??100;if(!Number.isSafeInteger(r)||r<1)throw new e(`Memory cache maxEntries must be a positive integer`,{code:`CONFIG_ERROR`});let i=new Map,a=new WeakSet;return{name:`memory-cache`,conflicts:[`cache`],clear(){i.clear()},install(e){e.hooks.onTransport(e=>{let r=e.config,o=t(r,`memoryCache`);if(!o?.enabled||e.response||!cacheableRequest(r,o)||(cacheTtl(o.ttl??n.ttl,r),!requestAllowsCache(r)))return;let s=cacheKey(r,o),c=i.get(s);if(!c)return;if(Date.now()>=c.expiresAt){i.delete(s);return}let l=restoreEntry(c,r,e.preserveRaw);if(!l){i.delete(s);return}i.delete(s),i.set(s,c),a.add(e),e.response=l,e.cacheHit=!0}),e.hooks.onResponse(e=>{if(a.delete(e))return;let o=e.config,s=t(o,`memoryCache`),c=e.response;if(!s?.enabled||!c||!cacheableRequest(o,s)||!requestAllowsCache(o)||c.status<200||c.status>=300||c.status===206||c.raw.type===`opaque`||c.raw.type===`opaqueredirect`||isAsyncIterable(c.data))return;let l=cacheResponseTtl(c,cacheTtl(s.ttl??n.ttl,o));if(l<=0)return;let u=cacheKey(o,s),d=snapshotResponse(c,Date.now()+l,e.preserveRaw);d&&(i.delete(u),i.set(u,d),i.size>r&&i.delete(i.keys().next().value))},{requiresRawResponse:!1})}}}function cacheableRequest(e,t){return n.has(e.method??`GET`)&&e.body==null&&e.json===void 0&&e.form==null&&e.formData==null&&(!e.parseJson||!!t.key)&&(!e.querySerializer||!!t.key)&&e.responseType!==`stream`&&e.responseType!==`sse`&&e.responseType!==`ndjson`&&e.responseType!==`bytes`&&e.responseType!==`formData`&&e.fetchOptions?.cache===void 0&&e.fetchOptions?.integrity===void 0&&e.fetchOptions?.referrer===void 0&&e.fetchOptions?.referrerPolicy===void 0&&e.fetchOptions?.mode===void 0&&(e.fetchOptions?.redirect===void 0||e.fetchOptions.redirect===`follow`)&&(e.fetchOptions?.credentials===`omit`||!!t.key)}function cacheTtl(t,n){let r=t??3e4;if(r!==1/0&&(!Number.isFinite(r)||r<0))throw new e(`Memory cache ttl must be non-negative`,{code:`CONFIG_ERROR`,config:n});return r}function requestAllowsCache(e){let t=new Headers(e.headers);return!t.has(`cache-control`)&&!t.has(`pragma`)}function cacheResponseTtl(e,t){if(e.headers.has(`vary`))return 0;let n=e.headers.get(`cache-control`),r;if(n)for(let e of n.split(`,`)){let t=e.trim().toLowerCase(),n=t.split(`=`,1)[0];if(n===`no-store`||n===`no-cache`||t.startsWith(`max-age=`)&&(r!==void 0||!/^max-age=\d+$/.test(t)||(r=Number(t.slice(8)),!Number.isSafeInteger(r))))return 0}if(r===void 0)return t;let i=e.headers.get(`age`),a=i&&/^\d+$/.test(i)?Number(i):0;return Math.min(t,Math.max(0,r-a)*1e3)}function cacheKey(e,t){if(t.key)return t.key;let n=new Headers(e.headers),r=[];n.forEach((e,t)=>{t!==`cache-control`&&t!==`pragma`&&r.push([t,e])}),r.sort(([e],[t])=>e.localeCompare(t));let i=[];if(e.searchParams)i.push(...e.searchParams.entries());else if(e.query)for(let t of Object.keys(e.query).sort())appendQuery(i,t,e.query[t]);return JSON.stringify({method:e.method??`GET`,baseURL:e.baseURL,url:String(e.url),responseType:e.responseType??`auto`,query:i,headers:r})}function appendQuery(e,t,n){if(n!==void 0){if(Array.isArray(n)){for(let r of n)appendQuery(e,t,r);return}e.push([t,n===null?``:String(n)])}}function snapshotResponse(e,t,n){let r=cloneData(e.data);if(!r)return;let i=n?tryClone(e.raw):void 0;if(!(n&&!i))return{data:r.value,expiresAt:t,status:e.status,statusText:e.statusText,headers:[...e.headers.entries()],raw:i}}function restoreEntry(e,t,n){try{if(n&&!e.raw)return;let r=cloneData(e.data);if(!r)return;let i=e.raw&&tryClone(e.raw);if(n&&!i)return;let a=new Response(i?.body??null,{status:e.status,statusText:e.statusText,headers:e.headers});return{data:r.value,status:e.status,statusText:e.statusText,headers:new Headers(e.headers),config:t,raw:a}}catch{return}}function tryClone(e){try{return e.clone()}catch{return}}function cloneData(e){if(typeof e!=`object`||!e)return{value:e};if(typeof structuredClone==`function`)try{return{value:structuredClone(e)}}catch{return}}function isAsyncIterable(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}export{memoryCachePlugin};
package/dist/plugins.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./PluginError-DT3VnlUB.cjs"),t=require("./plugins/auth.cjs"),n=require("./cachePlugin-ComdU-Tb.cjs"),r=require("./plugins/circuit-breaker.cjs"),i=require("./plugins/concurrency.cjs"),a=require("./plugins/download.cjs"),o=require("./plugins/logger.cjs"),s=require("./plugins/opentelemetry.cjs"),c=require("./plugins/opentelemetry-metrics.cjs"),l=require("./rateLimitPlugin-CtwD8U0P.cjs"),u=require("./plugins/retry.cjs"),d=require("./plugins/upload.cjs");exports.IndexedDBCacheStore=n.r,exports.MemoryCacheStore=n.i,exports.PluginError=e.t,exports.TieredCacheStore=n.n,exports.WebStorageCacheStore=n.a,exports.authPlugin=t.authPlugin,exports.cachePlugin=n.t,exports.circuitBreakerPlugin=r.circuitBreakerPlugin,exports.concurrencyPlugin=i.concurrencyPlugin,exports.downloadPlugin=a.downloadPlugin,exports.loggerPlugin=o.loggerPlugin,exports.openTelemetryMetricsPlugin=c.openTelemetryMetricsPlugin,exports.openTelemetryPlugin=s.openTelemetryPlugin,exports.rateLimitPlugin=l.t,exports.retryPlugin=u.retryPlugin,exports.uploadPlugin=d.uploadPlugin;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./PluginError-DT3VnlUB.cjs"),t=require("./plugins/auth.cjs"),n=require("./cachePlugin-BPpjDaM9.cjs"),r=require("./plugins/circuit-breaker.cjs"),i=require("./plugins/concurrency.cjs"),a=require("./plugins/download.cjs"),o=require("./plugins/logger.cjs"),s=require("./plugins/opentelemetry.cjs"),c=require("./plugins/opentelemetry-metrics.cjs"),l=require("./rateLimitPlugin-CtwD8U0P.cjs"),u=require("./plugins/retry.cjs"),d=require("./plugins/upload.cjs");exports.IndexedDBCacheStore=n.r,exports.MemoryCacheStore=n.i,exports.PluginError=e.t,exports.TieredCacheStore=n.n,exports.WebStorageCacheStore=n.a,exports.authPlugin=t.authPlugin,exports.cachePlugin=n.t,exports.circuitBreakerPlugin=r.circuitBreakerPlugin,exports.concurrencyPlugin=i.concurrencyPlugin,exports.downloadPlugin=a.downloadPlugin,exports.loggerPlugin=o.loggerPlugin,exports.openTelemetryMetricsPlugin=c.openTelemetryMetricsPlugin,exports.openTelemetryPlugin=s.openTelemetryPlugin,exports.rateLimitPlugin=l.t,exports.retryPlugin=u.retryPlugin,exports.uploadPlugin=d.uploadPlugin;
@@ -1,7 +1,7 @@
1
1
  import { a as PluginInterceptorManager, i as PluginHookManager, n as PluginCleanup, r as PluginContext, t as Plugin } from "./Plugin-DYSeSZ6O.cjs";
2
2
  import { n as PluginErrorCode, r as PluginErrorOptions, t as PluginError } from "./PluginError-DVP3pUt_.cjs";
3
3
  import { n as AuthTokenStorage, r as authPlugin, t as AuthPluginOptions } from "./authPlugin-DpE4afbz.cjs";
4
- import { C as WebStorageCacheStore, S as MemoryCacheStoreOptions, _ as IndexedDBCacheUsage, a as CacheSetOptions, b as CacheStore, c as TieredCacheBroadcastOptions, d as TieredCacheStoreOptions, f as IndexedDBCacheCompactionOptions, g as IndexedDBCacheStoreOptions, h as IndexedDBCacheStoreEvent, i as CachePluginOptions, l as TieredCacheCoordinationOptions, m as IndexedDBCacheStore, n as CacheEventType, o as CacheStats, p as IndexedDBCacheCompactionResult, r as CachePlugin, s as cachePlugin, t as CacheEvent, u as TieredCacheStore, v as CacheEntry, w as WebStorageCacheStoreOptions, x as MemoryCacheStore, y as CacheRefreshLease } from "./cachePlugin-BMcLP92z.cjs";
4
+ import { C as WebStorageCacheStore, S as MemoryCacheStoreOptions, _ as CacheStats, a as TieredCacheStoreOptions, b as CacheStore, c as IndexedDBCacheStore, d as IndexedDBCacheUsage, f as CacheEvent, g as CacheSetOptions, h as CachePluginOptions, i as TieredCacheStore, l as IndexedDBCacheStoreEvent, m as CachePlugin, n as TieredCacheBroadcastOptions, o as IndexedDBCacheCompactionOptions, p as CacheEventType, r as TieredCacheCoordinationOptions, s as IndexedDBCacheCompactionResult, t as cachePlugin, u as IndexedDBCacheStoreOptions, v as CacheEntry, w as WebStorageCacheStoreOptions, x as MemoryCacheStore, y as CacheRefreshLease } from "./cachePlugin-CukS_jh1.cjs";
5
5
  import { n as CircuitBreakerPluginOptions, r as circuitBreakerPlugin, t as CircuitBreakerPlugin } from "./circuitBreakerPlugin-tbwS-j5u.cjs";
6
6
  import { i as concurrencyPlugin, n as ConcurrencyPluginOptions, r as ConcurrencyState, t as ConcurrencyPlugin } from "./concurrencyPlugin-Dvsgel94.cjs";
7
7
  import { n as DownloadTransport, r as downloadPlugin, t as DownloadPluginOptions } from "./downloadPlugin-DJDuMLwT.cjs";
@@ -11,4 +11,4 @@ import { a as OpenTelemetryMetricsPluginOptions, i as OpenTelemetryMetricAttribu
11
11
  import { i as rateLimitPlugin, n as RateLimitPluginOptions, r as RateLimitState, t as RateLimitPlugin } from "./rateLimitPlugin-KOSUTbvE.cjs";
12
12
  import { t as retryPlugin } from "./retryPlugin-Ir1VPUHq.cjs";
13
13
  import { t as uploadPlugin } from "./uploadPlugin-CAHUGiz4.cjs";
14
- export { AuthPluginOptions, AuthTokenStorage, type CacheEntry, CacheEvent, CacheEventType, CachePlugin, CachePluginOptions, type CacheRefreshLease, CacheSetOptions, CacheStats, type CacheStore, CircuitBreakerPlugin, CircuitBreakerPluginOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadPluginOptions, DownloadTransport, type IndexedDBCacheCompactionOptions, type IndexedDBCacheCompactionResult, IndexedDBCacheStore, type IndexedDBCacheStoreEvent, type IndexedDBCacheStoreOptions, type IndexedDBCacheUsage, MemoryCacheStore, type MemoryCacheStoreOptions, OpenTelemetryContextApi, OpenTelemetryCounter, OpenTelemetryHeaderSetter, OpenTelemetryHistogram, OpenTelemetryMeter, OpenTelemetryMetricAttributes, OpenTelemetryMetricsPluginOptions, OpenTelemetryPluginOptions, OpenTelemetryPropagationApi, OpenTelemetrySpan, OpenTelemetryTraceApi, OpenTelemetryTracer, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, RateLimitPlugin, RateLimitPluginOptions, RateLimitState, type TieredCacheBroadcastOptions, type TieredCacheCoordinationOptions, TieredCacheStore, type TieredCacheStoreOptions, WebStorageCacheStore, type WebStorageCacheStoreOptions, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, downloadPlugin, loggerPlugin, openTelemetryMetricsPlugin, openTelemetryPlugin, rateLimitPlugin, retryPlugin, uploadPlugin };
14
+ export { AuthPluginOptions, AuthTokenStorage, type CacheEntry, type CacheEvent, type CacheEventType, type CachePlugin, type CachePluginOptions, type CacheRefreshLease, type CacheSetOptions, type CacheStats, type CacheStore, CircuitBreakerPlugin, CircuitBreakerPluginOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadPluginOptions, DownloadTransport, type IndexedDBCacheCompactionOptions, type IndexedDBCacheCompactionResult, IndexedDBCacheStore, type IndexedDBCacheStoreEvent, type IndexedDBCacheStoreOptions, type IndexedDBCacheUsage, MemoryCacheStore, type MemoryCacheStoreOptions, OpenTelemetryContextApi, OpenTelemetryCounter, OpenTelemetryHeaderSetter, OpenTelemetryHistogram, OpenTelemetryMeter, OpenTelemetryMetricAttributes, OpenTelemetryMetricsPluginOptions, OpenTelemetryPluginOptions, OpenTelemetryPropagationApi, OpenTelemetrySpan, OpenTelemetryTraceApi, OpenTelemetryTracer, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, RateLimitPlugin, RateLimitPluginOptions, RateLimitState, type TieredCacheBroadcastOptions, type TieredCacheCoordinationOptions, TieredCacheStore, type TieredCacheStoreOptions, WebStorageCacheStore, type WebStorageCacheStoreOptions, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, downloadPlugin, loggerPlugin, openTelemetryMetricsPlugin, openTelemetryPlugin, rateLimitPlugin, retryPlugin, uploadPlugin };
package/dist/plugins.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { a as PluginInterceptorManager, i as PluginHookManager, n as PluginCleanup, r as PluginContext, t as Plugin } from "./Plugin-C5P_tBXo.js";
2
2
  import { n as PluginErrorCode, r as PluginErrorOptions, t as PluginError } from "./PluginError-DVP3pUt_.js";
3
3
  import { n as AuthTokenStorage, r as authPlugin, t as AuthPluginOptions } from "./authPlugin-USKx_XNX.js";
4
- import { C as WebStorageCacheStore, S as MemoryCacheStoreOptions, _ as IndexedDBCacheUsage, a as CacheSetOptions, b as CacheStore, c as TieredCacheBroadcastOptions, d as TieredCacheStoreOptions, f as IndexedDBCacheCompactionOptions, g as IndexedDBCacheStoreOptions, h as IndexedDBCacheStoreEvent, i as CachePluginOptions, l as TieredCacheCoordinationOptions, m as IndexedDBCacheStore, n as CacheEventType, o as CacheStats, p as IndexedDBCacheCompactionResult, r as CachePlugin, s as cachePlugin, t as CacheEvent, u as TieredCacheStore, v as CacheEntry, w as WebStorageCacheStoreOptions, x as MemoryCacheStore, y as CacheRefreshLease } from "./cachePlugin-D5iyPREK.js";
4
+ import { C as WebStorageCacheStore, S as MemoryCacheStoreOptions, _ as CacheStats, a as TieredCacheStoreOptions, b as CacheStore, c as IndexedDBCacheStore, d as IndexedDBCacheUsage, f as CacheEvent, g as CacheSetOptions, h as CachePluginOptions, i as TieredCacheStore, l as IndexedDBCacheStoreEvent, m as CachePlugin, n as TieredCacheBroadcastOptions, o as IndexedDBCacheCompactionOptions, p as CacheEventType, r as TieredCacheCoordinationOptions, s as IndexedDBCacheCompactionResult, t as cachePlugin, u as IndexedDBCacheStoreOptions, v as CacheEntry, w as WebStorageCacheStoreOptions, x as MemoryCacheStore, y as CacheRefreshLease } from "./cachePlugin-ByLau-mj.js";
5
5
  import { n as CircuitBreakerPluginOptions, r as circuitBreakerPlugin, t as CircuitBreakerPlugin } from "./circuitBreakerPlugin-D12NHWon.js";
6
6
  import { i as concurrencyPlugin, n as ConcurrencyPluginOptions, r as ConcurrencyState, t as ConcurrencyPlugin } from "./concurrencyPlugin-W84oJyJP.js";
7
7
  import { n as DownloadTransport, r as downloadPlugin, t as DownloadPluginOptions } from "./downloadPlugin-DjCZgsVL.js";
@@ -11,4 +11,4 @@ import { a as OpenTelemetryMetricsPluginOptions, i as OpenTelemetryMetricAttribu
11
11
  import { i as rateLimitPlugin, n as RateLimitPluginOptions, r as RateLimitState, t as RateLimitPlugin } from "./rateLimitPlugin-cU0qI8TH.js";
12
12
  import { t as retryPlugin } from "./retryPlugin-Df4T3WEv.js";
13
13
  import { t as uploadPlugin } from "./uploadPlugin-C8CgYCKh.js";
14
- export { AuthPluginOptions, AuthTokenStorage, type CacheEntry, CacheEvent, CacheEventType, CachePlugin, CachePluginOptions, type CacheRefreshLease, CacheSetOptions, CacheStats, type CacheStore, CircuitBreakerPlugin, CircuitBreakerPluginOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadPluginOptions, DownloadTransport, type IndexedDBCacheCompactionOptions, type IndexedDBCacheCompactionResult, IndexedDBCacheStore, type IndexedDBCacheStoreEvent, type IndexedDBCacheStoreOptions, type IndexedDBCacheUsage, MemoryCacheStore, type MemoryCacheStoreOptions, OpenTelemetryContextApi, OpenTelemetryCounter, OpenTelemetryHeaderSetter, OpenTelemetryHistogram, OpenTelemetryMeter, OpenTelemetryMetricAttributes, OpenTelemetryMetricsPluginOptions, OpenTelemetryPluginOptions, OpenTelemetryPropagationApi, OpenTelemetrySpan, OpenTelemetryTraceApi, OpenTelemetryTracer, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, RateLimitPlugin, RateLimitPluginOptions, RateLimitState, type TieredCacheBroadcastOptions, type TieredCacheCoordinationOptions, TieredCacheStore, type TieredCacheStoreOptions, WebStorageCacheStore, type WebStorageCacheStoreOptions, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, downloadPlugin, loggerPlugin, openTelemetryMetricsPlugin, openTelemetryPlugin, rateLimitPlugin, retryPlugin, uploadPlugin };
14
+ export { AuthPluginOptions, AuthTokenStorage, type CacheEntry, type CacheEvent, type CacheEventType, type CachePlugin, type CachePluginOptions, type CacheRefreshLease, type CacheSetOptions, type CacheStats, type CacheStore, CircuitBreakerPlugin, CircuitBreakerPluginOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadPluginOptions, DownloadTransport, type IndexedDBCacheCompactionOptions, type IndexedDBCacheCompactionResult, IndexedDBCacheStore, type IndexedDBCacheStoreEvent, type IndexedDBCacheStoreOptions, type IndexedDBCacheUsage, MemoryCacheStore, type MemoryCacheStoreOptions, OpenTelemetryContextApi, OpenTelemetryCounter, OpenTelemetryHeaderSetter, OpenTelemetryHistogram, OpenTelemetryMeter, OpenTelemetryMetricAttributes, OpenTelemetryMetricsPluginOptions, OpenTelemetryPluginOptions, OpenTelemetryPropagationApi, OpenTelemetrySpan, OpenTelemetryTraceApi, OpenTelemetryTracer, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, RateLimitPlugin, RateLimitPluginOptions, RateLimitState, type TieredCacheBroadcastOptions, type TieredCacheCoordinationOptions, TieredCacheStore, type TieredCacheStoreOptions, WebStorageCacheStore, type WebStorageCacheStoreOptions, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, downloadPlugin, loggerPlugin, openTelemetryMetricsPlugin, openTelemetryPlugin, rateLimitPlugin, retryPlugin, uploadPlugin };
package/dist/plugins.js CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./PluginError-CcuPSIRv.js";import{authPlugin as t}from"./plugins/auth.js";import{a as n,i as r,n as i,r as a,t as o}from"./cachePlugin-kcIdZe02.js";import{circuitBreakerPlugin as s}from"./plugins/circuit-breaker.js";import{concurrencyPlugin as c}from"./plugins/concurrency.js";import{downloadPlugin as l}from"./plugins/download.js";import{loggerPlugin as u}from"./plugins/logger.js";import{openTelemetryPlugin as d}from"./plugins/opentelemetry.js";import{openTelemetryMetricsPlugin as f}from"./plugins/opentelemetry-metrics.js";import{t as p}from"./rateLimitPlugin-EyoriWyF.js";import{retryPlugin as m}from"./plugins/retry.js";import{uploadPlugin as h}from"./plugins/upload.js";export{a as IndexedDBCacheStore,r as MemoryCacheStore,e as PluginError,i as TieredCacheStore,n as WebStorageCacheStore,t as authPlugin,o as cachePlugin,s as circuitBreakerPlugin,c as concurrencyPlugin,l as downloadPlugin,u as loggerPlugin,f as openTelemetryMetricsPlugin,d as openTelemetryPlugin,p as rateLimitPlugin,m as retryPlugin,h as uploadPlugin};
1
+ import{t as e}from"./PluginError-CcuPSIRv.js";import{authPlugin as t}from"./plugins/auth.js";import{a as n,i as r,n as i,r as a,t as o}from"./cachePlugin-BLWjTpTf.js";import{circuitBreakerPlugin as s}from"./plugins/circuit-breaker.js";import{concurrencyPlugin as c}from"./plugins/concurrency.js";import{downloadPlugin as l}from"./plugins/download.js";import{loggerPlugin as u}from"./plugins/logger.js";import{openTelemetryPlugin as d}from"./plugins/opentelemetry.js";import{openTelemetryMetricsPlugin as f}from"./plugins/opentelemetry-metrics.js";import{t as p}from"./rateLimitPlugin-EyoriWyF.js";import{retryPlugin as m}from"./plugins/retry.js";import{uploadPlugin as h}from"./plugins/upload.js";export{a as IndexedDBCacheStore,r as MemoryCacheStore,e as PluginError,i as TieredCacheStore,n as WebStorageCacheStore,t as authPlugin,o as cachePlugin,s as circuitBreakerPlugin,c as concurrencyPlugin,l as downloadPlugin,u as loggerPlugin,f as openTelemetryMetricsPlugin,d as openTelemetryPlugin,p as rateLimitPlugin,m as retryPlugin,h as uploadPlugin};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.18.0",
3
+ "version": "1.18.2",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",
@@ -160,6 +160,8 @@
160
160
  "example": "tsx examples/basic.ts",
161
161
  "example:plugins": "tsx examples/plugins.ts",
162
162
  "example:memory-cache": "tsx examples/memory-cache.ts",
163
+ "example:streaming": "tsx examples/streaming.ts",
164
+ "example:auth-refresh": "tsx examples/auth-refresh.ts",
163
165
  "test:coverage": "vitest run --coverage",
164
166
  "test:run": "vitest run",
165
167
  "test:security": "vitest run test/security.test.ts",
@@ -1 +0,0 @@
1
- const e=require("./RequestError-DrCr_lwO.cjs"),t=require("./isBinaryBody-B0414zDU.cjs"),n=require("./isPromiseLike-C8e95Or2.cjs"),r=require("./waitForSignal-D5eX-NMv.cjs"),i=require("./resolveExtensionConfig-BHHfQwjF.cjs"),a={persist:!1,ttl:0};function resolveRequestCachePolicy(e){let t=new Headers(e.headers),n=t.get(`cache-control`),r=!1;if(n)for(let e of n.split(`,`)){let t=e.trim(),n=t.indexOf(`=`),i=(n===-1?t:t.slice(0,n)).trim().toLowerCase();if(i===`no-store`)return`no-store`;if(i===`no-cache`){r=!0;continue}if(i===`max-age`&&n!==-1){let e=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());e&&Number(e[1]??e[2])===0&&(r=!0)}}else t.get(`pragma`)?.split(`,`).some(e=>e.trim().toLowerCase()===`no-cache`)&&(r=!0);return r?`revalidate`:`default`}function resolveResponseCachePolicy(e,t,n,r){let i=e.headers.get(`cache-control`),o,s=!1;if(i)for(let e of i.split(`,`)){let t=e.trim(),n=t.indexOf(`=`),r=(n===-1?t:t.slice(0,n)).trim().toLowerCase();if(r===`no-store`)return a;if(r===`no-cache`){s=!0;continue}if(r!==`max-age`)continue;if(o!==void 0)return a;let i=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());if(!i)return a;o=Number(i[1]??i[2])}if(e.headers.get(`vary`)?.split(`,`).some(e=>{let t=e.trim().toLowerCase();return t===`*`||isRequestCacheControlHeader$1(t)})||t<=0||o!==void 0&&!Number.isSafeInteger(o))return a;let c=s?0:o===void 0?t:Math.min(t,Math.max(0,(o-parseAge(e.headers.get(`age`)))*1e3));return{ttl:c,persist:c>0||hasResponseValidator$1(e.headers)||resolveStaleIfErrorWindow(e.headers,n)>0||!s&&resolveStaleWhileRevalidateWindow(e.headers,r)>0}}function resolveStaleIfErrorWindow(e,t){return resolveWindow(e,t,`stale-if-error`)}function resolveStaleWhileRevalidateWindow(e,t){return resolveWindow(e,t,`stale-while-revalidate`)}function hasCacheControlDirective(e,t){return e.get(`cache-control`)?.split(`,`).some(e=>{let n=e.indexOf(`=`);return(n===-1?e:e.slice(0,n)).trim().toLowerCase()===t})??!1}function resolveWindow(e,t,n){let r=parseCacheDeltaSeconds(e.get(`cache-control`),n);return t===void 0?r??0:r===void 0?t:Math.min(t,r)}function parseCacheDeltaSeconds(e,t){let n;if(!e)return;for(let r of e.split(`,`)){let e=r.trim(),i=e.indexOf(`=`);if(i===-1||e.slice(0,i).trim().toLowerCase()!==t)continue;if(n!==void 0)return;let a=/^(?:"(\d+)"|(\d+))$/.exec(e.slice(i+1).trim());if(!a)return;n=Number(a[1]??a[2])}if(n===void 0||!Number.isSafeInteger(n))return;let r=n*1e3;return Number.isSafeInteger(r)?r:void 0}function parseAge(e){if(!e||!/^\d+$/.test(e.trim()))return 0;let t=Number(e);return Number.isSafeInteger(t)?t:0}function hasResponseValidator$1(e){return e.has(`etag`)||e.has(`last-modified`)}function isRequestCacheControlHeader$1(e){return e===`cache-control`||e===`pragma`}function isCacheableRequest(e,t,n){return t.has(e.method??`GET`)&&(!hasRequestBody(e)||!!n.key)&&(!e.parseJson||!!n.key)&&(!e.querySerializer||!!n.key)&&e.responseType!==`stream`&&e.responseType!==`sse`&&e.responseType!==`ndjson`&&e.responseType!==`bytes`&&e.responseType!==`formData`&&e.fetchOptions?.mode!==`no-cors`&&e.fetchOptions?.redirect!==`manual`}function hasRequestBody(e){return e.body!=null||e.json!==void 0||e.form!=null||e.formData!=null}function isAsyncIterable(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}function isSchemaValidationFailure(t){return e.n(t)&&t.code===`SCHEMA_ERROR`}function canUseStaleIfError(e,t,n,r){try{if(n&&!e.raw||hasConditionalRequestHeaders(t))return!1;let i=resolveStaleIfErrorWindow(new Headers(e.headers),r);return i>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+i}catch{return!1}}function canUseStaleWhileRevalidate(e,t,n,r){try{if(n&&!e.raw)return!1;let i=new Headers(e.headers);if(hasConditionalRequestHeaders(t)||hasCacheControlDirective(i,`no-cache`)||hasCacheControlDirective(i,`must-revalidate`))return!1;let a=resolveStaleWhileRevalidateWindow(i,r);return a>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+a}catch{return!1}}function startBackgroundRefresh(e,t,n,r,i,a){if(t.has(n))return;let o=new AbortController,s={...r,signal:o.signal};t.set(n,o),a(`background-refresh`),Promise.resolve().then(()=>e.dispatch(s,{background:!0,preserveRaw:i})).then(()=>a(`background-refresh-success`),()=>a(`background-refresh-error`)).finally(()=>{t.get(n)===o&&t.delete(n)})}function abortBackgroundRefreshes(e){for(let t of e.values())t.abort(`Cache background refresh stopped`);e.clear()}function isEligibleStaleIfError(t){return e.n(t)&&(t.code===`NETWORK_ERROR`||t.code===`TIMEOUT_ERROR`||t.code===`HTTP_ERROR`&&t.status!==void 0&&t.status>=500&&t.status<600)}function canRevalidateCacheEntry(e,t,n){try{return n&&!e.raw||hasConditionalRequestHeaders(t)?!1:hasResponseValidator(new Headers(e.headers))}catch{return!1}}function prepareConditionalRevalidation(e,t){let n=new Headers(t.headers),r=n.get(`etag`),i=n.get(`last-modified`);if(!r&&!i)return!1;let a=new Headers(e.headers);r&&a.set(`if-none-match`,r),i&&a.set(`if-modified-since`,i);let o=e.validateStatus,s=e.throwHttpErrors;return e.headers=a,e.throwHttpErrors=void 0,e.validateStatus=e=>e===304||(o?o(e):s===!1||e>=200&&e<300),!0}function hasResponseValidator(e){return e.has(`etag`)||e.has(`last-modified`)}function hasConditionalRequestHeaders(e){let t=new Headers(e.headers);return t.has(`if-none-match`)||t.has(`if-modified-since`)||t.has(`range`)}function normalizeCacheTtl(t,n){let r=t??3e4;if(r!==1/0&&(!Number.isFinite(r)||r<0))throw new e.t(`Cache ttl must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return r}function normalizeCacheStatus(t,n){let r=t??200;if(!Number.isInteger(r)||r<200||r>599)throw new e.t(`Cache status must be an integer between 200 and 599`,{code:`CONFIG_ERROR`,config:n});return r}function normalizeStaleIfError(t,n){if(t!==void 0){if(t!==1/0&&(!Number.isFinite(t)||t<0))throw new e.t(`Cache staleIfError must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return t}}function normalizeStaleWhileRevalidate(t,n){if(t!==void 0){if(t!==1/0&&(!Number.isFinite(t)||t<0))throw new e.t(`Cache staleWhileRevalidate must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return t}}function normalizeCacheTags(t,n){if(t===void 0)return[];if(typeof t!=`string`&&!Array.isArray(t))throw new e.t(`Cache tags must be an array of strings`,{code:`CONFIG_ERROR`,config:n});let r=typeof t==`string`?[t]:t;if(r.length>32)throw new e.t(`Cache tags cannot contain more than 32 values`,{code:`CONFIG_ERROR`,config:n});let i=new Set;for(let t of r){if(typeof t!=`string`||t.length===0||t.length>128)throw new e.t(`Cache tags must contain 1 to 128 characters`,{code:`CONFIG_ERROR`,config:n});i.add(t)}return[...i]}function isExpired(e){return e!==1/0&&(Number.isNaN(e)||Date.now()>=e)}var MemoryCacheStore=class{constructor(e={}){this.entries=new Map,this.maxEntries=normalizeMaxEntries(e.maxEntries)}get(e){let t=this.entries.get(e);if(t)return this.newestKey!==e&&(this.entries.delete(e),this.entries.set(e,t),this.newestKey=e),t}set(e,t){if(this.maxEntries!==0){for(this.entries.delete(e);this.entries.size>=this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e)}this.entries.set(e,t),this.newestKey=e}}delete(e){this.entries.delete(e),this.newestKey===e&&(this.newestKey=void 0)}invalidateTags(e){let t=new Set(e),n=0;for(let[e,r]of this.entries)r.tags?.some(e=>t.has(e))&&(this.entries.delete(e),n+=1,this.newestKey===e&&(this.newestKey=void 0));return n}clear(){this.entries.clear(),this.newestKey=void 0}},WebStorageCacheStore=class{constructor(e,t={}){this.storage=e,this.prefix=createWebStoragePrefix(t.namespace),this.maxEntries=normalizeMaxEntries(t.maxEntries)}get(e){if(this.maxEntries===0)return;let t=this.prefix+e,n=this.read(t);if(n){try{this.storage.setItem(t,serializeWebStorageEntry(n.entry,Date.now()))}catch{}return n.entry}}set(e,t){if(this.maxEntries===0)return;let n=this.prefix+e,r=this.keys(),i=r.includes(n),a=Math.max(0,r.length-this.maxEntries+ +!i);if(a>0){let e=r.map(e=>({key:e,accessedAt:this.read(e)?.accessedAt??0})).filter(e=>e.key!==n).sort((e,t)=>e.accessedAt-t.accessedAt);for(let t of e.slice(0,a))this.storage.removeItem(t.key)}this.storage.setItem(n,serializeWebStorageEntry(t,Date.now()))}delete(e){this.storage.removeItem(this.prefix+e)}invalidateTags(e){let t=new Set(e),n=0;for(let e of this.keys())this.read(e)?.entry.tags?.some(e=>t.has(e))&&(this.storage.removeItem(e),n+=1);return n}clear(){for(let e of this.keys())this.storage.removeItem(e)}keys(){let e=[];for(let t=0;t<this.storage.length;t+=1){let n=this.storage.key(t);n?.startsWith(this.prefix)&&e.push(n)}return e}read(e){let t=this.storage.getItem(e);if(t!==null)try{return parseWebStorageEntry(t)}catch{this.storage.removeItem(e);return}}};function normalizeMaxEntries(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function createWebStoragePrefix(t=`default`){if(typeof t!=`string`||t.length===0||t.length>128)throw new e.t(`Web storage cache namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return`@npora/request:${encodeURIComponent(t)}:`}function serializeWebStorageEntry(e,t){return JSON.stringify({version:1,data:e.data,expiresAt:e.expiresAt===1/0?null:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags,accessedAt:t})}function parseWebStorageEntry(e){let t=JSON.parse(e),n=t.expiresAt===null?1/0:t.expiresAt;if(t.version!==1||n!==1/0&&(typeof n!=`number`||!Number.isFinite(n))||typeof t.status!=`number`||!Number.isInteger(t.status)||t.status<200||t.status>599||typeof t.statusText!=`string`||!Array.isArray(t.headers)||typeof t.accessedAt!=`number`||!Number.isFinite(t.accessedAt))throw TypeError(`Invalid web storage cache entry`);let r=t.tags===void 0?void 0:normalizeCacheTags(t.tags);return{entry:{data:t.data,expiresAt:n,status:t.status,statusText:t.statusText,headers:[...new Headers(t.headers).entries()],tags:r&&r.length>0?r:void 0},accessedAt:t.accessedAt}}const o=[];function createCacheKey(e,t,n,r,i){if(t.key)return t.key;let a=e.method??`GET`,s=String(e.url),c=e.responseType??`auto`,l=!e.headers&&!e.query&&!e.searchParams;if(l&&i.key!==void 0&&i.method===a&&i.baseURL===e.baseURL&&i.url===s&&i.responseType===c)return i.key;let u=JSON.stringify({method:a,baseURL:e.baseURL,url:s,query:l?o:normalizeQuery(e.searchParams??e.query),responseType:c,headers:e.headers?normalizeCacheHeaders(new Headers(e.headers),n):r});return l&&(i.method=a,i.baseURL=e.baseURL,i.url=s,i.responseType=c,i.key=u),u}function normalizeCacheHeaders(e,t){let n=[];e?.forEach((e,t)=>{isRequestCacheControlHeader(t)||n.push([t,e])});for(let r of t)!isRequestCacheControlHeader(r)&&!e?.has(r)&&n.push([r,null]);return n.sort(([e],[t])=>e.localeCompare(t))}function isRequestCacheControlHeader(e){return e===`cache-control`||e===`pragma`}function normalizeVaryHeaders(e){return[...new Set(e.map(e=>e.toLowerCase()))]}function normalizeQuery(e){if(!e)return o;if(t.r(e))return[...e.entries()];let n=[];for(let t of Object.keys(e).sort())appendQueryValue(n,t,e[t]);return n}function appendQueryValue(e,t,n){if(n!==void 0){if(n===null){e.push([t,``]);return}if(Array.isArray(n)){for(let r of n)appendQueryValue(e,t,r);return}e.push([t,String(n)])}}function acquireCacheGeneration(e,t,n,r){let i=n.get(t);i||(i={activeRequests:0,tags:new Set},n.set(t,i)),i.activeRequests+=1;for(let e of r)i.tags.add(e);return{global:e,key:t,token:i}}function isCurrentCacheGeneration(e,t,n){return e!==void 0&&e.global===t&&n.get(e.key)===e.token}function releaseCacheGeneration(e,t){--e.token.activeRequests,e.token.activeRequests===0&&t.get(e.key)===e.token&&t.delete(e.key)}function createInFlightRequest(e,t,n){return{owner:e,key:t,generation:n}}function getInFlightPromise(e){if(e.promise)return e.promise;let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.catch(()=>{}),e.promise=r,e.resolve=t,e.reject=n,r}function readStore(e,t){try{let r=e.get(t);return n.t(r)?Promise.resolve(r).catch(()=>void 0):r}catch{return}}function writeStore(e,t,r){try{let i=e.set(t,r);if(n.t(i))return Promise.resolve(i).catch(ignoreStoreError)}catch{}}function deleteStore(e,t){try{let r=e.delete(t);if(n.t(r))return Promise.resolve(r).catch(ignoreStoreError)}catch{}}function ignoreStoreError(){}function waitForSharedRecord(e,t){let n=t.signal;return n?n.aborted?Promise.reject(createSharedAbortError(n.reason,t)):new Promise((r,i)=>{let a=!1,cleanup=()=>{try{n.removeEventListener(`abort`,onAbort)}catch{}},resolveOnce=e=>{a||(a=!0,cleanup(),r(e))},rejectOnce=e=>{a||(a=!0,cleanup(),i(e))},onAbort=()=>{rejectOnce(createSharedAbortError(n.reason,t))};try{n.addEventListener(`abort`,onAbort,{once:!0})}catch(e){rejectOnce(e);return}n.aborted&&onAbort(),!a&&e.then(resolveOnce,e=>{rejectOnce(cloneSharedError(e,t))})}):e.catch(e=>{throw cloneSharedError(e,t)})}function createSharedAbortError(t,n){return new e.t(`Request aborted while waiting for shared response`,{code:`ABORT_ERROR`,config:n,cause:t})}function cloneSharedError(t,n){return e.n(t)?new e.t(t.message,{code:t.code,status:t.status,data:t.data,response:t.response,config:n,cause:t}):t}function createCacheEntry(e,t,n,r){return{data:cloneCacheValue(e.data),expiresAt:t,status:e.status,statusText:e.statusText,headers:[...e.headers.entries()],tags:r?[...r]:void 0,raw:n?cloneResponse(e.raw):void 0}}function createCachedResponse(e,t){return{data:cloneCacheValue(e.data),status:e.status,statusText:e.statusText,headers:new Headers(e.headers),config:t,raw:cloneRawResponse(e)}}function restoreCacheEntry(e,t){try{return createCachedResponse(e,t)}catch{return}}function createRevalidatedResponse(e,t,n){let r=new Headers(e.headers);return t.headers.forEach((e,t)=>{r.set(t,e)}),createCachedResponse({...e,headers:[...r.entries()]},n)}function cloneRawResponse(e){if(e.raw){let t=cloneResponse(e.raw);if(t)return new Response(t.body,{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})}function cloneResponse(e){try{return e.clone()}catch{return}}function cloneCacheValue(e){if(typeof e!=`object`||!e||typeof structuredClone!=`function`)return e;try{return structuredClone(e)}catch{return e}}const s=`entries`,c=`namespace`;var IndexedDBCacheStore=class{constructor(e,t={}){this.namespace=normalizeIndexedDBName(t.namespace,`namespace`,`default`),this.maxEntries=normalizeIndexedDBMaxEntries(t.maxEntries),this.maxBytes=normalizeIndexedDBMaxBytes(t.maxBytes),this.quotaRecovery=normalizeQuotaRecovery(t.quotaRecovery),this.shouldPersist=normalizeIndexedDBAdmissionPolicy(t.shouldPersist),this.onEvent=normalizeIndexedDBEventObserver(t.onEvent),this.schemaVersion=normalizeIndexedDBSchemaVersion(t.schemaVersion),this.databaseName=normalizeIndexedDBName(t.databaseName,`database name`,`@npora/request-cache`),this.factory=e}async get(e){if(this.maxEntries===0||this.maxBytes===0){await this.delete(e);return}let t=(await this.getDatabase()).transaction(s,`readwrite`),n=waitForTransaction(t),r=t.objectStore(s),i=this.createKey(e),a=await waitForRequest(r.get(i)),o=isFutureIndexedDBRecord(a,this.schemaVersion);if(!isValidIndexedDBRecord(a,this.namespace,i,this.schemaVersion)){a!==void 0&&!o&&r.delete(i),await n,a!==void 0&&!o&&this.emitEvent({type:`eviction`,reason:`malformed`,entries:1,estimatedBytes:readIndexedDBRecordSize(a)});return}return a.accessedAt=Date.now(),a.size=readIndexedDBRecordSize(a),r.put(a),await n,toPortableCacheEntry(a)}async set(t,n){if(this.maxEntries===0||this.maxBytes===0){await this.delete(t);return}let r=await this.getDatabase(),i={...toPortableCacheEntry(n),key:this.createKey(t),namespace:this.namespace,accessedAt:Date.now(),schemaVersion:this.schemaVersion};if(i.size=estimateStructuredCloneSize(i),i.size>this.maxBytes){await this.delete(t),this.emitEvent({type:`rejection`,reason:`oversized`,entries:1,estimatedBytes:i.size});return}let a=!this.shouldPersist||await this.shouldPersist(toPortableCacheEntry(i),i.size);if(typeof a!=`boolean`)throw new e.t(`IndexedDB cache shouldPersist must return a boolean`,{code:`CONFIG_ERROR`});if(!a){await this.delete(t),this.emitEvent({type:`rejection`,reason:`admission-policy`,entries:1,estimatedBytes:i.size});return}try{await this.writeRecord(r,i)}catch(e){if(!this.quotaRecovery||!isQuotaExceededError(e)||!await this.recoverQuota(r))throw e;await this.writeRecord(r,i)}}async delete(e){let t=(await this.getDatabase()).transaction(s,`readwrite`),n=waitForTransaction(t),r=t.objectStore(s),i=this.createKey(e);isFutureIndexedDBRecord(await waitForRequest(r.get(i)),this.schemaVersion)||r.delete(i),await n}async invalidateTags(e){let t=new Set(e),n=0;return await this.visitNamespace(e=>e.tags?.some(e=>t.has(e))?(n+=1,!0):!1),n}async clear(){await this.visitNamespace(()=>!0)}async getUsage(){let e=(await this.getDatabase()).transaction(s,`readonly`),t=waitForTransaction(e),n=e.objectStore(s).index(c).openCursor(this.namespace),r=0,i=0;return await visitCursor(n,e=>{let t=e.value;isValidIndexedDBRecord(t,this.namespace,void 0,this.schemaVersion)&&(r+=1,i=addSizes(i,readIndexedDBRecordSize(t)))}),await t,{entries:r,estimatedBytes:i,maxEntries:this.maxEntries,maxBytes:this.maxBytes,schemaVersion:this.schemaVersion}}async compact(e={}){let t=normalizeCompactionBoundary(e.expiredBefore),n=normalizeCompactionMaxRemovals(e.maxRemovals),r=(await this.getDatabase()).transaction(s,`readwrite`),i=waitForTransaction(r),a=r.objectStore(s).index(c).openCursor(this.namespace),o=new Map,l=0,u=0,d=0,f=!1;return await visitCursor(a,e=>{let r=e.value,i=classifyIndexedDBRecord(r,this.namespace,this.schemaVersion);if(l+=1,i===`malformed`||i===`schema-version`)e.delete(),addCleanupSummary(o,i,r),u+=1,d=addSizes(d,readIndexedDBRecordSize(r));else if(i===`current`&&r.expiresAt<=t){let t=readIndexedDBRecordSize(r);e.delete(),addCleanupSummary(o,`expired`,r),u+=1,d=addSizes(d,t)}if(u>=n)return f=!0,!1}),await i,this.emitCleanupSummaries(o.values()),{scannedEntries:l,removedEntries:u,estimatedBytesFreed:d,expiredBefore:t,hasMore:f}}async close(){let e=this.database;e&&(this.database=void 0,(await e).close())}createKey(e){return this.schemaVersion===1?`${this.namespace}\0${e}`:`${this.namespace}\0@npora-schema:${this.schemaVersion}\0${e}`}async writeRecord(e,t){let n=e.transaction(s,`readwrite`),r=waitForTransaction(n),i=n.objectStore(s),a=new Map;if(isFutureIndexedDBRecord(await waitForRequest(i.get(t.key)),this.schemaVersion)){await r;return}if(i.put(t),this.maxEntries!==1/0||this.maxBytes!==1/0){let e=await waitForRequest(i.index(c).getAll(this.namespace)),n=[];for(let t of e){let e=classifyIndexedDBRecord(t,this.namespace,this.schemaVersion);e===`malformed`||e===`schema-version`?(i.delete(t.key),addCleanupSummary(a,e,t)):e===`current`&&n.push(t)}n.sort((e,n)=>e.key===t.key?1:n.key===t.key?-1:e.accessedAt-n.accessedAt||e.key.localeCompare(n.key));let r=n.reduce((e,t)=>addSizes(e,readIndexedDBRecordSize(t)),0),o=n.length;for(let e of n){if(o<=this.maxEntries&&r<=this.maxBytes)break;i.delete(e.key),addCleanupSummary(a,r>this.maxBytes?`max-bytes`:`max-entries`,e),--o,r=Math.max(0,r-readIndexedDBRecordSize(e))}}await r,this.emitCleanupSummaries(a.values())}async recoverQuota(e){let t=e.transaction(s,`readwrite`),n=waitForTransaction(t),r=t.objectStore(s),i=await waitForRequest(r.index(c).getAll(this.namespace)),a=[],o=new Map,l=!1;for(let e of i){let t=classifyIndexedDBRecord(e,this.namespace,this.schemaVersion);t===`malformed`||t===`schema-version`?(r.delete(e.key),addCleanupSummary(o,t,e),l=!0):t===`current`&&a.push(e)}a.sort((e,t)=>e.accessedAt-t.accessedAt||e.key.localeCompare(t.key));for(let e of a.slice(0,Math.max(1,Math.ceil(a.length/2))))r.delete(e.key),addCleanupSummary(o,`quota-recovery`,e),l=!0;return await n,this.emitCleanupSummaries(o.values()),l}emitCleanupSummaries(e){for(let t of e)this.emitEvent({type:`eviction`,...t})}emitEvent(e){if(this.onEvent)try{Promise.resolve(this.onEvent({...e,timestamp:Date.now()})).catch(()=>{})}catch{}}async visitNamespace(e){let t=(await this.getDatabase()).transaction(s,`readwrite`),n=waitForTransaction(t),r=t.objectStore(s).index(c).openCursor(this.namespace),i=new Map;await visitCursor(r,t=>{let n=t.value,r=classifyIndexedDBRecord(n,this.namespace,this.schemaVersion);(r===`malformed`||r===`schema-version`||r===`current`&&e(n))&&(t.delete(),(r===`malformed`||r===`schema-version`)&&addCleanupSummary(i,r,n))}),await n,this.emitCleanupSummaries(i.values())}getDatabase(){return this.database??(this.database=openCacheDatabase(this.factory,this.databaseName).then(async e=>{try{let t=await pruneOlderSchemaRecords(e,this.namespace,this.schemaVersion);return this.emitCleanupSummaries(t),e}catch(t){throw e.close(),t}})),this.database}};function openCacheDatabase(e,t){return new Promise((n,r)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(s)||e.createObjectStore(s,{keyPath:`key`}).createIndex(c,c,{unique:!1})},i.onerror=()=>r(i.error),i.onsuccess=()=>{let e=i.result;e.onversionchange=()=>e.close(),n(e)}})}function waitForRequest(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)})}function waitForTransaction(e){let t=new Promise((t,n)=>{let rejectWithTransactionError=t=>{n(e.error??readIDBRequestError(t.target)??Error(`IndexedDB transaction failed`))};e.onabort=rejectWithTransactionError,e.onerror=rejectWithTransactionError,e.oncomplete=()=>t()});return t.catch(()=>{}),t}function readIDBRequestError(e){if(!e||!(`error`in e))return null;let t=e.error;return t instanceof DOMException?t:null}function visitCursor(e,t){return new Promise((n,r)=>{e.onerror=()=>r(e.error),e.onsuccess=()=>{let i=e.result;if(!i){n();return}try{if(t(i)===!1){n();return}}catch(t){try{readCursorTransaction(e)?.abort()}catch{}r(t);return}i.continue()}})}function readCursorTransaction(e){let t=e.source;if(t)return`transaction`in t?t.transaction:`objectStore`in t?t.objectStore.transaction:`transaction`in t.source?t.source.transaction:t.source.objectStore.transaction}function toPortableCacheEntry(e){return{data:e.data,expiresAt:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags}}function isValidIndexedDBRecord(e,t,n,r=1){if(!e||typeof e!=`object`)return!1;let i=e;if(!(typeof i.key==`string`&&(n===void 0||i.key===n)&&i.namespace===t&&readIndexedDBSchemaVersion(i)===r&&(i.expiresAt===1/0||Number.isFinite(i.expiresAt))&&Number.isInteger(i.status)&&i.status>=200&&i.status<=599&&typeof i.statusText==`string`&&Array.isArray(i.headers)&&(i.tags===void 0||Array.isArray(i.tags)&&i.tags.length<=32&&i.tags.every(e=>typeof e==`string`&&e.length>0&&e.length<=128))&&Number.isFinite(i.accessedAt)))return!1;try{return new Headers(i.headers),!0}catch{return!1}}function readIndexedDBSchemaVersion(e){if(!e||typeof e!=`object`)return;let t=e.schemaVersion??1;return Number.isSafeInteger(t)&&t>=1&&t<=1e9?t:void 0}function classifyIndexedDBRecord(e,t,n){let r=readIndexedDBSchemaVersion(e);return r===void 0?`malformed`:r>n?`future`:r<n?`schema-version`:isValidIndexedDBRecord(e,t,void 0,n)?`current`:`malformed`}function isFutureIndexedDBRecord(e,t){let n=readIndexedDBSchemaVersion(e);return n!==void 0&&n>t}function readIndexedDBRecordSize(e){let t=e&&typeof e==`object`?e.size:void 0;return Number.isSafeInteger(t)&&t>=0?t:estimateStructuredCloneSize(e)}function estimateStructuredCloneSize(e,n=new WeakSet){if(e==null)return 0;if(typeof e==`string`)return Math.min(2**53-1,e.length*2);if(typeof e==`number`||typeof e==`bigint`)return 8;if(typeof e==`boolean`)return 4;if(typeof e!=`object`)return 0;if(n.has(e)||(n.add(e),e instanceof Date))return 8;if(t.n(e))return e.size;if(t.t(e)||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Map){let t=16;for(let[r,i]of e)t=addSizes(t,estimateStructuredCloneSize(r,n),estimateStructuredCloneSize(i,n));return t}if(e instanceof Set){let t=16;for(let r of e)t=addSizes(t,estimateStructuredCloneSize(r,n));return t}let r=Array.isArray(e)?16:32;for(let[t,i]of Object.entries(e))r=addSizes(r,t.length*2,estimateStructuredCloneSize(i,n));return r}function addSizes(...e){let t=0;for(let n of e){if(n>=2**53-1-t)return 2**53-1;t+=n}return t}function addCleanupSummary(e,t,n){let r=e.get(t),i=readIndexedDBRecordSize(n);if(r){r.entries+=1,r.estimatedBytes=addSizes(r.estimatedBytes,i);return}e.set(t,{reason:t,entries:1,estimatedBytes:i})}function isQuotaExceededError(e){return!!(e&&typeof e==`object`&&e.name===`QuotaExceededError`)}async function pruneOlderSchemaRecords(e,t,n){let r=e.transaction(s,`readwrite`),i=waitForTransaction(r),a=r.objectStore(s).index(c).openCursor(t),o=new Map;return await visitCursor(a,e=>{let r=e.value,i=classifyIndexedDBRecord(r,t,n);(i===`malformed`||i===`schema-version`)&&(e.delete(),addCleanupSummary(o,i,r))}),await i,[...o.values()]}function normalizeIndexedDBName(t,n,r){let i=t??r;if(typeof i!=`string`||i.length===0||i.length>128)throw new e.t(`IndexedDB cache ${n} must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return i}function normalizeIndexedDBMaxEntries(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function normalizeIndexedDBMaxBytes(t){if(t===void 0)return 1/0;if(t===1/0)return t;if(!Number.isSafeInteger(t)||t<0)throw new e.t(`IndexedDB cache maxBytes must be a non-negative safe integer or Infinity`,{code:`CONFIG_ERROR`});return t}function normalizeQuotaRecovery(t){if(t===void 0)return!0;if(typeof t!=`boolean`)throw new e.t(`IndexedDB cache quotaRecovery must be a boolean`,{code:`CONFIG_ERROR`});return t}function normalizeIndexedDBEventObserver(t){if(t!==void 0&&typeof t!=`function`)throw new e.t(`IndexedDB cache onEvent must be a function`,{code:`CONFIG_ERROR`});return t}function normalizeIndexedDBAdmissionPolicy(t){if(t!==void 0&&typeof t!=`function`)throw new e.t(`IndexedDB cache shouldPersist must be a function`,{code:`CONFIG_ERROR`});return t}function normalizeCompactionBoundary(t){let n=t??Date.now();if(!Number.isFinite(n))throw new e.t(`IndexedDB cache compact expiredBefore must be finite`,{code:`CONFIG_ERROR`});return n}function normalizeCompactionMaxRemovals(t){if(t===void 0||t===1/0)return 1/0;if(!Number.isSafeInteger(t)||t<1)throw new e.t(`IndexedDB cache compact maxRemovals must be a positive safe integer or Infinity`,{code:`CONFIG_ERROR`});return t}function normalizeIndexedDBSchemaVersion(t){let n=t??1;if(!Number.isSafeInteger(n)||n<1||n>1e9)throw new e.t(`IndexedDB cache schemaVersion must be an integer from 1 to 1000000000`,{code:`CONFIG_ERROR`});return n}var TieredCacheStore=class{constructor(t){if(this.leaseReleases=new Set,this.source=`${Date.now()}:${Math.random()}`,this.trackedKeys=new Map,this.trackedKeyCount=0,this.handleMessage=e=>{let t=e.data;if(!isTieredCacheMessage(t)||t.source===this.source)return;if(t.action===`clear`){this.clearPrimary();return}let n=this.trackedKeys.get(t.fingerprint);if(!n){this.clearPrimary();return}this.trackedKeys.delete(t.fingerprint),this.trackedKeyCount-=n.size;for(let e of n)ignoreStoreResult(()=>this.primary.delete(e))},!t||!t.primary||!t.secondary||t.primary===t.secondary)throw new e.t(`Tiered cache requires distinct primary and secondary stores`,{code:`CONFIG_ERROR`});if(this.primary=t.primary,this.secondary=t.secondary,t.broadcast&&!t.broadcast.channel)throw new e.t(`Tiered cache broadcast requires a channel`,{code:`CONFIG_ERROR`});if(t.coordination&&!t.coordination.locks)throw new e.t(`Tiered cache coordination requires a lock manager`,{code:`CONFIG_ERROR`});this.channel=t.broadcast?.channel,this.locks=t.coordination?.locks,this.lockNamespace=normalizeLockNamespace(t.coordination?.namespace),this.maxTrackedKeys=normalizeTrackedKeys(t.broadcast?.maxTrackedKeys),this.locks&&(this.acquireRefreshLease=(e,t)=>this.acquireCoordinatedLease(e,t)),this.channel?.addEventListener(`message`,this.handleMessage)}get(e){let t;try{t=this.primary.get(e)}catch{return this.readSecondary(e)}return n.t(t)?Promise.resolve(t).then(t=>t?this.remember(e,t):this.readSecondary(e),()=>this.readSecondary(e)):t?this.remember(e,t):this.readSecondary(e)}set(e,t){let writePrimary=()=>{let r;try{r=this.primary.set(e,t)}catch(t){throw this.recoverPrimaryWrite(e),t}return n.t(r)?Promise.resolve(r).catch(t=>{throw this.recoverPrimaryWrite(e),t}):r},r=this.secondary.set(e,t),i=n.t(r)?Promise.resolve(r).then(writePrimary):writePrimary();return this.afterSuccess(i,()=>{this.trackKey(e),this.broadcastKey(e)})}delete(e){return this.afterSettled(()=>combineStoreOperations([()=>this.primary.delete(e),()=>this.secondary.delete(e)],()=>void 0),()=>{this.untrackKey(e),this.broadcastKey(e)})}invalidateTags(t){let n=this.primary.invalidateTags,r=this.secondary.invalidateTags;if(!n||!r)throw new e.t(`Both tiered cache stores must support tag invalidation`,{code:`CONFIG_ERROR`});return this.afterSettled(()=>combineStoreOperations([()=>n.call(this.primary,t),()=>r.call(this.secondary,t)],e=>Math.max(...e)),()=>this.broadcastClear())}clear(){return this.afterSettled(()=>combineStoreOperations([()=>this.primary.clear(),()=>this.secondary.clear()],()=>void 0),()=>this.broadcastClear())}async acquireCoordinatedLease(t,n){let r=`${this.lockNamespace}:${fingerprintCacheKey(t)}`,i=await this.requestLease(r,!0,n);if(i)return i;let a=await this.requestLease(r,!1,n);if(!a)throw new e.t(`Cache refresh lock was unavailable`,{code:`NETWORK_ERROR`});return await ignoreStoreFailure(()=>this.primary.delete(t)),a}dispose(){this.channel?.removeEventListener(`message`,this.handleMessage);for(let e of this.leaseReleases)e();this.leaseReleases.clear(),this.trackedKeys.clear(),this.trackedKeyCount=0}requestLease(e,t,n){return new Promise((r,i)=>{let a=!1,o=createDeferred(),s={mode:`exclusive`,ifAvailable:t};n&&(s.signal=n),this.locks.request(e,s,async e=>{if(!e){a=!0,r(void 0);return}let n=!0,release=()=>{n&&(n=!1,this.leaseReleases.delete(release),o.resolve())};this.leaseReleases.add(release),a=!0,r({contended:!t,release}),await o.promise}).catch(e=>{a||i(e)})})}readSecondary(e){let promote=t=>{if(t){try{let r=this.primary.set(e,t);if(n.t(r))return Promise.resolve(r).then(()=>this.remember(e,t),()=>this.remember(e,t))}catch{}return this.remember(e,t)}},t=this.secondary.get(e);return n.t(t)?Promise.resolve(t).then(promote):promote(t)}remember(e,t){return this.trackKey(e),t}trackKey(e){if(!this.channel)return;let t=fingerprintCacheKey(e),n=this.trackedKeys.get(t);if(n?.has(e)){this.trackedKeys.delete(t),this.trackedKeys.set(t,n);return}for(;this.trackedKeyCount>=this.maxTrackedKeys;){let e=this.trackedKeys.entries().next().value;if(!e)break;this.trackedKeys.delete(e[0]),this.trackedKeyCount-=e[1].size}n??(n=new Set),n.add(e),this.trackedKeys.delete(t),this.trackedKeys.set(t,n),this.trackedKeyCount+=1}untrackKey(e){let t=fingerprintCacheKey(e),n=this.trackedKeys.get(t);n?.delete(e)&&(--this.trackedKeyCount,n.size===0&&this.trackedKeys.delete(t))}broadcastKey(e){this.postMessage({protocol:`npora-cache:1`,source:this.source,action:`delete`,fingerprint:fingerprintCacheKey(e)})}broadcastClear(){this.trackedKeys.clear(),this.trackedKeyCount=0,this.postMessage({protocol:`npora-cache:1`,source:this.source,action:`clear`})}postMessage(e){try{this.channel?.postMessage(e)}catch{}}clearPrimary(){this.trackedKeys.clear(),this.trackedKeyCount=0,ignoreStoreResult(()=>this.primary.clear())}recoverPrimaryWrite(e){this.untrackKey(e),ignoreStoreResult(()=>this.primary.delete(e)),this.broadcastKey(e)}afterSuccess(e,t){return n.t(e)?Promise.resolve(e).then(e=>(t(),e)):(t(),e)}afterSettled(e,t){let r;try{r=e()}catch(e){throw t(),e}return n.t(r)?Promise.resolve(r).then(e=>(t(),e),e=>{throw t(),e}):(t(),r)}};function combineStoreOperations(e,t){let r=[],i=[],a,o=!1;for(let t of e)try{let e=t();n.t(e)?i.push(Promise.resolve(e).then(e=>{r.push(e)},e=>{o||(o=!0,a=e)})):r.push(e)}catch(e){o||(o=!0,a=e)}let finish=()=>{if(o)throw a;return t(r)};return i.length>0?Promise.all(i).then(finish):finish()}function fingerprintCacheKey(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function isTieredCacheMessage(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.protocol===`npora-cache:1`&&typeof t.source==`string`&&(t.action===`clear`||t.action===`delete`&&typeof t.fingerprint==`string`&&t.fingerprint.length<=16)}function normalizeTrackedKeys(t){let n=t??1e3;if(!Number.isInteger(n)||n<1||n>1e5)throw new e.t(`Tiered cache maxTrackedKeys must be an integer from 1 to 100000`,{code:`CONFIG_ERROR`});return n}function normalizeLockNamespace(t){let n=t??`npora-cache`;if(typeof n!=`string`||n.length<1||n.length>128)throw new e.t(`Tiered cache lock namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return n}function createDeferred(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}function ignoreStoreResult(e){try{let t=e();n.t(t)&&Promise.resolve(t).catch(()=>{})}catch{}}async function ignoreStoreFailure(e){try{await e()}catch{}}const l=[`GET`,`HEAD`],u=[`authorization`,`cookie`,`accept`,`accept-language`],d={hit:`hits`,miss:`misses`,bypass:`bypasses`,invalidated:`invalidations`,"invalidation-error":`invalidationErrors`,deduplicated:`deduplicated`,revalidated:`revalidations`,"stale-if-error":`staleIfError`,"stale-while-revalidate":`staleWhileRevalidate`,"background-refresh":`backgroundRefreshes`,"background-refresh-success":`backgroundRefreshSuccesses`,"background-refresh-error":`backgroundRefreshErrors`};function createCacheStats(){return{hits:0,misses:0,bypasses:0,invalidations:0,invalidationErrors:0,deduplicated:0,revalidations:0,staleIfError:0,staleWhileRevalidate:0,backgroundRefreshes:0,backgroundRefreshSuccesses:0,backgroundRefreshErrors:0}}function resetCacheStats(e){Object.assign(e,createCacheStats())}function createCacheEventRecorder(e,t){return r=>{if(incrementCacheStat(e,r),t)try{let e=t({type:r,timestamp:Date.now()});n.t(e)&&Promise.resolve(e).catch(ignoreCacheEventError)}catch{}}}function incrementCacheStat(e,t){let n=d[t];e[n]=Math.min(2**53-1,e[n]+1)}function ignoreCacheEventError(){}function cachePlugin(t={}){let a=t.store??new MemoryCacheStore({maxEntries:t.maxEntries}),o=new WeakSet,s=new WeakMap,c=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,m=new WeakMap,h=new WeakSet,g=new WeakSet,_=new WeakMap,v=new WeakMap,y=new WeakSet,b=new WeakSet,x=new Map,S=new Map,C=new WeakSet,w=new Map,T=new Map,E=new Map,D=new Map,O=createCacheStats(),k=createCacheEventRecorder(O,t.onEvent),A=0,j=new Set(t.methods??l),M=normalizeVaryHeaders(t.varyHeaders??u),N=normalizeCacheHeaders(void 0,M),P={};function trackKeyOperation(e,t,n,r){let i=Promise.resolve(t),a;return a=i.then(()=>n&&k(n),()=>r&&k(r)).finally(()=>{E.get(e)===a&&E.delete(e)}),E.set(e,a),i}function runKeyOperation(e,t,r=[],i,a){let o=new Set(r),s=E.get(e);if(s&&o.add(s),o.size>0)return trackKeyOperation(e,Promise.all(o).then(t),i,a);let c;try{c=t()}catch(e){throw a&&k(a),e}return n.t(c)?trackKeyOperation(e,c,i,a):(i&&k(i),c)}function invalidateKeyState(e,t){T.delete(e),x.delete(e),S.delete(e);let n=w.get(e);n&&(w.delete(e),n.abort(t))}function trackTagInvalidation(e,t){let n=Promise.resolve(t),r;r=n.then(()=>k(`invalidated`),()=>k(`invalidation-error`)).finally(()=>{for(let t of e)D.get(t)===r&&D.delete(t)});for(let t of e)D.set(t,r);return n}let F={name:`cache`,clear(){return A+=1,x.clear(),S.clear(),T.clear(),abortBackgroundRefreshes(w),a.clear()},delete(e){let t=createCacheKey(e,i.t(e,`cache`)??{},M,N,P);return invalidateKeyState(t,`Cache entry invalidated`),runKeyOperation(t,()=>a.delete(t),[],`invalidated`,`invalidation-error`)},set(e,t,n={}){let r=i.t(e,`cache`)??{},o=createCacheKey(e,r,M,N,P),s=normalizeCacheTtl(n.ttl??r.ttl,e),c=normalizeCacheStatus(n.status,e),l=normalizeCacheTags(n.tags??r.tags,e),u={data:cloneCacheValue(t),expiresAt:s===1/0?s:Date.now()+s,status:c,statusText:n.statusText??(c===200?`OK`:``),headers:[...new Headers(n.headers).entries()],tags:l.length>0?l:void 0},d=l.map(e=>D.get(e)).filter(e=>!!e);return invalidateKeyState(o,`Cache entry replaced`),runKeyOperation(o,()=>a.set(o,u),d)},update(e,t){let r=createCacheKey(e,i.t(e,`cache`)??{},M,N,P);return invalidateKeyState(r,`Cache entry updated`),runKeyOperation(r,()=>{let updateEntry=e=>{if(!e)return!1;let i=t(cloneCacheValue(e.data));if(i===void 0){let e=a.delete(r);return!n.t(e)||Promise.resolve(e).then(()=>!0)}let o=a.set(r,{...e,data:cloneCacheValue(i),raw:void 0});return!n.t(o)||Promise.resolve(o).then(()=>!0)},e=a.get(r);return n.t(e)?Promise.resolve(e).then(updateEntry):updateEntry(e)},D.values())},invalidateTags(t){let r=normalizeCacheTags(t);if(r.length===0)throw new e.t(`Cache tag invalidation requires at least one tag`,{code:`CONFIG_ERROR`});let i=a.invalidateTags;if(!i)throw new e.t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`});for(let[e,t]of T)r.some(e=>t.tags.has(e))&&invalidateKeyState(e,`Cache tags invalidated`);let o=new Set(r.map(e=>D.get(e)).filter(e=>!!e));for(let e of E.values())o.add(e);if(o.size>0)return trackTagInvalidation(r,Promise.all(o).then(()=>i.call(a,r)));let s;try{s=i.call(a,r)}catch(e){throw k(`invalidation-error`),e}return n.t(s)?trackTagInvalidation(r,s):(k(`invalidated`),s)},getStats(){return{...O}},resetStats(){resetCacheStats(O)},install(l){let u=new Set,O=new Set,I=!0;l.hooks.onRequest(t=>{let o=i.t(t.config,`cache`);if(!o)return;let s=normalizeCacheTags(o.invalidateTags,t.config);if(s.length>0){if(!a.invalidateTags)throw new e.t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`,config:t.config});d.set(t,s)}if(!o.enabled||!isCacheableRequest(t.config,j,o))return;normalizeCacheTtl(o.ttl,t.config),normalizeStaleIfError(o.staleIfError,t.config),normalizeStaleWhileRevalidate(o.staleWhileRevalidate,t.config);let l=normalizeCacheTags(o.tags,t.config),u=resolveRequestCachePolicy(t.config);if(u===`no-store`){k(`bypass`),g.add(t);return}(u===`revalidate`||t.background)&&h.add(t);let f=createCacheKey(t.config,o,M,N,P),p=acquireCacheGeneration(A,f,T,l);c.set(t,p);let read=()=>{let e=readStore(a,f);return t.config.signal&&n.t(e)?r.t(()=>e,t.config).then(e=>{if(isCurrentCacheGeneration(p,A,T))return handleCacheRecord(t,o,f,e,p)}):n.t(e)?Promise.resolve(e).then(e=>{if(isCurrentCacheGeneration(p,A,T))return handleCacheRecord(t,o,f,e,p)}):handleCacheRecord(t,o,f,e,p)},m=new Set,_=E.get(f);_&&m.add(_);for(let e of l){let t=D.get(e);t&&m.add(t)}if(m.size>0){let e=Promise.all(m).then(()=>{});return t.config.signal?r.t(()=>e,t.config).then(read):e.then(read)}return read()}),l.hooks.onResponse(e=>{if(y.has(e)&&e.fallbackResponse){k(`stale-if-error`),o.add(e),e.cacheHit=!0,s.get(e)?.owner===e&&b.add(e);return}if(o.has(e))return;let t=i.t(e.config,`cache`);if(!t?.enabled||!e.response||!isCacheableRequest(e.config,j,t)||g.has(e))return;let l=m.get(e);if(e.response.raw.type===`opaque`||e.response.raw.type===`opaqueredirect`){s.get(e)?.owner===e&&b.add(e);return}l&&e.response.status===304&&(k(`revalidated`),e.response=createRevalidatedResponse(l,e.response,e.config));let u=s.get(e),d=u?.key??createCacheKey(e.config,t,M,N,P),h=isCurrentCacheGeneration(u?.generation??f.get(e)??c.get(e),A,T),_=(u?.generation??c.get(e))?.token.tags,v=_&&_.size>0?[..._]:l?.tags;if(isAsyncIterable(e.response.data)){if(b.add(e),!h)return;let t=deleteStore(a,d);return n.t(t)?e.config.signal?r.t(()=>t,e.config):t:void 0}let x=normalizeCacheTtl(t.ttl,e.config),S=normalizeStaleIfError(t.staleIfError,e.config),C=normalizeStaleWhileRevalidate(t.staleWhileRevalidate,e.config),w=resolveResponseCachePolicy(e.response,x,S,C),E=w.ttl;if(!w.persist){let t=h?deleteStore(a,d):void 0,i=n.t(t),o=u;return o?.owner===e&&(o.promise!==void 0||i)?p.set(e,createCacheEntry(e.response,Date.now()+Math.max(0,E),e.preserveRaw,v)):o?.owner===e&&b.add(e),i?e.config.signal?r.t(()=>t,e.config):t:void 0}let D=createCacheEntry(e.response,Date.now()+E,e.preserveRaw,v);if(p.set(e,D),!h||u?.rawDemanded)return;let O=writeStore(a,d,D);if(n.t(O))return e.config.signal?r.t(()=>O,e.config):O},{requiresRawResponse:!1});function handleCacheRecord(e,t,i,s,c){if(!(!I||!isCurrentCacheGeneration(c,A,T))){if(s){let u=!isExpired(s.expiresAt),d=h.has(e);if(u&&!d){if(e.preserveRaw&&!s.raw)return prepareCacheMiss(e,t,i,c);let n=restoreCacheEntry(s,e.config);if(n){k(`hit`),e.response=n,o.add(e),e.cacheHit=!0;return}}if(!e.background&&!d&&canUseStaleWhileRevalidate(s,e.config,e.preserveRaw,normalizeStaleWhileRevalidate(t.staleWhileRevalidate,e.config))){let t=restoreCacheEntry(s,e.config);if(t){k(`stale-while-revalidate`),e.response=t,o.add(e),e.cacheHit=!0,startBackgroundRefresh(l,w,i,e.initialConfig,e.preserveRaw,k);return}}if(!e.background&&canUseStaleIfError(s,e.config,e.preserveRaw,normalizeStaleIfError(t.staleIfError,e.config))&&_.set(e,s),canRevalidateCacheEntry(s,e.config,e.preserveRaw)&&restoreCacheEntry(s,e.config))return prepareCacheMiss(e,t,i,c,s);if(u&&d||e.background)return prepareCacheMiss(e,t,i,c);let f=deleteStore(a,i);if(n.t(f))return(e.config.signal?r.t(()=>f,e.config):Promise.resolve(f)).then(()=>prepareCacheMiss(e,t,i,c))}return prepareCacheMiss(e,t,i,c)}}function prepareCacheMiss(e,n,i,c,l){if(!I||!isCurrentCacheGeneration(c,A,T))return;if(!(n.dedupe??t.dedupe??!0)){e.background||k(`miss`),f.set(e,c);return}let d=e.preserveRaw?S.get(i):x.get(i)??S.get(i);if(d)return k(`deduplicated`),waitForSharedRecord(getInFlightPromise(d),e.config).then(t=>{t&&(e.response=createCachedResponse(t,e.config),o.add(e),e.cacheHit=!0)});let p=a.acquireRefreshLease;if(p&&!v.has(e)){let t;try{let n=p.call(a,i,e.config.signal);t=e.config.signal?r.t(()=>n,e.config):n}catch{return v.set(e,{contended:!1,release(){}}),handleCacheRecord(e,n,i,l,c)}return t.then(t=>(v.set(e,t),O.add(t),t.contended&&(h.delete(e),k(`deduplicated`)),Promise.resolve(readStore(a,i)).then(t=>handleCacheRecord(e,n,i,t,c))),t=>{if(e.config.signal?.aborted)throw t;return v.set(e,{contended:!1,release(){}}),handleCacheRecord(e,n,i,l,c)})}if(e.preserveRaw){let e=x.get(i);e&&(e.rawDemanded=!0)}let g=createInFlightRequest(e,i,c);e.preserveRaw?(S.set(i,g),C.add(e)):x.set(i,g),s.set(e,g),u.add(e),e.background||k(`miss`),l&&prepareConditionalRevalidation(e.config,l)&&m.set(e,l)}return l.hooks.onError(e=>{let t=_.get(e);if(!t||!isEligibleStaleIfError(e.error))return;let n=restoreCacheEntry(t,e.config);n&&(y.add(e),e.fallbackResponse=n)}),l.hooks.onSettled(t=>{let r=v.get(t);r&&(r.release(),O.delete(r)),v.delete(t),h.delete(t),g.delete(t),_.delete(t),y.delete(t);let i=c.get(t),invalidateAfterSuccess=()=>{let e=d.get(t);if(d.delete(t),!(!e||t.background||t.error||!t.response))try{let t=F.invalidateTags(e);if(n.t(t))return Promise.resolve(t).then(()=>{}).catch(ignoreCacheEventError)}catch{}};i&&(c.delete(t),releaseCacheGeneration(i,T));let a=s.get(t);if(!a)return invalidateAfterSuccess();s.delete(t),u.delete(t),m.delete(t);let o=a.key,l=C.delete(t)?S:x;if(l.get(o)===a&&l.delete(o),b.delete(t))return a.resolve?.(void 0),invalidateAfterSuccess();let f=p.get(t);return p.delete(t),f&&t.response&&(!t.error||isSchemaValidationFailure(t.error))?(a.resolve?.(f),invalidateAfterSuccess()):(a.reject?.(t.error??new e.t(`Shared request failed`,{code:`NETWORK_ERROR`,config:t.config})),invalidateAfterSuccess())}),()=>{I=!1;for(let e of O)e.release();O.clear();for(let t of u){let n=s.get(t);if(s.delete(t),!n)continue;let r=n.key,i=C.delete(t)?S:x;i.get(r)===n&&i.delete(r),n.reject?.(new e.t(`Cache plugin removed during shared request`,{code:`ABORT_ERROR`}))}u.clear(),T.clear(),abortBackgroundRefreshes(w)}}};return F}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return WebStorageCacheStore}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return MemoryCacheStore}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return TieredCacheStore}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return IndexedDBCacheStore}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return cachePlugin}});
@@ -1 +0,0 @@
1
- import{n as e,t}from"./RequestError-B0HIY1zK.js";import{n,r,t as i}from"./isBinaryBody-i4r46MoJ.js";import{t as a}from"./isPromiseLike-BuAv3bAe.js";import{t as o}from"./waitForSignal-iy_PYkkb.js";import{t as s}from"./resolveExtensionConfig-QAFHZVte.js";const c={persist:!1,ttl:0};function resolveRequestCachePolicy(e){let t=new Headers(e.headers),n=t.get(`cache-control`),r=!1;if(n)for(let e of n.split(`,`)){let t=e.trim(),n=t.indexOf(`=`),i=(n===-1?t:t.slice(0,n)).trim().toLowerCase();if(i===`no-store`)return`no-store`;if(i===`no-cache`){r=!0;continue}if(i===`max-age`&&n!==-1){let e=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());e&&Number(e[1]??e[2])===0&&(r=!0)}}else t.get(`pragma`)?.split(`,`).some(e=>e.trim().toLowerCase()===`no-cache`)&&(r=!0);return r?`revalidate`:`default`}function resolveResponseCachePolicy(e,t,n,r){let i=e.headers.get(`cache-control`),a,o=!1;if(i)for(let e of i.split(`,`)){let t=e.trim(),n=t.indexOf(`=`),r=(n===-1?t:t.slice(0,n)).trim().toLowerCase();if(r===`no-store`)return c;if(r===`no-cache`){o=!0;continue}if(r!==`max-age`)continue;if(a!==void 0)return c;let i=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());if(!i)return c;a=Number(i[1]??i[2])}if(e.headers.get(`vary`)?.split(`,`).some(e=>{let t=e.trim().toLowerCase();return t===`*`||isRequestCacheControlHeader$1(t)})||t<=0||a!==void 0&&!Number.isSafeInteger(a))return c;let s=o?0:a===void 0?t:Math.min(t,Math.max(0,(a-parseAge(e.headers.get(`age`)))*1e3));return{ttl:s,persist:s>0||hasResponseValidator$1(e.headers)||resolveStaleIfErrorWindow(e.headers,n)>0||!o&&resolveStaleWhileRevalidateWindow(e.headers,r)>0}}function resolveStaleIfErrorWindow(e,t){return resolveWindow(e,t,`stale-if-error`)}function resolveStaleWhileRevalidateWindow(e,t){return resolveWindow(e,t,`stale-while-revalidate`)}function hasCacheControlDirective(e,t){return e.get(`cache-control`)?.split(`,`).some(e=>{let n=e.indexOf(`=`);return(n===-1?e:e.slice(0,n)).trim().toLowerCase()===t})??!1}function resolveWindow(e,t,n){let r=parseCacheDeltaSeconds(e.get(`cache-control`),n);return t===void 0?r??0:r===void 0?t:Math.min(t,r)}function parseCacheDeltaSeconds(e,t){let n;if(!e)return;for(let r of e.split(`,`)){let e=r.trim(),i=e.indexOf(`=`);if(i===-1||e.slice(0,i).trim().toLowerCase()!==t)continue;if(n!==void 0)return;let a=/^(?:"(\d+)"|(\d+))$/.exec(e.slice(i+1).trim());if(!a)return;n=Number(a[1]??a[2])}if(n===void 0||!Number.isSafeInteger(n))return;let r=n*1e3;return Number.isSafeInteger(r)?r:void 0}function parseAge(e){if(!e||!/^\d+$/.test(e.trim()))return 0;let t=Number(e);return Number.isSafeInteger(t)?t:0}function hasResponseValidator$1(e){return e.has(`etag`)||e.has(`last-modified`)}function isRequestCacheControlHeader$1(e){return e===`cache-control`||e===`pragma`}function isCacheableRequest(e,t,n){return t.has(e.method??`GET`)&&(!hasRequestBody(e)||!!n.key)&&(!e.parseJson||!!n.key)&&(!e.querySerializer||!!n.key)&&e.responseType!==`stream`&&e.responseType!==`sse`&&e.responseType!==`ndjson`&&e.responseType!==`bytes`&&e.responseType!==`formData`&&e.fetchOptions?.mode!==`no-cors`&&e.fetchOptions?.redirect!==`manual`}function hasRequestBody(e){return e.body!=null||e.json!==void 0||e.form!=null||e.formData!=null}function isAsyncIterable(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}function isSchemaValidationFailure(t){return e(t)&&t.code===`SCHEMA_ERROR`}function canUseStaleIfError(e,t,n,r){try{if(n&&!e.raw||hasConditionalRequestHeaders(t))return!1;let i=resolveStaleIfErrorWindow(new Headers(e.headers),r);return i>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+i}catch{return!1}}function canUseStaleWhileRevalidate(e,t,n,r){try{if(n&&!e.raw)return!1;let i=new Headers(e.headers);if(hasConditionalRequestHeaders(t)||hasCacheControlDirective(i,`no-cache`)||hasCacheControlDirective(i,`must-revalidate`))return!1;let a=resolveStaleWhileRevalidateWindow(i,r);return a>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+a}catch{return!1}}function startBackgroundRefresh(e,t,n,r,i,a){if(t.has(n))return;let o=new AbortController,s={...r,signal:o.signal};t.set(n,o),a(`background-refresh`),Promise.resolve().then(()=>e.dispatch(s,{background:!0,preserveRaw:i})).then(()=>a(`background-refresh-success`),()=>a(`background-refresh-error`)).finally(()=>{t.get(n)===o&&t.delete(n)})}function abortBackgroundRefreshes(e){for(let t of e.values())t.abort(`Cache background refresh stopped`);e.clear()}function isEligibleStaleIfError(t){return e(t)&&(t.code===`NETWORK_ERROR`||t.code===`TIMEOUT_ERROR`||t.code===`HTTP_ERROR`&&t.status!==void 0&&t.status>=500&&t.status<600)}function canRevalidateCacheEntry(e,t,n){try{return n&&!e.raw||hasConditionalRequestHeaders(t)?!1:hasResponseValidator(new Headers(e.headers))}catch{return!1}}function prepareConditionalRevalidation(e,t){let n=new Headers(t.headers),r=n.get(`etag`),i=n.get(`last-modified`);if(!r&&!i)return!1;let a=new Headers(e.headers);r&&a.set(`if-none-match`,r),i&&a.set(`if-modified-since`,i);let o=e.validateStatus,s=e.throwHttpErrors;return e.headers=a,e.throwHttpErrors=void 0,e.validateStatus=e=>e===304||(o?o(e):s===!1||e>=200&&e<300),!0}function hasResponseValidator(e){return e.has(`etag`)||e.has(`last-modified`)}function hasConditionalRequestHeaders(e){let t=new Headers(e.headers);return t.has(`if-none-match`)||t.has(`if-modified-since`)||t.has(`range`)}function normalizeCacheTtl(e,n){let r=e??3e4;if(r!==1/0&&(!Number.isFinite(r)||r<0))throw new t(`Cache ttl must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return r}function normalizeCacheStatus(e,n){let r=e??200;if(!Number.isInteger(r)||r<200||r>599)throw new t(`Cache status must be an integer between 200 and 599`,{code:`CONFIG_ERROR`,config:n});return r}function normalizeStaleIfError(e,n){if(e!==void 0){if(e!==1/0&&(!Number.isFinite(e)||e<0))throw new t(`Cache staleIfError must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return e}}function normalizeStaleWhileRevalidate(e,n){if(e!==void 0){if(e!==1/0&&(!Number.isFinite(e)||e<0))throw new t(`Cache staleWhileRevalidate must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return e}}function normalizeCacheTags(e,n){if(e===void 0)return[];if(typeof e!=`string`&&!Array.isArray(e))throw new t(`Cache tags must be an array of strings`,{code:`CONFIG_ERROR`,config:n});let r=typeof e==`string`?[e]:e;if(r.length>32)throw new t(`Cache tags cannot contain more than 32 values`,{code:`CONFIG_ERROR`,config:n});let i=new Set;for(let e of r){if(typeof e!=`string`||e.length===0||e.length>128)throw new t(`Cache tags must contain 1 to 128 characters`,{code:`CONFIG_ERROR`,config:n});i.add(e)}return[...i]}function isExpired(e){return e!==1/0&&(Number.isNaN(e)||Date.now()>=e)}var MemoryCacheStore=class{constructor(e={}){this.entries=new Map,this.maxEntries=normalizeMaxEntries(e.maxEntries)}get(e){let t=this.entries.get(e);if(t)return this.newestKey!==e&&(this.entries.delete(e),this.entries.set(e,t),this.newestKey=e),t}set(e,t){if(this.maxEntries!==0){for(this.entries.delete(e);this.entries.size>=this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e)}this.entries.set(e,t),this.newestKey=e}}delete(e){this.entries.delete(e),this.newestKey===e&&(this.newestKey=void 0)}invalidateTags(e){let t=new Set(e),n=0;for(let[e,r]of this.entries)r.tags?.some(e=>t.has(e))&&(this.entries.delete(e),n+=1,this.newestKey===e&&(this.newestKey=void 0));return n}clear(){this.entries.clear(),this.newestKey=void 0}},WebStorageCacheStore=class{constructor(e,t={}){this.storage=e,this.prefix=createWebStoragePrefix(t.namespace),this.maxEntries=normalizeMaxEntries(t.maxEntries)}get(e){if(this.maxEntries===0)return;let t=this.prefix+e,n=this.read(t);if(n){try{this.storage.setItem(t,serializeWebStorageEntry(n.entry,Date.now()))}catch{}return n.entry}}set(e,t){if(this.maxEntries===0)return;let n=this.prefix+e,r=this.keys(),i=r.includes(n),a=Math.max(0,r.length-this.maxEntries+ +!i);if(a>0){let e=r.map(e=>({key:e,accessedAt:this.read(e)?.accessedAt??0})).filter(e=>e.key!==n).sort((e,t)=>e.accessedAt-t.accessedAt);for(let t of e.slice(0,a))this.storage.removeItem(t.key)}this.storage.setItem(n,serializeWebStorageEntry(t,Date.now()))}delete(e){this.storage.removeItem(this.prefix+e)}invalidateTags(e){let t=new Set(e),n=0;for(let e of this.keys())this.read(e)?.entry.tags?.some(e=>t.has(e))&&(this.storage.removeItem(e),n+=1);return n}clear(){for(let e of this.keys())this.storage.removeItem(e)}keys(){let e=[];for(let t=0;t<this.storage.length;t+=1){let n=this.storage.key(t);n?.startsWith(this.prefix)&&e.push(n)}return e}read(e){let t=this.storage.getItem(e);if(t!==null)try{return parseWebStorageEntry(t)}catch{this.storage.removeItem(e);return}}};function normalizeMaxEntries(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function createWebStoragePrefix(e=`default`){if(typeof e!=`string`||e.length===0||e.length>128)throw new t(`Web storage cache namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return`@npora/request:${encodeURIComponent(e)}:`}function serializeWebStorageEntry(e,t){return JSON.stringify({version:1,data:e.data,expiresAt:e.expiresAt===1/0?null:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags,accessedAt:t})}function parseWebStorageEntry(e){let t=JSON.parse(e),n=t.expiresAt===null?1/0:t.expiresAt;if(t.version!==1||n!==1/0&&(typeof n!=`number`||!Number.isFinite(n))||typeof t.status!=`number`||!Number.isInteger(t.status)||t.status<200||t.status>599||typeof t.statusText!=`string`||!Array.isArray(t.headers)||typeof t.accessedAt!=`number`||!Number.isFinite(t.accessedAt))throw TypeError(`Invalid web storage cache entry`);let r=t.tags===void 0?void 0:normalizeCacheTags(t.tags);return{entry:{data:t.data,expiresAt:n,status:t.status,statusText:t.statusText,headers:[...new Headers(t.headers).entries()],tags:r&&r.length>0?r:void 0},accessedAt:t.accessedAt}}const l=[];function createCacheKey(e,t,n,r,i){if(t.key)return t.key;let a=e.method??`GET`,o=String(e.url),s=e.responseType??`auto`,c=!e.headers&&!e.query&&!e.searchParams;if(c&&i.key!==void 0&&i.method===a&&i.baseURL===e.baseURL&&i.url===o&&i.responseType===s)return i.key;let u=JSON.stringify({method:a,baseURL:e.baseURL,url:o,query:c?l:normalizeQuery(e.searchParams??e.query),responseType:s,headers:e.headers?normalizeCacheHeaders(new Headers(e.headers),n):r});return c&&(i.method=a,i.baseURL=e.baseURL,i.url=o,i.responseType=s,i.key=u),u}function normalizeCacheHeaders(e,t){let n=[];e?.forEach((e,t)=>{isRequestCacheControlHeader(t)||n.push([t,e])});for(let r of t)!isRequestCacheControlHeader(r)&&!e?.has(r)&&n.push([r,null]);return n.sort(([e],[t])=>e.localeCompare(t))}function isRequestCacheControlHeader(e){return e===`cache-control`||e===`pragma`}function normalizeVaryHeaders(e){return[...new Set(e.map(e=>e.toLowerCase()))]}function normalizeQuery(e){if(!e)return l;if(r(e))return[...e.entries()];let t=[];for(let n of Object.keys(e).sort())appendQueryValue(t,n,e[n]);return t}function appendQueryValue(e,t,n){if(n!==void 0){if(n===null){e.push([t,``]);return}if(Array.isArray(n)){for(let r of n)appendQueryValue(e,t,r);return}e.push([t,String(n)])}}function acquireCacheGeneration(e,t,n,r){let i=n.get(t);i||(i={activeRequests:0,tags:new Set},n.set(t,i)),i.activeRequests+=1;for(let e of r)i.tags.add(e);return{global:e,key:t,token:i}}function isCurrentCacheGeneration(e,t,n){return e!==void 0&&e.global===t&&n.get(e.key)===e.token}function releaseCacheGeneration(e,t){--e.token.activeRequests,e.token.activeRequests===0&&t.get(e.key)===e.token&&t.delete(e.key)}function createInFlightRequest(e,t,n){return{owner:e,key:t,generation:n}}function getInFlightPromise(e){if(e.promise)return e.promise;let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.catch(()=>{}),e.promise=r,e.resolve=t,e.reject=n,r}function readStore(e,t){try{let n=e.get(t);return a(n)?Promise.resolve(n).catch(()=>void 0):n}catch{return}}function writeStore(e,t,n){try{let r=e.set(t,n);if(a(r))return Promise.resolve(r).catch(ignoreStoreError)}catch{}}function deleteStore(e,t){try{let n=e.delete(t);if(a(n))return Promise.resolve(n).catch(ignoreStoreError)}catch{}}function ignoreStoreError(){}function waitForSharedRecord(e,t){let n=t.signal;return n?n.aborted?Promise.reject(createSharedAbortError(n.reason,t)):new Promise((r,i)=>{let a=!1,cleanup=()=>{try{n.removeEventListener(`abort`,onAbort)}catch{}},resolveOnce=e=>{a||(a=!0,cleanup(),r(e))},rejectOnce=e=>{a||(a=!0,cleanup(),i(e))},onAbort=()=>{rejectOnce(createSharedAbortError(n.reason,t))};try{n.addEventListener(`abort`,onAbort,{once:!0})}catch(e){rejectOnce(e);return}n.aborted&&onAbort(),!a&&e.then(resolveOnce,e=>{rejectOnce(cloneSharedError(e,t))})}):e.catch(e=>{throw cloneSharedError(e,t)})}function createSharedAbortError(e,n){return new t(`Request aborted while waiting for shared response`,{code:`ABORT_ERROR`,config:n,cause:e})}function cloneSharedError(n,r){return e(n)?new t(n.message,{code:n.code,status:n.status,data:n.data,response:n.response,config:r,cause:n}):n}function createCacheEntry(e,t,n,r){return{data:cloneCacheValue(e.data),expiresAt:t,status:e.status,statusText:e.statusText,headers:[...e.headers.entries()],tags:r?[...r]:void 0,raw:n?cloneResponse(e.raw):void 0}}function createCachedResponse(e,t){return{data:cloneCacheValue(e.data),status:e.status,statusText:e.statusText,headers:new Headers(e.headers),config:t,raw:cloneRawResponse(e)}}function restoreCacheEntry(e,t){try{return createCachedResponse(e,t)}catch{return}}function createRevalidatedResponse(e,t,n){let r=new Headers(e.headers);return t.headers.forEach((e,t)=>{r.set(t,e)}),createCachedResponse({...e,headers:[...r.entries()]},n)}function cloneRawResponse(e){if(e.raw){let t=cloneResponse(e.raw);if(t)return new Response(t.body,{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})}function cloneResponse(e){try{return e.clone()}catch{return}}function cloneCacheValue(e){if(typeof e!=`object`||!e||typeof structuredClone!=`function`)return e;try{return structuredClone(e)}catch{return e}}const u=`entries`,d=`namespace`;var IndexedDBCacheStore=class{constructor(e,t={}){this.namespace=normalizeIndexedDBName(t.namespace,`namespace`,`default`),this.maxEntries=normalizeIndexedDBMaxEntries(t.maxEntries),this.maxBytes=normalizeIndexedDBMaxBytes(t.maxBytes),this.quotaRecovery=normalizeQuotaRecovery(t.quotaRecovery),this.shouldPersist=normalizeIndexedDBAdmissionPolicy(t.shouldPersist),this.onEvent=normalizeIndexedDBEventObserver(t.onEvent),this.schemaVersion=normalizeIndexedDBSchemaVersion(t.schemaVersion),this.databaseName=normalizeIndexedDBName(t.databaseName,`database name`,`@npora/request-cache`),this.factory=e}async get(e){if(this.maxEntries===0||this.maxBytes===0){await this.delete(e);return}let t=(await this.getDatabase()).transaction(u,`readwrite`),n=waitForTransaction(t),r=t.objectStore(u),i=this.createKey(e),a=await waitForRequest(r.get(i)),o=isFutureIndexedDBRecord(a,this.schemaVersion);if(!isValidIndexedDBRecord(a,this.namespace,i,this.schemaVersion)){a!==void 0&&!o&&r.delete(i),await n,a!==void 0&&!o&&this.emitEvent({type:`eviction`,reason:`malformed`,entries:1,estimatedBytes:readIndexedDBRecordSize(a)});return}return a.accessedAt=Date.now(),a.size=readIndexedDBRecordSize(a),r.put(a),await n,toPortableCacheEntry(a)}async set(e,n){if(this.maxEntries===0||this.maxBytes===0){await this.delete(e);return}let r=await this.getDatabase(),i={...toPortableCacheEntry(n),key:this.createKey(e),namespace:this.namespace,accessedAt:Date.now(),schemaVersion:this.schemaVersion};if(i.size=estimateStructuredCloneSize(i),i.size>this.maxBytes){await this.delete(e),this.emitEvent({type:`rejection`,reason:`oversized`,entries:1,estimatedBytes:i.size});return}let a=!this.shouldPersist||await this.shouldPersist(toPortableCacheEntry(i),i.size);if(typeof a!=`boolean`)throw new t(`IndexedDB cache shouldPersist must return a boolean`,{code:`CONFIG_ERROR`});if(!a){await this.delete(e),this.emitEvent({type:`rejection`,reason:`admission-policy`,entries:1,estimatedBytes:i.size});return}try{await this.writeRecord(r,i)}catch(e){if(!this.quotaRecovery||!isQuotaExceededError(e)||!await this.recoverQuota(r))throw e;await this.writeRecord(r,i)}}async delete(e){let t=(await this.getDatabase()).transaction(u,`readwrite`),n=waitForTransaction(t),r=t.objectStore(u),i=this.createKey(e);isFutureIndexedDBRecord(await waitForRequest(r.get(i)),this.schemaVersion)||r.delete(i),await n}async invalidateTags(e){let t=new Set(e),n=0;return await this.visitNamespace(e=>e.tags?.some(e=>t.has(e))?(n+=1,!0):!1),n}async clear(){await this.visitNamespace(()=>!0)}async getUsage(){let e=(await this.getDatabase()).transaction(u,`readonly`),t=waitForTransaction(e),n=e.objectStore(u).index(d).openCursor(this.namespace),r=0,i=0;return await visitCursor(n,e=>{let t=e.value;isValidIndexedDBRecord(t,this.namespace,void 0,this.schemaVersion)&&(r+=1,i=addSizes(i,readIndexedDBRecordSize(t)))}),await t,{entries:r,estimatedBytes:i,maxEntries:this.maxEntries,maxBytes:this.maxBytes,schemaVersion:this.schemaVersion}}async compact(e={}){let t=normalizeCompactionBoundary(e.expiredBefore),n=normalizeCompactionMaxRemovals(e.maxRemovals),r=(await this.getDatabase()).transaction(u,`readwrite`),i=waitForTransaction(r),a=r.objectStore(u).index(d).openCursor(this.namespace),o=new Map,s=0,c=0,l=0,f=!1;return await visitCursor(a,e=>{let r=e.value,i=classifyIndexedDBRecord(r,this.namespace,this.schemaVersion);if(s+=1,i===`malformed`||i===`schema-version`)e.delete(),addCleanupSummary(o,i,r),c+=1,l=addSizes(l,readIndexedDBRecordSize(r));else if(i===`current`&&r.expiresAt<=t){let t=readIndexedDBRecordSize(r);e.delete(),addCleanupSummary(o,`expired`,r),c+=1,l=addSizes(l,t)}if(c>=n)return f=!0,!1}),await i,this.emitCleanupSummaries(o.values()),{scannedEntries:s,removedEntries:c,estimatedBytesFreed:l,expiredBefore:t,hasMore:f}}async close(){let e=this.database;e&&(this.database=void 0,(await e).close())}createKey(e){return this.schemaVersion===1?`${this.namespace}\0${e}`:`${this.namespace}\0@npora-schema:${this.schemaVersion}\0${e}`}async writeRecord(e,t){let n=e.transaction(u,`readwrite`),r=waitForTransaction(n),i=n.objectStore(u),a=new Map;if(isFutureIndexedDBRecord(await waitForRequest(i.get(t.key)),this.schemaVersion)){await r;return}if(i.put(t),this.maxEntries!==1/0||this.maxBytes!==1/0){let e=await waitForRequest(i.index(d).getAll(this.namespace)),n=[];for(let t of e){let e=classifyIndexedDBRecord(t,this.namespace,this.schemaVersion);e===`malformed`||e===`schema-version`?(i.delete(t.key),addCleanupSummary(a,e,t)):e===`current`&&n.push(t)}n.sort((e,n)=>e.key===t.key?1:n.key===t.key?-1:e.accessedAt-n.accessedAt||e.key.localeCompare(n.key));let r=n.reduce((e,t)=>addSizes(e,readIndexedDBRecordSize(t)),0),o=n.length;for(let e of n){if(o<=this.maxEntries&&r<=this.maxBytes)break;i.delete(e.key),addCleanupSummary(a,r>this.maxBytes?`max-bytes`:`max-entries`,e),--o,r=Math.max(0,r-readIndexedDBRecordSize(e))}}await r,this.emitCleanupSummaries(a.values())}async recoverQuota(e){let t=e.transaction(u,`readwrite`),n=waitForTransaction(t),r=t.objectStore(u),i=await waitForRequest(r.index(d).getAll(this.namespace)),a=[],o=new Map,s=!1;for(let e of i){let t=classifyIndexedDBRecord(e,this.namespace,this.schemaVersion);t===`malformed`||t===`schema-version`?(r.delete(e.key),addCleanupSummary(o,t,e),s=!0):t===`current`&&a.push(e)}a.sort((e,t)=>e.accessedAt-t.accessedAt||e.key.localeCompare(t.key));for(let e of a.slice(0,Math.max(1,Math.ceil(a.length/2))))r.delete(e.key),addCleanupSummary(o,`quota-recovery`,e),s=!0;return await n,this.emitCleanupSummaries(o.values()),s}emitCleanupSummaries(e){for(let t of e)this.emitEvent({type:`eviction`,...t})}emitEvent(e){if(this.onEvent)try{Promise.resolve(this.onEvent({...e,timestamp:Date.now()})).catch(()=>{})}catch{}}async visitNamespace(e){let t=(await this.getDatabase()).transaction(u,`readwrite`),n=waitForTransaction(t),r=t.objectStore(u).index(d).openCursor(this.namespace),i=new Map;await visitCursor(r,t=>{let n=t.value,r=classifyIndexedDBRecord(n,this.namespace,this.schemaVersion);(r===`malformed`||r===`schema-version`||r===`current`&&e(n))&&(t.delete(),(r===`malformed`||r===`schema-version`)&&addCleanupSummary(i,r,n))}),await n,this.emitCleanupSummaries(i.values())}getDatabase(){return this.database??(this.database=openCacheDatabase(this.factory,this.databaseName).then(async e=>{try{let t=await pruneOlderSchemaRecords(e,this.namespace,this.schemaVersion);return this.emitCleanupSummaries(t),e}catch(t){throw e.close(),t}})),this.database}};function openCacheDatabase(e,t){return new Promise((n,r)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(u)||e.createObjectStore(u,{keyPath:`key`}).createIndex(d,d,{unique:!1})},i.onerror=()=>r(i.error),i.onsuccess=()=>{let e=i.result;e.onversionchange=()=>e.close(),n(e)}})}function waitForRequest(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)})}function waitForTransaction(e){let t=new Promise((t,n)=>{let rejectWithTransactionError=t=>{n(e.error??readIDBRequestError(t.target)??Error(`IndexedDB transaction failed`))};e.onabort=rejectWithTransactionError,e.onerror=rejectWithTransactionError,e.oncomplete=()=>t()});return t.catch(()=>{}),t}function readIDBRequestError(e){if(!e||!(`error`in e))return null;let t=e.error;return t instanceof DOMException?t:null}function visitCursor(e,t){return new Promise((n,r)=>{e.onerror=()=>r(e.error),e.onsuccess=()=>{let i=e.result;if(!i){n();return}try{if(t(i)===!1){n();return}}catch(t){try{readCursorTransaction(e)?.abort()}catch{}r(t);return}i.continue()}})}function readCursorTransaction(e){let t=e.source;if(t)return`transaction`in t?t.transaction:`objectStore`in t?t.objectStore.transaction:`transaction`in t.source?t.source.transaction:t.source.objectStore.transaction}function toPortableCacheEntry(e){return{data:e.data,expiresAt:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags}}function isValidIndexedDBRecord(e,t,n,r=1){if(!e||typeof e!=`object`)return!1;let i=e;if(!(typeof i.key==`string`&&(n===void 0||i.key===n)&&i.namespace===t&&readIndexedDBSchemaVersion(i)===r&&(i.expiresAt===1/0||Number.isFinite(i.expiresAt))&&Number.isInteger(i.status)&&i.status>=200&&i.status<=599&&typeof i.statusText==`string`&&Array.isArray(i.headers)&&(i.tags===void 0||Array.isArray(i.tags)&&i.tags.length<=32&&i.tags.every(e=>typeof e==`string`&&e.length>0&&e.length<=128))&&Number.isFinite(i.accessedAt)))return!1;try{return new Headers(i.headers),!0}catch{return!1}}function readIndexedDBSchemaVersion(e){if(!e||typeof e!=`object`)return;let t=e.schemaVersion??1;return Number.isSafeInteger(t)&&t>=1&&t<=1e9?t:void 0}function classifyIndexedDBRecord(e,t,n){let r=readIndexedDBSchemaVersion(e);return r===void 0?`malformed`:r>n?`future`:r<n?`schema-version`:isValidIndexedDBRecord(e,t,void 0,n)?`current`:`malformed`}function isFutureIndexedDBRecord(e,t){let n=readIndexedDBSchemaVersion(e);return n!==void 0&&n>t}function readIndexedDBRecordSize(e){let t=e&&typeof e==`object`?e.size:void 0;return Number.isSafeInteger(t)&&t>=0?t:estimateStructuredCloneSize(e)}function estimateStructuredCloneSize(e,t=new WeakSet){if(e==null)return 0;if(typeof e==`string`)return Math.min(2**53-1,e.length*2);if(typeof e==`number`||typeof e==`bigint`)return 8;if(typeof e==`boolean`)return 4;if(typeof e!=`object`)return 0;if(t.has(e)||(t.add(e),e instanceof Date))return 8;if(n(e))return e.size;if(i(e)||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Map){let n=16;for(let[r,i]of e)n=addSizes(n,estimateStructuredCloneSize(r,t),estimateStructuredCloneSize(i,t));return n}if(e instanceof Set){let n=16;for(let r of e)n=addSizes(n,estimateStructuredCloneSize(r,t));return n}let r=Array.isArray(e)?16:32;for(let[n,i]of Object.entries(e))r=addSizes(r,n.length*2,estimateStructuredCloneSize(i,t));return r}function addSizes(...e){let t=0;for(let n of e){if(n>=2**53-1-t)return 2**53-1;t+=n}return t}function addCleanupSummary(e,t,n){let r=e.get(t),i=readIndexedDBRecordSize(n);if(r){r.entries+=1,r.estimatedBytes=addSizes(r.estimatedBytes,i);return}e.set(t,{reason:t,entries:1,estimatedBytes:i})}function isQuotaExceededError(e){return!!(e&&typeof e==`object`&&e.name===`QuotaExceededError`)}async function pruneOlderSchemaRecords(e,t,n){let r=e.transaction(u,`readwrite`),i=waitForTransaction(r),a=r.objectStore(u).index(d).openCursor(t),o=new Map;return await visitCursor(a,e=>{let r=e.value,i=classifyIndexedDBRecord(r,t,n);(i===`malformed`||i===`schema-version`)&&(e.delete(),addCleanupSummary(o,i,r))}),await i,[...o.values()]}function normalizeIndexedDBName(e,n,r){let i=e??r;if(typeof i!=`string`||i.length===0||i.length>128)throw new t(`IndexedDB cache ${n} must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return i}function normalizeIndexedDBMaxEntries(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function normalizeIndexedDBMaxBytes(e){if(e===void 0)return 1/0;if(e===1/0)return e;if(!Number.isSafeInteger(e)||e<0)throw new t(`IndexedDB cache maxBytes must be a non-negative safe integer or Infinity`,{code:`CONFIG_ERROR`});return e}function normalizeQuotaRecovery(e){if(e===void 0)return!0;if(typeof e!=`boolean`)throw new t(`IndexedDB cache quotaRecovery must be a boolean`,{code:`CONFIG_ERROR`});return e}function normalizeIndexedDBEventObserver(e){if(e!==void 0&&typeof e!=`function`)throw new t(`IndexedDB cache onEvent must be a function`,{code:`CONFIG_ERROR`});return e}function normalizeIndexedDBAdmissionPolicy(e){if(e!==void 0&&typeof e!=`function`)throw new t(`IndexedDB cache shouldPersist must be a function`,{code:`CONFIG_ERROR`});return e}function normalizeCompactionBoundary(e){let n=e??Date.now();if(!Number.isFinite(n))throw new t(`IndexedDB cache compact expiredBefore must be finite`,{code:`CONFIG_ERROR`});return n}function normalizeCompactionMaxRemovals(e){if(e===void 0||e===1/0)return 1/0;if(!Number.isSafeInteger(e)||e<1)throw new t(`IndexedDB cache compact maxRemovals must be a positive safe integer or Infinity`,{code:`CONFIG_ERROR`});return e}function normalizeIndexedDBSchemaVersion(e){let n=e??1;if(!Number.isSafeInteger(n)||n<1||n>1e9)throw new t(`IndexedDB cache schemaVersion must be an integer from 1 to 1000000000`,{code:`CONFIG_ERROR`});return n}var TieredCacheStore=class{constructor(e){if(this.leaseReleases=new Set,this.source=`${Date.now()}:${Math.random()}`,this.trackedKeys=new Map,this.trackedKeyCount=0,this.handleMessage=e=>{let t=e.data;if(!isTieredCacheMessage(t)||t.source===this.source)return;if(t.action===`clear`){this.clearPrimary();return}let n=this.trackedKeys.get(t.fingerprint);if(!n){this.clearPrimary();return}this.trackedKeys.delete(t.fingerprint),this.trackedKeyCount-=n.size;for(let e of n)ignoreStoreResult(()=>this.primary.delete(e))},!e||!e.primary||!e.secondary||e.primary===e.secondary)throw new t(`Tiered cache requires distinct primary and secondary stores`,{code:`CONFIG_ERROR`});if(this.primary=e.primary,this.secondary=e.secondary,e.broadcast&&!e.broadcast.channel)throw new t(`Tiered cache broadcast requires a channel`,{code:`CONFIG_ERROR`});if(e.coordination&&!e.coordination.locks)throw new t(`Tiered cache coordination requires a lock manager`,{code:`CONFIG_ERROR`});this.channel=e.broadcast?.channel,this.locks=e.coordination?.locks,this.lockNamespace=normalizeLockNamespace(e.coordination?.namespace),this.maxTrackedKeys=normalizeTrackedKeys(e.broadcast?.maxTrackedKeys),this.locks&&(this.acquireRefreshLease=(e,t)=>this.acquireCoordinatedLease(e,t)),this.channel?.addEventListener(`message`,this.handleMessage)}get(e){let t;try{t=this.primary.get(e)}catch{return this.readSecondary(e)}return a(t)?Promise.resolve(t).then(t=>t?this.remember(e,t):this.readSecondary(e),()=>this.readSecondary(e)):t?this.remember(e,t):this.readSecondary(e)}set(e,t){let writePrimary=()=>{let n;try{n=this.primary.set(e,t)}catch(t){throw this.recoverPrimaryWrite(e),t}return a(n)?Promise.resolve(n).catch(t=>{throw this.recoverPrimaryWrite(e),t}):n},n=this.secondary.set(e,t),r=a(n)?Promise.resolve(n).then(writePrimary):writePrimary();return this.afterSuccess(r,()=>{this.trackKey(e),this.broadcastKey(e)})}delete(e){return this.afterSettled(()=>combineStoreOperations([()=>this.primary.delete(e),()=>this.secondary.delete(e)],()=>void 0),()=>{this.untrackKey(e),this.broadcastKey(e)})}invalidateTags(e){let n=this.primary.invalidateTags,r=this.secondary.invalidateTags;if(!n||!r)throw new t(`Both tiered cache stores must support tag invalidation`,{code:`CONFIG_ERROR`});return this.afterSettled(()=>combineStoreOperations([()=>n.call(this.primary,e),()=>r.call(this.secondary,e)],e=>Math.max(...e)),()=>this.broadcastClear())}clear(){return this.afterSettled(()=>combineStoreOperations([()=>this.primary.clear(),()=>this.secondary.clear()],()=>void 0),()=>this.broadcastClear())}async acquireCoordinatedLease(e,n){let r=`${this.lockNamespace}:${fingerprintCacheKey(e)}`,i=await this.requestLease(r,!0,n);if(i)return i;let a=await this.requestLease(r,!1,n);if(!a)throw new t(`Cache refresh lock was unavailable`,{code:`NETWORK_ERROR`});return await ignoreStoreFailure(()=>this.primary.delete(e)),a}dispose(){this.channel?.removeEventListener(`message`,this.handleMessage);for(let e of this.leaseReleases)e();this.leaseReleases.clear(),this.trackedKeys.clear(),this.trackedKeyCount=0}requestLease(e,t,n){return new Promise((r,i)=>{let a=!1,o=createDeferred(),s={mode:`exclusive`,ifAvailable:t};n&&(s.signal=n),this.locks.request(e,s,async e=>{if(!e){a=!0,r(void 0);return}let n=!0,release=()=>{n&&(n=!1,this.leaseReleases.delete(release),o.resolve())};this.leaseReleases.add(release),a=!0,r({contended:!t,release}),await o.promise}).catch(e=>{a||i(e)})})}readSecondary(e){let promote=t=>{if(t){try{let n=this.primary.set(e,t);if(a(n))return Promise.resolve(n).then(()=>this.remember(e,t),()=>this.remember(e,t))}catch{}return this.remember(e,t)}},t=this.secondary.get(e);return a(t)?Promise.resolve(t).then(promote):promote(t)}remember(e,t){return this.trackKey(e),t}trackKey(e){if(!this.channel)return;let t=fingerprintCacheKey(e),n=this.trackedKeys.get(t);if(n?.has(e)){this.trackedKeys.delete(t),this.trackedKeys.set(t,n);return}for(;this.trackedKeyCount>=this.maxTrackedKeys;){let e=this.trackedKeys.entries().next().value;if(!e)break;this.trackedKeys.delete(e[0]),this.trackedKeyCount-=e[1].size}n??(n=new Set),n.add(e),this.trackedKeys.delete(t),this.trackedKeys.set(t,n),this.trackedKeyCount+=1}untrackKey(e){let t=fingerprintCacheKey(e),n=this.trackedKeys.get(t);n?.delete(e)&&(--this.trackedKeyCount,n.size===0&&this.trackedKeys.delete(t))}broadcastKey(e){this.postMessage({protocol:`npora-cache:1`,source:this.source,action:`delete`,fingerprint:fingerprintCacheKey(e)})}broadcastClear(){this.trackedKeys.clear(),this.trackedKeyCount=0,this.postMessage({protocol:`npora-cache:1`,source:this.source,action:`clear`})}postMessage(e){try{this.channel?.postMessage(e)}catch{}}clearPrimary(){this.trackedKeys.clear(),this.trackedKeyCount=0,ignoreStoreResult(()=>this.primary.clear())}recoverPrimaryWrite(e){this.untrackKey(e),ignoreStoreResult(()=>this.primary.delete(e)),this.broadcastKey(e)}afterSuccess(e,t){return a(e)?Promise.resolve(e).then(e=>(t(),e)):(t(),e)}afterSettled(e,t){let n;try{n=e()}catch(e){throw t(),e}return a(n)?Promise.resolve(n).then(e=>(t(),e),e=>{throw t(),e}):(t(),n)}};function combineStoreOperations(e,t){let n=[],r=[],i,o=!1;for(let t of e)try{let e=t();a(e)?r.push(Promise.resolve(e).then(e=>{n.push(e)},e=>{o||(o=!0,i=e)})):n.push(e)}catch(e){o||(o=!0,i=e)}let finish=()=>{if(o)throw i;return t(n)};return r.length>0?Promise.all(r).then(finish):finish()}function fingerprintCacheKey(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function isTieredCacheMessage(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.protocol===`npora-cache:1`&&typeof t.source==`string`&&(t.action===`clear`||t.action===`delete`&&typeof t.fingerprint==`string`&&t.fingerprint.length<=16)}function normalizeTrackedKeys(e){let n=e??1e3;if(!Number.isInteger(n)||n<1||n>1e5)throw new t(`Tiered cache maxTrackedKeys must be an integer from 1 to 100000`,{code:`CONFIG_ERROR`});return n}function normalizeLockNamespace(e){let n=e??`npora-cache`;if(typeof n!=`string`||n.length<1||n.length>128)throw new t(`Tiered cache lock namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return n}function createDeferred(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}function ignoreStoreResult(e){try{let t=e();a(t)&&Promise.resolve(t).catch(()=>{})}catch{}}async function ignoreStoreFailure(e){try{await e()}catch{}}const f=[`GET`,`HEAD`],p=[`authorization`,`cookie`,`accept`,`accept-language`],m={hit:`hits`,miss:`misses`,bypass:`bypasses`,invalidated:`invalidations`,"invalidation-error":`invalidationErrors`,deduplicated:`deduplicated`,revalidated:`revalidations`,"stale-if-error":`staleIfError`,"stale-while-revalidate":`staleWhileRevalidate`,"background-refresh":`backgroundRefreshes`,"background-refresh-success":`backgroundRefreshSuccesses`,"background-refresh-error":`backgroundRefreshErrors`};function createCacheStats(){return{hits:0,misses:0,bypasses:0,invalidations:0,invalidationErrors:0,deduplicated:0,revalidations:0,staleIfError:0,staleWhileRevalidate:0,backgroundRefreshes:0,backgroundRefreshSuccesses:0,backgroundRefreshErrors:0}}function resetCacheStats(e){Object.assign(e,createCacheStats())}function createCacheEventRecorder(e,t){return n=>{if(incrementCacheStat(e,n),t)try{let e=t({type:n,timestamp:Date.now()});a(e)&&Promise.resolve(e).catch(ignoreCacheEventError)}catch{}}}function incrementCacheStat(e,t){let n=m[t];e[n]=Math.min(2**53-1,e[n]+1)}function ignoreCacheEventError(){}function cachePlugin(e={}){let n=e.store??new MemoryCacheStore({maxEntries:e.maxEntries}),r=new WeakSet,i=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakMap,m=new WeakMap,h=new WeakSet,g=new WeakSet,_=new WeakMap,v=new WeakMap,y=new WeakSet,b=new WeakSet,x=new Map,S=new Map,C=new WeakSet,w=new Map,T=new Map,E=new Map,D=new Map,O=createCacheStats(),k=createCacheEventRecorder(O,e.onEvent),A=0,j=new Set(e.methods??f),M=normalizeVaryHeaders(e.varyHeaders??p),N=normalizeCacheHeaders(void 0,M),P={};function trackKeyOperation(e,t,n,r){let i=Promise.resolve(t),a;return a=i.then(()=>n&&k(n),()=>r&&k(r)).finally(()=>{E.get(e)===a&&E.delete(e)}),E.set(e,a),i}function runKeyOperation(e,t,n=[],r,i){let o=new Set(n),s=E.get(e);if(s&&o.add(s),o.size>0)return trackKeyOperation(e,Promise.all(o).then(t),r,i);let c;try{c=t()}catch(e){throw i&&k(i),e}return a(c)?trackKeyOperation(e,c,r,i):(r&&k(r),c)}function invalidateKeyState(e,t){T.delete(e),x.delete(e),S.delete(e);let n=w.get(e);n&&(w.delete(e),n.abort(t))}function trackTagInvalidation(e,t){let n=Promise.resolve(t),r;r=n.then(()=>k(`invalidated`),()=>k(`invalidation-error`)).finally(()=>{for(let t of e)D.get(t)===r&&D.delete(t)});for(let t of e)D.set(t,r);return n}let F={name:`cache`,clear(){return A+=1,x.clear(),S.clear(),T.clear(),abortBackgroundRefreshes(w),n.clear()},delete(e){let t=createCacheKey(e,s(e,`cache`)??{},M,N,P);return invalidateKeyState(t,`Cache entry invalidated`),runKeyOperation(t,()=>n.delete(t),[],`invalidated`,`invalidation-error`)},set(e,t,r={}){let i=s(e,`cache`)??{},a=createCacheKey(e,i,M,N,P),o=normalizeCacheTtl(r.ttl??i.ttl,e),c=normalizeCacheStatus(r.status,e),l=normalizeCacheTags(r.tags??i.tags,e),u={data:cloneCacheValue(t),expiresAt:o===1/0?o:Date.now()+o,status:c,statusText:r.statusText??(c===200?`OK`:``),headers:[...new Headers(r.headers).entries()],tags:l.length>0?l:void 0},d=l.map(e=>D.get(e)).filter(e=>!!e);return invalidateKeyState(a,`Cache entry replaced`),runKeyOperation(a,()=>n.set(a,u),d)},update(e,t){let r=createCacheKey(e,s(e,`cache`)??{},M,N,P);return invalidateKeyState(r,`Cache entry updated`),runKeyOperation(r,()=>{let updateEntry=e=>{if(!e)return!1;let i=t(cloneCacheValue(e.data));if(i===void 0){let e=n.delete(r);return!a(e)||Promise.resolve(e).then(()=>!0)}let o=n.set(r,{...e,data:cloneCacheValue(i),raw:void 0});return!a(o)||Promise.resolve(o).then(()=>!0)},e=n.get(r);return a(e)?Promise.resolve(e).then(updateEntry):updateEntry(e)},D.values())},invalidateTags(e){let r=normalizeCacheTags(e);if(r.length===0)throw new t(`Cache tag invalidation requires at least one tag`,{code:`CONFIG_ERROR`});let i=n.invalidateTags;if(!i)throw new t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`});for(let[e,t]of T)r.some(e=>t.tags.has(e))&&invalidateKeyState(e,`Cache tags invalidated`);let o=new Set(r.map(e=>D.get(e)).filter(e=>!!e));for(let e of E.values())o.add(e);if(o.size>0)return trackTagInvalidation(r,Promise.all(o).then(()=>i.call(n,r)));let s;try{s=i.call(n,r)}catch(e){throw k(`invalidation-error`),e}return a(s)?trackTagInvalidation(r,s):(k(`invalidated`),s)},getStats(){return{...O}},resetStats(){resetCacheStats(O)},install(f){let p=new Set,O=new Set,I=!0;f.hooks.onRequest(e=>{let r=s(e.config,`cache`);if(!r)return;let i=normalizeCacheTags(r.invalidateTags,e.config);if(i.length>0){if(!n.invalidateTags)throw new t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`,config:e.config});l.set(e,i)}if(!r.enabled||!isCacheableRequest(e.config,j,r))return;normalizeCacheTtl(r.ttl,e.config),normalizeStaleIfError(r.staleIfError,e.config),normalizeStaleWhileRevalidate(r.staleWhileRevalidate,e.config);let u=normalizeCacheTags(r.tags,e.config),d=resolveRequestCachePolicy(e.config);if(d===`no-store`){k(`bypass`),g.add(e);return}(d===`revalidate`||e.background)&&h.add(e);let f=createCacheKey(e.config,r,M,N,P),p=acquireCacheGeneration(A,f,T,u);c.set(e,p);let read=()=>{let t=readStore(n,f);return e.config.signal&&a(t)?o(()=>t,e.config).then(t=>{if(isCurrentCacheGeneration(p,A,T))return handleCacheRecord(e,r,f,t,p)}):a(t)?Promise.resolve(t).then(t=>{if(isCurrentCacheGeneration(p,A,T))return handleCacheRecord(e,r,f,t,p)}):handleCacheRecord(e,r,f,t,p)},m=new Set,_=E.get(f);_&&m.add(_);for(let e of u){let t=D.get(e);t&&m.add(t)}if(m.size>0){let t=Promise.all(m).then(()=>{});return e.config.signal?o(()=>t,e.config).then(read):t.then(read)}return read()}),f.hooks.onResponse(e=>{if(y.has(e)&&e.fallbackResponse){k(`stale-if-error`),r.add(e),e.cacheHit=!0,i.get(e)?.owner===e&&b.add(e);return}if(r.has(e))return;let t=s(e.config,`cache`);if(!t?.enabled||!e.response||!isCacheableRequest(e.config,j,t)||g.has(e))return;let l=m.get(e);if(e.response.raw.type===`opaque`||e.response.raw.type===`opaqueredirect`){i.get(e)?.owner===e&&b.add(e);return}l&&e.response.status===304&&(k(`revalidated`),e.response=createRevalidatedResponse(l,e.response,e.config));let f=i.get(e),p=f?.key??createCacheKey(e.config,t,M,N,P),h=isCurrentCacheGeneration(f?.generation??u.get(e)??c.get(e),A,T),_=(f?.generation??c.get(e))?.token.tags,v=_&&_.size>0?[..._]:l?.tags;if(isAsyncIterable(e.response.data)){if(b.add(e),!h)return;let t=deleteStore(n,p);return a(t)?e.config.signal?o(()=>t,e.config):t:void 0}let x=normalizeCacheTtl(t.ttl,e.config),S=normalizeStaleIfError(t.staleIfError,e.config),C=normalizeStaleWhileRevalidate(t.staleWhileRevalidate,e.config),w=resolveResponseCachePolicy(e.response,x,S,C),E=w.ttl;if(!w.persist){let t=h?deleteStore(n,p):void 0,r=a(t),i=f;return i?.owner===e&&(i.promise!==void 0||r)?d.set(e,createCacheEntry(e.response,Date.now()+Math.max(0,E),e.preserveRaw,v)):i?.owner===e&&b.add(e),r?e.config.signal?o(()=>t,e.config):t:void 0}let D=createCacheEntry(e.response,Date.now()+E,e.preserveRaw,v);if(d.set(e,D),!h||f?.rawDemanded)return;let O=writeStore(n,p,D);if(a(O))return e.config.signal?o(()=>O,e.config):O},{requiresRawResponse:!1});function handleCacheRecord(e,t,i,s,c){if(!(!I||!isCurrentCacheGeneration(c,A,T))){if(s){let l=!isExpired(s.expiresAt),u=h.has(e);if(l&&!u){if(e.preserveRaw&&!s.raw)return prepareCacheMiss(e,t,i,c);let n=restoreCacheEntry(s,e.config);if(n){k(`hit`),e.response=n,r.add(e),e.cacheHit=!0;return}}if(!e.background&&!u&&canUseStaleWhileRevalidate(s,e.config,e.preserveRaw,normalizeStaleWhileRevalidate(t.staleWhileRevalidate,e.config))){let t=restoreCacheEntry(s,e.config);if(t){k(`stale-while-revalidate`),e.response=t,r.add(e),e.cacheHit=!0,startBackgroundRefresh(f,w,i,e.initialConfig,e.preserveRaw,k);return}}if(!e.background&&canUseStaleIfError(s,e.config,e.preserveRaw,normalizeStaleIfError(t.staleIfError,e.config))&&_.set(e,s),canRevalidateCacheEntry(s,e.config,e.preserveRaw)&&restoreCacheEntry(s,e.config))return prepareCacheMiss(e,t,i,c,s);if(l&&u||e.background)return prepareCacheMiss(e,t,i,c);let d=deleteStore(n,i);if(a(d))return(e.config.signal?o(()=>d,e.config):Promise.resolve(d)).then(()=>prepareCacheMiss(e,t,i,c))}return prepareCacheMiss(e,t,i,c)}}function prepareCacheMiss(t,a,s,c,l){if(!I||!isCurrentCacheGeneration(c,A,T))return;if(!(a.dedupe??e.dedupe??!0)){t.background||k(`miss`),u.set(t,c);return}let d=t.preserveRaw?S.get(s):x.get(s)??S.get(s);if(d)return k(`deduplicated`),waitForSharedRecord(getInFlightPromise(d),t.config).then(e=>{e&&(t.response=createCachedResponse(e,t.config),r.add(t),t.cacheHit=!0)});let f=n.acquireRefreshLease;if(f&&!v.has(t)){let e;try{let r=f.call(n,s,t.config.signal);e=t.config.signal?o(()=>r,t.config):r}catch{return v.set(t,{contended:!1,release(){}}),handleCacheRecord(t,a,s,l,c)}return e.then(e=>(v.set(t,e),O.add(e),e.contended&&(h.delete(t),k(`deduplicated`)),Promise.resolve(readStore(n,s)).then(e=>handleCacheRecord(t,a,s,e,c))),e=>{if(t.config.signal?.aborted)throw e;return v.set(t,{contended:!1,release(){}}),handleCacheRecord(t,a,s,l,c)})}if(t.preserveRaw){let e=x.get(s);e&&(e.rawDemanded=!0)}let g=createInFlightRequest(t,s,c);t.preserveRaw?(S.set(s,g),C.add(t)):x.set(s,g),i.set(t,g),p.add(t),t.background||k(`miss`),l&&prepareConditionalRevalidation(t.config,l)&&m.set(t,l)}return f.hooks.onError(e=>{let t=_.get(e);if(!t||!isEligibleStaleIfError(e.error))return;let n=restoreCacheEntry(t,e.config);n&&(y.add(e),e.fallbackResponse=n)}),f.hooks.onSettled(e=>{let n=v.get(e);n&&(n.release(),O.delete(n)),v.delete(e),h.delete(e),g.delete(e),_.delete(e),y.delete(e);let r=c.get(e),invalidateAfterSuccess=()=>{let t=l.get(e);if(l.delete(e),!(!t||e.background||e.error||!e.response))try{let e=F.invalidateTags(t);if(a(e))return Promise.resolve(e).then(()=>{}).catch(ignoreCacheEventError)}catch{}};r&&(c.delete(e),releaseCacheGeneration(r,T));let o=i.get(e);if(!o)return invalidateAfterSuccess();i.delete(e),p.delete(e),m.delete(e);let s=o.key,u=C.delete(e)?S:x;if(u.get(s)===o&&u.delete(s),b.delete(e))return o.resolve?.(void 0),invalidateAfterSuccess();let f=d.get(e);return d.delete(e),f&&e.response&&(!e.error||isSchemaValidationFailure(e.error))?(o.resolve?.(f),invalidateAfterSuccess()):(o.reject?.(e.error??new t(`Shared request failed`,{code:`NETWORK_ERROR`,config:e.config})),invalidateAfterSuccess())}),()=>{I=!1;for(let e of O)e.release();O.clear();for(let e of p){let n=i.get(e);if(i.delete(e),!n)continue;let r=n.key,a=C.delete(e)?S:x;a.get(r)===n&&a.delete(r),n.reject?.(new t(`Cache plugin removed during shared request`,{code:`ABORT_ERROR`}))}p.clear(),T.clear(),abortBackgroundRefreshes(w)}}};return F}export{WebStorageCacheStore as a,MemoryCacheStore as i,TieredCacheStore as n,IndexedDBCacheStore as r,cachePlugin as t};