Socket
Socket
Sign inDemoInstall

workbox-strategies

Package Overview
Dependencies
Maintainers
6
Versions
82
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

workbox-strategies - npm Package Compare versions

Comparing version 6.3.0 to 6.4.0

2

_version.js
"use strict";
// @ts-ignore
try {
self['workbox:strategies:6.2.4'] && _();
self['workbox:strategies:6.3.0'] && _();
}
catch (e) { }

@@ -6,3 +6,3 @@ this.workbox = this.workbox || {};

try {
self['workbox:strategies:6.2.4'] && _();
self['workbox:strategies:6.3.0'] && _();
} catch (e) {}

@@ -401,3 +401,4 @@

// params has a type any can't change right now.
params: this.params
params: this.params // eslint-disable-line
}));

@@ -404,0 +405,0 @@ }

@@ -1,2 +0,2 @@

this.workbox=this.workbox||{},this.workbox.strategies=function(t,e,s,r,n,i,a,o,c){"use strict";try{self["workbox:strategies:6.2.4"]&&_()}catch(t){}function h(t){return"string"==typeof t?new Request(t):t}class l{constructor(t,e){this.yt={},Object.assign(this,e),this.event=e.event,this.ot=t,this.vt=new n.Deferred,this.qt=[],this.bt=[...t.plugins],this.Et=new Map;for(const t of this.bt)this.Et.set(t,{});this.event.waitUntil(this.vt.promise)}async fetch(t){const{event:s}=this;let r=h(t);if("navigate"===r.mode&&s instanceof FetchEvent&&s.preloadResponse){const t=await s.preloadResponse;if(t)return t}const n=this.hasCallback("fetchDidFail")?r.clone():null;try{for(const t of this.iterateCallbacks("requestWillFetch"))r=await t({request:r.clone(),event:s})}catch(t){if(t instanceof Error)throw new e.WorkboxError("plugin-error-request-will-fetch",{thrownErrorMessage:t.message})}const i=r.clone();try{let t;t=await fetch(r,"navigate"===r.mode?void 0:this.ot.fetchOptions);for(const e of this.iterateCallbacks("fetchDidSucceed"))t=await e({event:s,request:i,response:t});return t}catch(t){throw n&&await this.runCallbacks("fetchDidFail",{error:t,event:s,originalRequest:n.clone(),request:i.clone()}),t}}async fetchAndCachePut(t){const e=await this.fetch(t),s=e.clone();return this.waitUntil(this.cachePut(t,s)),e}async cacheMatch(t){const e=h(t);let s;const{cacheName:r,matchOptions:n}=this.ot,i=await this.getCacheKey(e,"read"),a=Object.assign(Object.assign({},n),{cacheName:r});s=await caches.match(i,a);for(const t of this.iterateCallbacks("cachedResponseWillBeUsed"))s=await t({cacheName:r,matchOptions:n,cachedResponse:s,request:i,event:this.event})||void 0;return s}async cachePut(t,s){const n=h(t);await c.timeout(0);const o=await this.getCacheKey(n,"write");if(!s)throw new e.WorkboxError("cache-put-with-no-response",{url:a.getFriendlyURL(o.url)});const l=await this._t(s);if(!l)return!1;const{cacheName:w,matchOptions:u}=this.ot,f=await self.caches.open(w),d=this.hasCallback("cacheDidUpdate"),p=d?await r.cacheMatchIgnoreParams(f,o.clone(),["__WB_REVISION__"],u):null;try{await f.put(o,d?l.clone():l)}catch(t){if(t instanceof Error)throw"QuotaExceededError"===t.name&&await i.executeQuotaErrorCallbacks(),t}for(const t of this.iterateCallbacks("cacheDidUpdate"))await t({cacheName:w,oldResponse:p,newResponse:l.clone(),request:o,event:this.event});return!0}async getCacheKey(t,e){if(!this.yt[e]){let s=t;for(const t of this.iterateCallbacks("cacheKeyWillBeUsed"))s=h(await t({mode:e,request:s,event:this.event,params:this.params}));this.yt[e]=s}return this.yt[e]}hasCallback(t){for(const e of this.ot.plugins)if(t in e)return!0;return!1}async runCallbacks(t,e){for(const s of this.iterateCallbacks(t))await s(e)}*iterateCallbacks(t){for(const e of this.ot.plugins)if("function"==typeof e[t]){const s=this.Et.get(e),r=r=>{const n=Object.assign(Object.assign({},r),{state:s});return e[t](n)};yield r}}waitUntil(t){return this.qt.push(t),t}async doneWaiting(){let t;for(;t=this.qt.shift();)await t}destroy(){this.vt.resolve(null)}async _t(t){let e=t,s=!1;for(const t of this.iterateCallbacks("cacheWillUpdate"))if(e=await t({request:this.request,response:e,event:this.event})||void 0,s=!0,!e)break;return s||e&&200!==e.status&&(e=void 0),e}}class w{constructor(t={}){this.cacheName=s.cacheNames.getRuntimeName(t.cacheName),this.plugins=t.plugins||[],this.fetchOptions=t.fetchOptions,this.matchOptions=t.matchOptions}handle(t){const[e]=this.handleAll(t);return e}handleAll(t){t instanceof FetchEvent&&(t={event:t,request:t.request});const e=t.event,s="string"==typeof t.request?new Request(t.request):t.request,r="params"in t?t.params:void 0,n=new l(this,{event:e,request:s,params:r}),i=this.kt(n,s,e);return[i,this.xt(i,n,s,e)]}async kt(t,s,r){await t.runCallbacks("handlerWillStart",{event:r,request:s});let n=void 0;try{if(n=await this._handle(s,t),!n||"error"===n.type)throw new e.WorkboxError("no-response",{url:s.url})}catch(e){if(e instanceof Error)for(const i of t.iterateCallbacks("handlerDidError"))if(n=await i({error:e,event:r,request:s}),n)break;if(!n)throw e}for(const e of t.iterateCallbacks("handlerWillRespond"))n=await e({event:r,request:s,response:n});return n}async xt(t,e,s,r){let n,i;try{n=await t}catch(i){}try{await e.runCallbacks("handlerDidRespond",{event:r,request:s,response:n}),await e.doneWaiting()}catch(t){t instanceof Error&&(i=t)}if(await e.runCallbacks("handlerDidComplete",{event:r,request:s,response:n,error:i}),e.destroy(),i)throw i}}const u={cacheWillUpdate:async({response:t})=>200===t.status||0===t.status?t:null};return t.CacheFirst=class extends w{async _handle(t,s){let r=await s.cacheMatch(t),n=void 0;if(!r)try{r=await s.fetchAndCachePut(t)}catch(t){t instanceof Error&&(n=t)}if(!r)throw new e.WorkboxError("no-response",{url:t.url,error:n});return r}},t.CacheOnly=class extends w{async _handle(t,s){const r=await s.cacheMatch(t);if(!r)throw new e.WorkboxError("no-response",{url:t.url});return r}},t.NetworkFirst=class extends w{constructor(t={}){super(t),this.plugins.some((t=>"cacheWillUpdate"in t))||this.plugins.unshift(u),this.Rt=t.networkTimeoutSeconds||0}async _handle(t,s){const r=[],n=[];let i;if(this.Rt){const{id:e,promise:a}=this.Wt({request:t,logs:r,handler:s});i=e,n.push(a)}const a=this.Ot({timeoutId:i,request:t,logs:r,handler:s});n.push(a);const o=await s.waitUntil((async()=>await s.waitUntil(Promise.race(n))||await a)());if(!o)throw new e.WorkboxError("no-response",{url:t.url});return o}Wt({request:t,logs:e,handler:s}){let r;return{promise:new Promise((e=>{r=setTimeout((async()=>{e(await s.cacheMatch(t))}),1e3*this.Rt)})),id:r}}async Ot({timeoutId:t,request:e,logs:s,handler:r}){let n,i;try{i=await r.fetchAndCachePut(e)}catch(t){t instanceof Error&&(n=t)}return t&&clearTimeout(t),!n&&i||(i=await r.cacheMatch(e)),i}},t.NetworkOnly=class extends w{constructor(t={}){super(t),this.Rt=t.networkTimeoutSeconds||0}async _handle(t,s){let r,n=void 0;try{const e=[s.fetch(t)];if(this.Rt){const t=c.timeout(1e3*this.Rt);e.push(t)}if(r=await Promise.race(e),!r)throw new Error("Timed out the network response after "+this.Rt+" seconds.")}catch(t){t instanceof Error&&(n=t)}if(!r)throw new e.WorkboxError("no-response",{url:t.url,error:n});return r}},t.StaleWhileRevalidate=class extends w{constructor(t={}){super(t),this.plugins.some((t=>"cacheWillUpdate"in t))||this.plugins.unshift(u)}async _handle(t,s){const r=s.fetchAndCachePut(t).catch((()=>{}));let n,i=await s.cacheMatch(t);if(i);else try{i=await r}catch(t){t instanceof Error&&(n=t)}if(!i)throw new e.WorkboxError("no-response",{url:t.url,error:n});return i}},t.Strategy=w,t.StrategyHandler=l,t}({},workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private);
this.workbox=this.workbox||{},this.workbox.strategies=function(t,e,s,r,n,i,a,o,c){"use strict";try{self["workbox:strategies:6.3.0"]&&_()}catch(t){}function h(t){return"string"==typeof t?new Request(t):t}class l{constructor(t,e){this.yt={},Object.assign(this,e),this.event=e.event,this.ot=t,this.vt=new n.Deferred,this.qt=[],this.bt=[...t.plugins],this.Et=new Map;for(const t of this.bt)this.Et.set(t,{});this.event.waitUntil(this.vt.promise)}async fetch(t){const{event:s}=this;let r=h(t);if("navigate"===r.mode&&s instanceof FetchEvent&&s.preloadResponse){const t=await s.preloadResponse;if(t)return t}const n=this.hasCallback("fetchDidFail")?r.clone():null;try{for(const t of this.iterateCallbacks("requestWillFetch"))r=await t({request:r.clone(),event:s})}catch(t){if(t instanceof Error)throw new e.WorkboxError("plugin-error-request-will-fetch",{thrownErrorMessage:t.message})}const i=r.clone();try{let t;t=await fetch(r,"navigate"===r.mode?void 0:this.ot.fetchOptions);for(const e of this.iterateCallbacks("fetchDidSucceed"))t=await e({event:s,request:i,response:t});return t}catch(t){throw n&&await this.runCallbacks("fetchDidFail",{error:t,event:s,originalRequest:n.clone(),request:i.clone()}),t}}async fetchAndCachePut(t){const e=await this.fetch(t),s=e.clone();return this.waitUntil(this.cachePut(t,s)),e}async cacheMatch(t){const e=h(t);let s;const{cacheName:r,matchOptions:n}=this.ot,i=await this.getCacheKey(e,"read"),a=Object.assign(Object.assign({},n),{cacheName:r});s=await caches.match(i,a);for(const t of this.iterateCallbacks("cachedResponseWillBeUsed"))s=await t({cacheName:r,matchOptions:n,cachedResponse:s,request:i,event:this.event})||void 0;return s}async cachePut(t,s){const n=h(t);await c.timeout(0);const o=await this.getCacheKey(n,"write");if(!s)throw new e.WorkboxError("cache-put-with-no-response",{url:a.getFriendlyURL(o.url)});const l=await this._t(s);if(!l)return!1;const{cacheName:w,matchOptions:u}=this.ot,f=await self.caches.open(w),d=this.hasCallback("cacheDidUpdate"),p=d?await r.cacheMatchIgnoreParams(f,o.clone(),["__WB_REVISION__"],u):null;try{await f.put(o,d?l.clone():l)}catch(t){if(t instanceof Error)throw"QuotaExceededError"===t.name&&await i.executeQuotaErrorCallbacks(),t}for(const t of this.iterateCallbacks("cacheDidUpdate"))await t({cacheName:w,oldResponse:p,newResponse:l.clone(),request:o,event:this.event});return!0}async getCacheKey(t,e){if(!this.yt[e]){let s=t;for(const t of this.iterateCallbacks("cacheKeyWillBeUsed"))s=h(await t({mode:e,request:s,event:this.event,params:this.params}));this.yt[e]=s}return this.yt[e]}hasCallback(t){for(const e of this.ot.plugins)if(t in e)return!0;return!1}async runCallbacks(t,e){for(const s of this.iterateCallbacks(t))await s(e)}*iterateCallbacks(t){for(const e of this.ot.plugins)if("function"==typeof e[t]){const s=this.Et.get(e),r=r=>{const n=Object.assign(Object.assign({},r),{state:s});return e[t](n)};yield r}}waitUntil(t){return this.qt.push(t),t}async doneWaiting(){let t;for(;t=this.qt.shift();)await t}destroy(){this.vt.resolve(null)}async _t(t){let e=t,s=!1;for(const t of this.iterateCallbacks("cacheWillUpdate"))if(e=await t({request:this.request,response:e,event:this.event})||void 0,s=!0,!e)break;return s||e&&200!==e.status&&(e=void 0),e}}class w{constructor(t={}){this.cacheName=s.cacheNames.getRuntimeName(t.cacheName),this.plugins=t.plugins||[],this.fetchOptions=t.fetchOptions,this.matchOptions=t.matchOptions}handle(t){const[e]=this.handleAll(t);return e}handleAll(t){t instanceof FetchEvent&&(t={event:t,request:t.request});const e=t.event,s="string"==typeof t.request?new Request(t.request):t.request,r="params"in t?t.params:void 0,n=new l(this,{event:e,request:s,params:r}),i=this.kt(n,s,e);return[i,this.xt(i,n,s,e)]}async kt(t,s,r){await t.runCallbacks("handlerWillStart",{event:r,request:s});let n=void 0;try{if(n=await this._handle(s,t),!n||"error"===n.type)throw new e.WorkboxError("no-response",{url:s.url})}catch(e){if(e instanceof Error)for(const i of t.iterateCallbacks("handlerDidError"))if(n=await i({error:e,event:r,request:s}),n)break;if(!n)throw e}for(const e of t.iterateCallbacks("handlerWillRespond"))n=await e({event:r,request:s,response:n});return n}async xt(t,e,s,r){let n,i;try{n=await t}catch(i){}try{await e.runCallbacks("handlerDidRespond",{event:r,request:s,response:n}),await e.doneWaiting()}catch(t){t instanceof Error&&(i=t)}if(await e.runCallbacks("handlerDidComplete",{event:r,request:s,response:n,error:i}),e.destroy(),i)throw i}}const u={cacheWillUpdate:async({response:t})=>200===t.status||0===t.status?t:null};return t.CacheFirst=class extends w{async _handle(t,s){let r=await s.cacheMatch(t),n=void 0;if(!r)try{r=await s.fetchAndCachePut(t)}catch(t){t instanceof Error&&(n=t)}if(!r)throw new e.WorkboxError("no-response",{url:t.url,error:n});return r}},t.CacheOnly=class extends w{async _handle(t,s){const r=await s.cacheMatch(t);if(!r)throw new e.WorkboxError("no-response",{url:t.url});return r}},t.NetworkFirst=class extends w{constructor(t={}){super(t),this.plugins.some((t=>"cacheWillUpdate"in t))||this.plugins.unshift(u),this.Rt=t.networkTimeoutSeconds||0}async _handle(t,s){const r=[],n=[];let i;if(this.Rt){const{id:e,promise:a}=this.Wt({request:t,logs:r,handler:s});i=e,n.push(a)}const a=this.Ot({timeoutId:i,request:t,logs:r,handler:s});n.push(a);const o=await s.waitUntil((async()=>await s.waitUntil(Promise.race(n))||await a)());if(!o)throw new e.WorkboxError("no-response",{url:t.url});return o}Wt({request:t,logs:e,handler:s}){let r;return{promise:new Promise((e=>{r=setTimeout((async()=>{e(await s.cacheMatch(t))}),1e3*this.Rt)})),id:r}}async Ot({timeoutId:t,request:e,logs:s,handler:r}){let n,i;try{i=await r.fetchAndCachePut(e)}catch(t){t instanceof Error&&(n=t)}return t&&clearTimeout(t),!n&&i||(i=await r.cacheMatch(e)),i}},t.NetworkOnly=class extends w{constructor(t={}){super(t),this.Rt=t.networkTimeoutSeconds||0}async _handle(t,s){let r,n=void 0;try{const e=[s.fetch(t)];if(this.Rt){const t=c.timeout(1e3*this.Rt);e.push(t)}if(r=await Promise.race(e),!r)throw new Error("Timed out the network response after "+this.Rt+" seconds.")}catch(t){t instanceof Error&&(n=t)}if(!r)throw new e.WorkboxError("no-response",{url:t.url,error:n});return r}},t.StaleWhileRevalidate=class extends w{constructor(t={}){super(t),this.plugins.some((t=>"cacheWillUpdate"in t))||this.plugins.unshift(u)}async _handle(t,s){const r=s.fetchAndCachePut(t).catch((()=>{}));let n,i=await s.cacheMatch(t);if(i);else try{i=await r}catch(t){t instanceof Error&&(n=t)}if(!i)throw new e.WorkboxError("no-response",{url:t.url,error:n});return i}},t.Strategy=w,t.StrategyHandler=l,t}({},workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private);
//# sourceMappingURL=workbox-strategies.prod.js.map

@@ -48,4 +48,3 @@ /*

if (response) {
logger.log(`Found a cached response in the '${this.cacheName}' ` +
`cache.`);
logger.log(`Found a cached response in the '${this.cacheName}' ` + `cache.`);
messages.printFinalResponse(response);

@@ -52,0 +51,0 @@ }

import { CacheFirst } from './CacheFirst.js';
import { CacheOnly } from './CacheOnly.js';
import { NetworkFirst } from './NetworkFirst.js';
import { NetworkOnly } from './NetworkOnly.js';
import { NetworkFirst, NetworkFirstOptions } from './NetworkFirst.js';
import { NetworkOnly, NetworkOnlyOptions } from './NetworkOnly.js';
import { StaleWhileRevalidate } from './StaleWhileRevalidate.js';
import { Strategy } from './Strategy.js';
import { Strategy, StrategyOptions } from './Strategy.js';
import { StrategyHandler } from './StrategyHandler.js';
import './_version.js';
declare global {
interface FetchEvent {
readonly preloadResponse: Promise<Response | undefined>;
}
}
/**

@@ -15,2 +20,2 @@ * There are common caching strategies that most service workers will need

*/
export { CacheFirst, CacheOnly, NetworkFirst, NetworkOnly, StaleWhileRevalidate, Strategy, StrategyHandler, };
export { CacheFirst, CacheOnly, NetworkFirst, NetworkFirstOptions, NetworkOnly, NetworkOnlyOptions, StaleWhileRevalidate, Strategy, StrategyHandler, StrategyOptions, };

@@ -73,3 +73,3 @@ import { Strategy, StrategyOptions } from './Strategy.js';

*/
_getNetworkPromise({ timeoutId, request, logs, handler }: {
_getNetworkPromise({ timeoutId, request, logs, handler, }: {
request: Request;

@@ -76,0 +76,0 @@ logs: any[];

@@ -94,7 +94,12 @@ /*

}
const networkPromise = this._getNetworkPromise({ timeoutId, request, logs, handler });
const networkPromise = this._getNetworkPromise({
timeoutId,
request,
logs,
handler,
});
promises.push(networkPromise);
const response = await handler.waitUntil((async () => {
// Promise.race() will resolve as soon as the first promise resolves.
return await handler.waitUntil(Promise.race(promises)) ||
return ((await handler.waitUntil(Promise.race(promises))) ||
// If Promise.race() resolved with null, it might be due to a network

@@ -105,3 +110,3 @@ // timeout + a cache miss. If that were to happen, we'd rather wait until

// have to check to see if it's still "in flight".
await networkPromise;
(await networkPromise));
})());

@@ -130,3 +135,3 @@ if (process.env.NODE_ENV !== 'production') {

*/
_getTimeoutPromise({ request, logs, handler }) {
_getTimeoutPromise({ request, logs, handler, }) {
let timeoutId;

@@ -158,3 +163,3 @@ const timeoutPromise = new Promise((resolve) => {

*/
async _getNetworkPromise({ timeoutId, request, logs, handler }) {
async _getNetworkPromise({ timeoutId, request, logs, handler, }) {
let error;

@@ -186,4 +191,3 @@ let response;

if (response) {
logs.push(`Found a cached response in the '${this.cacheName}'` +
` cache.`);
logs.push(`Found a cached response in the '${this.cacheName}'` + ` cache.`);
}

@@ -190,0 +194,0 @@ else {

@@ -63,3 +63,5 @@ /*

try {
const promises = [handler.fetch(request)];
const promises = [
handler.fetch(request),
];
if (this._networkTimeoutSeconds) {

@@ -66,0 +68,0 @@ const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000);

{
"name": "workbox-strategies",
"version": "6.3.0",
"version": "6.4.0",
"license": "MIT",

@@ -26,5 +26,5 @@ "author": "Google's Web DevRel Team",

"dependencies": {
"workbox-core": "6.3.0"
"workbox-core": "6.4.0"
},
"gitHead": "03055e64014a46f6cc977a3a50ad814c6409d36a"
"gitHead": "cdad230c678a3626c217615d5792eb0f1c77194c"
}
// @ts-ignore
try{self['workbox:strategies:6.3.0']&&_()}catch(e){}
try{self['workbox:strategies:6.4.0']&&_()}catch(e){}

@@ -18,3 +18,2 @@ /*

/**

@@ -60,4 +59,5 @@ * An implementation of a [cache-first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network}

logs.push(
`No response found in the '${this.cacheName}' cache. ` +
`Will respond with a network request.`);
`No response found in the '${this.cacheName}' cache. ` +
`Will respond with a network request.`,
);
}

@@ -81,4 +81,3 @@ try {

if (process.env.NODE_ENV !== 'production') {
logs.push(
`Found a cached response in the '${this.cacheName}' cache.`);
logs.push(`Found a cached response in the '${this.cacheName}' cache.`);
}

@@ -89,3 +88,4 @@ }

logger.groupCollapsed(
messages.strategyStart(this.constructor.name, request));
messages.strategyStart(this.constructor.name, request),
);
for (const log of logs) {

@@ -92,0 +92,0 @@ logger.log(log);

@@ -18,3 +18,2 @@ /*

/**

@@ -55,6 +54,8 @@ * An implementation of a

logger.groupCollapsed(
messages.strategyStart(this.constructor.name, request));
messages.strategyStart(this.constructor.name, request),
);
if (response) {
logger.log(`Found a cached response in the '${this.cacheName}' ` +
`cache.`);
logger.log(
`Found a cached response in the '${this.cacheName}' ` + `cache.`,
);
messages.printFinalResponse(response);

@@ -61,0 +62,0 @@ } else {

@@ -11,9 +11,15 @@ /*

import {CacheOnly} from './CacheOnly.js';
import {NetworkFirst} from './NetworkFirst.js';
import {NetworkOnly} from './NetworkOnly.js';
import {NetworkFirst, NetworkFirstOptions} from './NetworkFirst.js';
import {NetworkOnly, NetworkOnlyOptions} from './NetworkOnly.js';
import {StaleWhileRevalidate} from './StaleWhileRevalidate.js';
import {Strategy} from './Strategy.js';
import {Strategy, StrategyOptions} from './Strategy.js';
import {StrategyHandler} from './StrategyHandler.js';
import './_version.js';
// See https://github.com/GoogleChrome/workbox/issues/2946
declare global {
interface FetchEvent {
readonly preloadResponse: Promise<Response | undefined>;
}
}

@@ -31,7 +37,9 @@ /**

NetworkFirst,
NetworkFirstOptions,
NetworkOnly,
NetworkOnlyOptions,
StaleWhileRevalidate,
Strategy,
StrategyHandler,
StrategyOptions,
};

@@ -19,3 +19,2 @@ /*

export interface NetworkFirstOptions extends StrategyOptions {

@@ -113,10 +112,16 @@ networkTimeoutSeconds?: number;

const networkPromise =
this._getNetworkPromise({timeoutId, request, logs, handler});
const networkPromise = this._getNetworkPromise({
timeoutId,
request,
logs,
handler,
});
promises.push(networkPromise);
const response = await handler.waitUntil((async () => {
// Promise.race() will resolve as soon as the first promise resolves.
return await handler.waitUntil(Promise.race(promises)) ||
const response = await handler.waitUntil(
(async () => {
// Promise.race() will resolve as soon as the first promise resolves.
return (
(await handler.waitUntil(Promise.race(promises))) ||
// If Promise.race() resolved with null, it might be due to a network

@@ -127,8 +132,11 @@ // timeout + a cache miss. If that were to happen, we'd rather wait until

// have to check to see if it's still "in flight".
await networkPromise;
})());
(await networkPromise)
);
})(),
);
if (process.env.NODE_ENV !== 'production') {
logger.groupCollapsed(
messages.strategyStart(this.constructor.name, request));
messages.strategyStart(this.constructor.name, request),
);
for (const log of logs) {

@@ -156,3 +164,7 @@ logger.log(log);

*/
private _getTimeoutPromise({request, logs, handler}: {
private _getTimeoutPromise({
request,
logs,
handler,
}: {
request: Request;

@@ -163,15 +175,19 @@ logs: any[];

let timeoutId;
const timeoutPromise: Promise<Response | undefined> = new Promise((resolve) => {
const onNetworkTimeout = async () => {
if (process.env.NODE_ENV !== 'production') {
logs.push(`Timing out the network response at ` +
`${this._networkTimeoutSeconds} seconds.`);
}
resolve(await handler.cacheMatch(request));
};
timeoutId = setTimeout(
const timeoutPromise: Promise<Response | undefined> = new Promise(
(resolve) => {
const onNetworkTimeout = async () => {
if (process.env.NODE_ENV !== 'production') {
logs.push(
`Timing out the network response at ` +
`${this._networkTimeoutSeconds} seconds.`,
);
}
resolve(await handler.cacheMatch(request));
};
timeoutId = setTimeout(
onNetworkTimeout,
this._networkTimeoutSeconds * 1000,
);
});
);
},
);

@@ -194,3 +210,8 @@ return {

*/
async _getNetworkPromise({timeoutId, request, logs, handler}: {
async _getNetworkPromise({
timeoutId,
request,
logs,
handler,
}: {
request: Request;

@@ -200,3 +221,3 @@ logs: any[];

handler: StrategyHandler;
}): Promise<Response|undefined> {
}): Promise<Response | undefined> {
let error;

@@ -220,4 +241,6 @@ let response;

} else {
logs.push(`Unable to get a response from the network. Will respond ` +
`with a cached response.`);
logs.push(
`Unable to get a response from the network. Will respond ` +
`with a cached response.`,
);
}

@@ -231,4 +254,5 @@ }

if (response) {
logs.push(`Found a cached response in the '${this.cacheName}'` +
` cache.`);
logs.push(
`Found a cached response in the '${this.cacheName}'` + ` cache.`,
);
} else {

@@ -235,0 +259,0 @@ logs.push(`No response found in the '${this.cacheName}' cache.`);

@@ -19,4 +19,4 @@ /*

interface NetworkOnlyOptions extends Omit<StrategyOptions, 'cacheName' | 'matchOptions'> {
interface NetworkOnlyOptions
extends Omit<StrategyOptions, 'cacheName' | 'matchOptions'> {
networkTimeoutSeconds?: number;

@@ -79,6 +79,10 @@ }

try {
const promises: Promise<Response|undefined>[] = [handler.fetch(request)];
const promises: Promise<Response | undefined>[] = [
handler.fetch(request),
];
if (this._networkTimeoutSeconds) {
const timeoutPromise = timeout(this._networkTimeoutSeconds * 1000) as Promise<undefined>;
const timeoutPromise = timeout(
this._networkTimeoutSeconds * 1000,
) as Promise<undefined>;
promises.push(timeoutPromise);

@@ -89,4 +93,6 @@ }

if (!response) {
throw new Error(`Timed out the network response after ` +
`${this._networkTimeoutSeconds} seconds.`);
throw new Error(
`Timed out the network response after ` +
`${this._networkTimeoutSeconds} seconds.`,
);
}

@@ -101,3 +107,4 @@ } catch (err) {

logger.groupCollapsed(
messages.strategyStart(this.constructor.name, request));
messages.strategyStart(this.constructor.name, request),
);
if (response) {

@@ -104,0 +111,0 @@ logger.log(`Got response from network.`);

@@ -12,3 +12,2 @@ /*

export const cacheOkAndOpaquePlugin: WorkboxPlugin = {

@@ -15,0 +14,0 @@ /**

@@ -19,3 +19,2 @@ /*

/**

@@ -85,8 +84,6 @@ * An implementation of a

const fetchAndCachePromise = handler
.fetchAndCachePut(request)
.catch(() => {
// Swallow this error because a 'no-response' error will be thrown in
// main handler return flow. This will be in the `waitUntil()` flow.
});
const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => {
// Swallow this error because a 'no-response' error will be thrown in
// main handler return flow. This will be in the `waitUntil()` flow.
});

@@ -98,9 +95,13 @@ let response = await handler.cacheMatch(request);

if (process.env.NODE_ENV !== 'production') {
logs.push(`Found a cached response in the '${this.cacheName}'` +
` cache. Will update with the network response in the background.`);
logs.push(
`Found a cached response in the '${this.cacheName}'` +
` cache. Will update with the network response in the background.`,
);
}
} else {
if (process.env.NODE_ENV !== 'production') {
logs.push(`No response found in the '${this.cacheName}' cache. ` +
`Will wait for the network response.`);
logs.push(
`No response found in the '${this.cacheName}' cache. ` +
`Will wait for the network response.`,
);
}

@@ -110,3 +111,3 @@ try {

// https://github.com/microsoft/TypeScript/issues/20006
response = (await fetchAndCachePromise as Response | undefined);
response = (await fetchAndCachePromise) as Response | undefined;
} catch (err) {

@@ -121,3 +122,4 @@ if (err instanceof Error) {

logger.groupCollapsed(
messages.strategyStart(this.constructor.name, request));
messages.strategyStart(this.constructor.name, request),
);
for (const log of logs) {

@@ -124,0 +126,0 @@ logger.log(log);

@@ -13,4 +13,7 @@ /*

import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js';
import {HandlerCallbackOptions, RouteHandlerObject, WorkboxPlugin}
from 'workbox-core/types.js';
import {
HandlerCallbackOptions,
RouteHandlerObject,
WorkboxPlugin,
} from 'workbox-core/types.js';

@@ -41,3 +44,3 @@ import {StrategyHandler} from './StrategyHandler.js';

request: Request,
handler: StrategyHandler
handler: StrategyHandler,
): Promise<Response | undefined>;

@@ -148,6 +151,5 @@

*/
handleAll(options: FetchEvent | HandlerCallbackOptions): [
Promise<Response>,
Promise<void>,
] {
handleAll(
options: FetchEvent | HandlerCallbackOptions,
): [Promise<Response>, Promise<void>] {
// Allow for flexible options to be passed.

@@ -162,5 +164,6 @@ if (options instanceof FetchEvent) {

const event = options.event;
const request = typeof options.request === 'string' ?
new Request(options.request) :
options.request;
const request =
typeof options.request === 'string'
? new Request(options.request)
: options.request;
const params = 'params' in options ? options.params : undefined;

@@ -171,3 +174,8 @@

const responseDone = this._getResponse(handler, request, event);
const handlerDone = this._awaitComplete(responseDone, handler, request, event);
const handlerDone = this._awaitComplete(
responseDone,
handler,
request,
event,
);

@@ -178,3 +186,7 @@ // Return an array of promises, suitable for use with Promise.all().

async _getResponse(handler: StrategyHandler, request: Request, event: ExtendableEvent): Promise<Response> {
async _getResponse(
handler: StrategyHandler,
request: Request,
event: ExtendableEvent,
): Promise<Response> {
await handler.runCallbacks('handlerWillStart', {event, request});

@@ -204,5 +216,9 @@

} else if (process.env.NODE_ENV !== 'production') {
logger.log(`While responding to '${getFriendlyURL(request.url)}', ` +
`an ${error instanceof Error ? error.toString() : ''} error occurred. Using a fallback response provided by ` +
`a handlerDidError plugin.`);
logger.log(
`While responding to '${getFriendlyURL(request.url)}', ` +
`an ${
error instanceof Error ? error.toString() : ''
} error occurred. Using a fallback response provided by ` +
`a handlerDidError plugin.`,
);
}

@@ -218,3 +234,8 @@ }

async _awaitComplete(responseDone: Promise<Response>, handler: StrategyHandler, request: Request, event: ExtendableEvent): Promise<void> {
async _awaitComplete(
responseDone: Promise<Response>,
handler: StrategyHandler,
request: Request,
event: ExtendableEvent,
): Promise<void> {
let response;

@@ -242,3 +263,2 @@ let error;

}
}

@@ -260,3 +280,3 @@

export {Strategy}
export {Strategy};

@@ -263,0 +283,0 @@ /**

@@ -27,5 +27,4 @@ /*

function toRequest(input: RequestInfo) {
return (typeof input === 'string') ? new Request(input) : input;
return typeof input === 'string' ? new Request(input) : input;
}

@@ -155,10 +154,14 @@

if (request.mode === 'navigate' &&
event instanceof FetchEvent &&
event.preloadResponse) {
const possiblePreloadResponse = await event.preloadResponse as Response | undefined;
if (
request.mode === 'navigate' &&
event instanceof FetchEvent &&
event.preloadResponse
) {
const possiblePreloadResponse = await event.preloadResponse;
if (possiblePreloadResponse) {
if (process.env.NODE_ENV !== 'production') {
logger.log(`Using a preloaded navigation response for ` +
`'${getFriendlyURL(request.url)}'`);
logger.log(
`Using a preloaded navigation response for ` +
`'${getFriendlyURL(request.url)}'`,
);
}

@@ -172,4 +175,5 @@ return possiblePreloadResponse;

// plugin or before the original request's body is consumed via fetch().
const originalRequest = this.hasCallback('fetchDidFail') ?
request.clone() : null;
const originalRequest = this.hasCallback('fetchDidFail')
? request.clone()
: null;

@@ -182,4 +186,5 @@ try {

if (err instanceof Error) {
throw new WorkboxError('plugin-error-request-will-fetch',
{thrownErrorMessage: err.message});
throw new WorkboxError('plugin-error-request-will-fetch', {
thrownErrorMessage: err.message,
});
}

@@ -197,9 +202,13 @@ }

// See https://github.com/GoogleChrome/workbox/issues/1796
fetchResponse = await fetch(request, request.mode === 'navigate' ?
undefined : this._strategy.fetchOptions);
fetchResponse = await fetch(
request,
request.mode === 'navigate' ? undefined : this._strategy.fetchOptions,
);
if (process.env.NODE_ENV !== 'production') {
logger.debug(`Network request for ` +
logger.debug(
`Network request for ` +
`'${getFriendlyURL(request.url)}' returned a response with ` +
`status '${fetchResponse.status}'.`);
`status '${fetchResponse.status}'.`,
);
}

@@ -217,4 +226,7 @@

if (process.env.NODE_ENV !== 'production') {
logger.log(`Network request for `+
`'${getFriendlyURL(request.url)}' threw an error.`, error);
logger.log(
`Network request for ` +
`'${getFriendlyURL(request.url)}' threw an error.`,
error,
);
}

@@ -286,9 +298,10 @@

for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) {
cachedResponse = (await callback({
cacheName,
matchOptions,
cachedResponse,
request: effectiveRequest,
event: this.event,
})) || undefined;
cachedResponse =
(await callback({
cacheName,
matchOptions,
cachedResponse,
request: effectiveRequest,
event: this.event,
})) || undefined;
}

@@ -344,4 +357,6 @@ return cachedResponse;

if (process.env.NODE_ENV !== 'production') {
logger.error(`Cannot cache non-existent response for ` +
`'${getFriendlyURL(effectiveRequest.url)}'.`);
logger.error(
`Cannot cache non-existent response for ` +
`'${getFriendlyURL(effectiveRequest.url)}'.`,
);
}

@@ -358,4 +373,7 @@

if (process.env.NODE_ENV !== 'production') {
logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' ` +
`will not be cached.`, responseToCache);
logger.debug(
`Response '${getFriendlyURL(effectiveRequest.url)}' ` +
`will not be cached.`,
responseToCache,
);
}

@@ -369,20 +387,29 @@ return false;

const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate');
const oldResponse = hasCacheUpdateCallback ? await cacheMatchIgnoreParams(
// TODO(philipwalton): the `__WB_REVISION__` param is a precaching
// feature. Consider into ways to only add this behavior if using
// precaching.
cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions) :
null;
const oldResponse = hasCacheUpdateCallback
? await cacheMatchIgnoreParams(
// TODO(philipwalton): the `__WB_REVISION__` param is a precaching
// feature. Consider into ways to only add this behavior if using
// precaching.
cache,
effectiveRequest.clone(),
['__WB_REVISION__'],
matchOptions,
)
: null;
if (process.env.NODE_ENV !== 'production') {
logger.debug(`Updating the '${cacheName}' cache with a new Response ` +
`for ${getFriendlyURL(effectiveRequest.url)}.`);
logger.debug(
`Updating the '${cacheName}' cache with a new Response ` +
`for ${getFriendlyURL(effectiveRequest.url)}.`,
);
}
try {
await cache.put(effectiveRequest, hasCacheUpdateCallback ?
responseToCache.clone() : responseToCache);
await cache.put(
effectiveRequest,
hasCacheUpdateCallback ? responseToCache.clone() : responseToCache,
);
} catch (error) {
if (error instanceof Error) {
// See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
// See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError
if (error.name === 'QuotaExceededError') {

@@ -419,3 +446,6 @@ await executeQuotaErrorCallbacks();

*/
async getCacheKey(request: Request, mode: 'read' | 'write'): Promise<Request> {
async getCacheKey(
request: Request,
mode: 'read' | 'write',
): Promise<Request> {
if (!this._cacheKeys[mode]) {

@@ -425,9 +455,11 @@ let effectiveRequest = request;

for (const callback of this.iterateCallbacks('cacheKeyWillBeUsed')) {
effectiveRequest = toRequest(await callback({
mode,
request: effectiveRequest,
event: this.event,
// params has a type any can't change right now.
params: this.params, // eslint-disable-line
}));
effectiveRequest = toRequest(
await callback({
mode,
request: effectiveRequest,
event: this.event,
// params has a type any can't change right now.
params: this.params, // eslint-disable-line
}),
);
}

@@ -498,3 +530,5 @@

const state = this._pluginStateMap.get(plugin);
const statefulCallback = (param: Omit<WorkboxPluginCallbackParam[C], 'state'>) => {
const statefulCallback = (
param: Omit<WorkboxPluginCallbackParam[C], 'state'>,
) => {
const statefulParam = {...param, state};

@@ -541,3 +575,3 @@

let promise;
while (promise = this._extendLifetimePromises.shift()) {
while ((promise = this._extendLifetimePromises.shift())) {
await promise;

@@ -565,3 +599,5 @@ }

*/
async _ensureResponseSafeToCache(response: Response): Promise<Response | undefined> {
async _ensureResponseSafeToCache(
response: Response,
): Promise<Response | undefined> {
let responseToCache: Response | undefined = response;

@@ -571,7 +607,8 @@ let pluginsUsed = false;

for (const callback of this.iterateCallbacks('cacheWillUpdate')) {
responseToCache = (await callback({
request: this.request,
response: responseToCache,
event: this.event,
})) || undefined;
responseToCache =
(await callback({
request: this.request,
response: responseToCache,
event: this.event,
})) || undefined;
pluginsUsed = true;

@@ -592,9 +629,13 @@

if (responseToCache.status === 0) {
logger.warn(`The response for '${this.request.url}' ` +
logger.warn(
`The response for '${this.request.url}' ` +
`is an opaque response. The caching strategy that you're ` +
`using will not cache opaque responses by default.`);
`using will not cache opaque responses by default.`,
);
} else {
logger.debug(`The response for '${this.request.url}' ` +
logger.debug(
`The response for '${this.request.url}' ` +
`returned a status code of '${response.status}' and won't ` +
`be cached as a result.`);
`be cached as a result.`,
);
}

@@ -610,2 +651,2 @@ }

export {StrategyHandler}
export {StrategyHandler};

@@ -13,3 +13,2 @@ /*

export const messages = {

@@ -16,0 +15,0 @@ strategyStart: (strategyName: string, request: Request): string =>

@@ -75,5 +75,3 @@ /*

}
const fetchAndCachePromise = handler
.fetchAndCachePut(request)
.catch(() => {
const fetchAndCachePromise = handler.fetchAndCachePut(request).catch(() => {
// Swallow this error because a 'no-response' error will be thrown in

@@ -98,3 +96,3 @@ // main handler return flow. This will be in the `waitUntil()` flow.

// https://github.com/microsoft/TypeScript/issues/20006
response = await fetchAndCachePromise;
response = (await fetchAndCachePromise);
}

@@ -101,0 +99,0 @@ catch (err) {

@@ -86,6 +86,3 @@ import { HandlerCallbackOptions, RouteHandlerObject, WorkboxPlugin } from 'workbox-core/types.js';

*/
handleAll(options: FetchEvent | HandlerCallbackOptions): [
Promise<Response>,
Promise<void>
];
handleAll(options: FetchEvent | HandlerCallbackOptions): [Promise<Response>, Promise<void>];
_getResponse(handler: StrategyHandler, request: Request, event: ExtendableEvent): Promise<Response>;

@@ -92,0 +89,0 @@ _awaitComplete(responseDone: Promise<Response>, handler: StrategyHandler, request: Request, event: ExtendableEvent): Promise<void>;

@@ -130,5 +130,5 @@ /*

const event = options.event;
const request = typeof options.request === 'string' ?
new Request(options.request) :
options.request;
const request = typeof options.request === 'string'
? new Request(options.request)
: options.request;
const params = 'params' in options ? options.params : undefined;

@@ -135,0 +135,0 @@ const handler = new StrategyHandler(this, { event, request, params });

@@ -18,3 +18,3 @@ /*

function toRequest(input) {
return (typeof input === 'string') ? new Request(input) : input;
return typeof input === 'string' ? new Request(input) : input;
}

@@ -140,4 +140,5 @@ /**

// plugin or before the original request's body is consumed via fetch().
const originalRequest = this.hasCallback('fetchDidFail') ?
request.clone() : null;
const originalRequest = this.hasCallback('fetchDidFail')
? request.clone()
: null;
try {

@@ -150,3 +151,5 @@ for (const cb of this.iterateCallbacks('requestWillFetch')) {

if (err instanceof Error) {
throw new WorkboxError('plugin-error-request-will-fetch', { thrownErrorMessage: err.message });
throw new WorkboxError('plugin-error-request-will-fetch', {
thrownErrorMessage: err.message,
});
}

@@ -161,4 +164,3 @@ }

// See https://github.com/GoogleChrome/workbox/issues/1796
fetchResponse = await fetch(request, request.mode === 'navigate' ?
undefined : this._strategy.fetchOptions);
fetchResponse = await fetch(request, request.mode === 'navigate' ? undefined : this._strategy.fetchOptions);
if (process.env.NODE_ENV !== 'production') {

@@ -240,9 +242,10 @@ logger.debug(`Network request for ` +

for (const callback of this.iterateCallbacks('cachedResponseWillBeUsed')) {
cachedResponse = (await callback({
cacheName,
matchOptions,
cachedResponse,
request: effectiveRequest,
event: this.event,
})) || undefined;
cachedResponse =
(await callback({
cacheName,
matchOptions,
cachedResponse,
request: effectiveRequest,
event: this.event,
})) || undefined;
}

@@ -308,8 +311,9 @@ return cachedResponse;

const hasCacheUpdateCallback = this.hasCallback('cacheDidUpdate');
const oldResponse = hasCacheUpdateCallback ? await cacheMatchIgnoreParams(
// TODO(philipwalton): the `__WB_REVISION__` param is a precaching
// feature. Consider into ways to only add this behavior if using
// precaching.
cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions) :
null;
const oldResponse = hasCacheUpdateCallback
? await cacheMatchIgnoreParams(
// TODO(philipwalton): the `__WB_REVISION__` param is a precaching
// feature. Consider into ways to only add this behavior if using
// precaching.
cache, effectiveRequest.clone(), ['__WB_REVISION__'], matchOptions)
: null;
if (process.env.NODE_ENV !== 'production') {

@@ -320,4 +324,3 @@ logger.debug(`Updating the '${cacheName}' cache with a new Response ` +

try {
await cache.put(effectiveRequest, hasCacheUpdateCallback ?
responseToCache.clone() : responseToCache);
await cache.put(effectiveRequest, hasCacheUpdateCallback ? responseToCache.clone() : responseToCache);
}

@@ -364,3 +367,3 @@ catch (error) {

// params has a type any can't change right now.
params: this.params,
params: this.params, // eslint-disable-line
}));

@@ -462,3 +465,3 @@ }

let promise;
while (promise = this._extendLifetimePromises.shift()) {
while ((promise = this._extendLifetimePromises.shift())) {
await promise;

@@ -488,7 +491,8 @@ }

for (const callback of this.iterateCallbacks('cacheWillUpdate')) {
responseToCache = (await callback({
request: this.request,
response: responseToCache,
event: this.event,
})) || undefined;
responseToCache =
(await callback({
request: this.request,
response: responseToCache,
event: this.event,
})) || undefined;
pluginsUsed = true;

@@ -495,0 +499,0 @@ if (!responseToCache) {

@@ -8,8 +8,4 @@ {

},
"include": [
"src/**/*.ts"
],
"references": [
{ "path": "../workbox-core/" }
]
"include": ["src/**/*.ts"],
"references": [{"path": "../workbox-core/"}]
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc