Socket
Socket
Sign inDemoInstall

workbox-background-sync

Package Overview
Dependencies
Maintainers
6
Versions
97
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

workbox-background-sync - npm Package Compare versions

Comparing version 6.1.5 to 6.2.0-alpha.0

lib/QueueDb.d.ts

2

_version.js
"use strict";
// @ts-ignore
try {
self['workbox:background-sync:6.1.5'] && _();
self['workbox:background-sync:6.2.0-alpha.0'] && _();
}
catch (e) { }
this.workbox = this.workbox || {};
this.workbox.backgroundSync = (function (exports, WorkboxError_js, logger_js, assert_js, getFriendlyURL_js, DBWrapper_js) {
this.workbox.backgroundSync = (function (exports, WorkboxError_js, logger_js, assert_js, getFriendlyURL_js) {
'use strict';
try {
self['workbox:background-sync:6.1.5'] && _();
self['workbox:background-sync:6.2.0-alpha.0'] && _();
} catch (e) {}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
const instanceOfAny = (object, constructors) => constructors.some(c => object instanceof c);
let idbProxyableTypes;
let cursorAdvanceMethods; // This is a function to prevent it throwing up in node environments.
function getIdbProxyableTypes() {
return idbProxyableTypes || (idbProxyableTypes = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction]);
} // This is a function to prevent it throwing up in node environments.
function getCursorAdvanceMethods() {
return cursorAdvanceMethods || (cursorAdvanceMethods = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey]);
}
const cursorRequestMap = new WeakMap();
const transactionDoneMap = new WeakMap();
const transactionStoreNamesMap = new WeakMap();
const transformCache = new WeakMap();
const reverseTransformCache = new WeakMap();
function promisifyRequest(request) {
const promise = new Promise((resolve, reject) => {
const unlisten = () => {
request.removeEventListener('success', success);
request.removeEventListener('error', error);
};
const success = () => {
resolve(wrap(request.result));
unlisten();
};
const error = () => {
reject(request.error);
unlisten();
};
request.addEventListener('success', success);
request.addEventListener('error', error);
});
promise.then(value => {
// Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
// (see wrapFunction).
if (value instanceof IDBCursor) {
cursorRequestMap.set(value, request);
} // Catching to avoid "Uncaught Promise exceptions"
}).catch(() => {}); // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
// is because we create many promises from a single IDBRequest.
reverseTransformCache.set(promise, request);
return promise;
}
function cacheDonePromiseForTransaction(tx) {
// Early bail if we've already created a done promise for this transaction.
if (transactionDoneMap.has(tx)) return;
const done = new Promise((resolve, reject) => {
const unlisten = () => {
tx.removeEventListener('complete', complete);
tx.removeEventListener('error', error);
tx.removeEventListener('abort', error);
};
const complete = () => {
resolve();
unlisten();
};
const error = () => {
reject(tx.error || new DOMException('AbortError', 'AbortError'));
unlisten();
};
tx.addEventListener('complete', complete);
tx.addEventListener('error', error);
tx.addEventListener('abort', error);
}); // Cache it for later retrieval.
transactionDoneMap.set(tx, done);
}
let idbProxyTraps = {
get(target, prop, receiver) {
if (target instanceof IDBTransaction) {
// Special handling for transaction.done.
if (prop === 'done') return transactionDoneMap.get(target); // Polyfill for objectStoreNames because of Edge.
if (prop === 'objectStoreNames') {
return target.objectStoreNames || transactionStoreNamesMap.get(target);
} // Make tx.store return the only store in the transaction, or undefined if there are many.
if (prop === 'store') {
return receiver.objectStoreNames[1] ? undefined : receiver.objectStore(receiver.objectStoreNames[0]);
}
} // Else transform whatever we get back.
return wrap(target[prop]);
},
set(target, prop, value) {
target[prop] = value;
return true;
},
has(target, prop) {
if (target instanceof IDBTransaction && (prop === 'done' || prop === 'store')) {
return true;
}
return prop in target;
}
};
function replaceTraps(callback) {
idbProxyTraps = callback(idbProxyTraps);
}
function wrapFunction(func) {
// Due to expected object equality (which is enforced by the caching in `wrap`), we
// only create one new func per func.
// Edge doesn't support objectStoreNames (booo), so we polyfill it here.
if (func === IDBDatabase.prototype.transaction && !('objectStoreNames' in IDBTransaction.prototype)) {
return function (storeNames, ...args) {
const tx = func.call(unwrap(this), storeNames, ...args);
transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
return wrap(tx);
};
} // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
// IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
// cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
// with real promises, so each advance methods returns a new promise for the cursor object, or
// undefined if the end of the cursor has been reached.
if (getCursorAdvanceMethods().includes(func)) {
return function (...args) {
// Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
// the original object.
func.apply(unwrap(this), args);
return wrap(cursorRequestMap.get(this));
};
}
return function (...args) {
// Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
// the original object.
return wrap(func.apply(unwrap(this), args));
};
}
function transformCachableValue(value) {
if (typeof value === 'function') return wrapFunction(value); // This doesn't return, it just creates a 'done' promise for the transaction,
// which is later returned for transaction.done (see idbObjectHandler).
if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value);
if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps); // Return the same value back if we're not going to transform it.
return value;
}
function wrap(value) {
// We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
// IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
if (value instanceof IDBRequest) return promisifyRequest(value); // If we've already transformed this value before, reuse the transformed value.
// This is faster, but it also provides object equality.
if (transformCache.has(value)) return transformCache.get(value);
const newValue = transformCachableValue(value); // Not all types are transformed.
// These may be primitive types, so they can't be WeakMap keys.
if (newValue !== value) {
transformCache.set(value, newValue);
reverseTransformCache.set(newValue, value);
}
return newValue;
}
const unwrap = value => reverseTransformCache.get(value);
/**
* Open a database.
*
* @param name Name of the database.
* @param version Schema version.
* @param callbacks Additional callbacks.
*/
function openDB(name, version, {
blocked,
upgrade,
blocking,
terminated
} = {}) {
const request = indexedDB.open(name, version);
const openPromise = wrap(request);
if (upgrade) {
request.addEventListener('upgradeneeded', event => {
upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction));
});
}
if (blocked) request.addEventListener('blocked', () => blocked());
openPromise.then(db => {
if (terminated) db.addEventListener('close', () => terminated());
if (blocking) db.addEventListener('versionchange', () => blocking());
}).catch(() => {});
return openPromise;
}
const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
const writeMethods = ['put', 'add', 'delete', 'clear'];
const cachedMethods = new Map();
function getMethod(target, prop) {
if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === 'string')) {
return;
}
if (cachedMethods.get(prop)) return cachedMethods.get(prop);
const targetFuncName = prop.replace(/FromIndex$/, '');
const useIndex = prop !== targetFuncName;
const isWrite = writeMethods.includes(targetFuncName);
if ( // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
!(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) {
return;
}
const method = async function (storeName, ...args) {
// isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
let target = tx.store;
if (useIndex) target = target.index(args.shift()); // Must reject if op rejects.
// If it's a write operation, must reject if tx.done rejects.
// Must reject with op rejection first.
// Must resolve with op value.
// Must handle both promises (no unhandled rejections)
return (await Promise.all([target[targetFuncName](...args), isWrite && tx.done]))[0];
};
cachedMethods.set(prop, method);
return method;
}
replaceTraps(oldTraps => _extends({}, oldTraps, {
get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop)
}));
/*
Copyright 2018 Google LLC
Copyright 2021 Google LLC

@@ -18,5 +292,150 @@ Use of this source code is governed by an MIT-style

const DB_NAME = 'workbox-background-sync';
const OBJECT_STORE_NAME = 'requests';
const INDEXED_PROP = 'queueName';
const REQUEST_OBJECT_STORE_NAME = 'requests';
const QUEUE_NAME_INDEX = 'queueName';
/**
* A class to interact directly an IndexedDB created specifically to save and
* retrieve QueueStoreEntries. This class encapsulates all the schema details
* to store the representation of a Queue.
*
* @private
*/
class QueueDb {
constructor() {
this._db = null;
}
/**
* Add QueueStoreEntry to underlying db.
*
* @param {UnidentifiedQueueStoreEntry} entry
*/
async addEntry(entry) {
const db = await this.getDb();
await db.add(REQUEST_OBJECT_STORE_NAME, entry);
}
/**
* Returns the first entry id in the ObjectStore.
*
* @return {number | undefined}
*/
async getFirstEntryId() {
const db = await this.getDb();
const cursor = await db.transaction(REQUEST_OBJECT_STORE_NAME).store.openCursor();
return cursor == null ? void 0 : cursor.value.id;
}
/**
* Get all the entries filtered by index
*
* @param queueName
* @return {Promise<QueueStoreEntry[]>}
*/
async getAllEntriesByQueueName(queueName) {
const db = await this.getDb();
const results = await db.getAllFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName));
return results ? results : new Array();
}
/**
* Deletes a single entry by id.
*
* @param {number} id the id of the entry to be deleted
*/
async deleteEntry(id) {
const db = await this.getDb();
await db.delete(REQUEST_OBJECT_STORE_NAME, id);
}
/**
*
* @param queueName
* @returns {Promise<QueueStoreEntry | undefined>}
*/
async getFirstEntryByQueueName(queueName) {
return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), 'next');
}
/**
*
* @param queueName
* @returns {Promise<QueueStoreEntry | undefined>}
*/
async getLastEntryByQueueName(queueName) {
return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), 'prev');
}
/**
* Returns either the first or the last entries, depending on direction.
* Filtered by index.
*
* @param {IDBCursorDirection} direction
* @param {IDBKeyRange} query
* @return {Promise<QueueStoreEntry | undefined>}
* @private
*/
async getEndEntryFromIndex(query, direction) {
const db = await this.getDb();
const cursor = await db.transaction(REQUEST_OBJECT_STORE_NAME).store.index(QUEUE_NAME_INDEX).openCursor(query, direction);
return cursor == null ? void 0 : cursor.value;
}
/**
* Returns an open connection to the database.
*
* @private
*/
async getDb() {
if (!this._db) {
this._db = await openDB(DB_NAME, DB_VERSION, {
upgrade: this._upgradeDb
});
}
return this._db;
}
/**
* Upgrades QueueDB
*
* @param {IDBPDatabase<QueueDBSchema>} db
* @param {number} oldVersion
* @private
*/
_upgradeDb(db, oldVersion) {
if (oldVersion > 0 && oldVersion < DB_VERSION) {
if (db.objectStoreNames.contains(REQUEST_OBJECT_STORE_NAME)) {
db.deleteObjectStore(REQUEST_OBJECT_STORE_NAME);
}
}
const objStore = db.createObjectStore(REQUEST_OBJECT_STORE_NAME, {
autoIncrement: true,
keyPath: 'id'
});
objStore.createIndex(QUEUE_NAME_INDEX, QUEUE_NAME_INDEX, {
unique: false
});
}
}
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
/**
* A class to manage storing requests from a Queue in IndexedDB,

@@ -38,5 +457,3 @@ * indexed by their queue name for easier access.

this._queueName = queueName;
this._db = new DBWrapper_js.DBWrapper(DB_NAME, DB_VERSION, {
onupgradeneeded: this._upgradeDb
});
this._queueDb = new QueueDb();
}

@@ -73,3 +490,3 @@ /**

entry.queueName = this._queueName;
await this._db.add(OBJECT_STORE_NAME, entry);
await this._queueDb.addEntry(entry);
}

@@ -103,9 +520,7 @@ /**

const [firstEntry] = await this._db.getAllMatching(OBJECT_STORE_NAME, {
count: 1
});
const firstId = await this._queueDb.getFirstEntryId();
if (firstEntry) {
if (firstId) {
// Pick an ID one less than the lowest ID in the object store.
entry.id = firstEntry.id - 1;
entry.id = firstId - 1;
} else {

@@ -117,3 +532,3 @@ // Otherwise let the auto-incrementor assign the ID.

entry.queueName = this._queueName;
await this._db.add(OBJECT_STORE_NAME, entry);
await this._queueDb.addEntry(entry);
}

@@ -123,3 +538,3 @@ /**

*
* @return {Promise<Object>}
* @return {Promise<QueueStoreEntry|undefined>}
* @private

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

async popEntry() {
return this._removeEntry({
direction: 'prev'
});
return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName));
}

@@ -138,3 +551,3 @@ /**

*
* @return {Promise<Object>}
* @return {Promise<QueueStoreEntry|undefined>}
* @private

@@ -145,5 +558,3 @@ */

async shiftEntry() {
return this._removeEntry({
direction: 'next'
});
return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName));
}

@@ -160,6 +571,3 @@ /**

async getAll() {
return await this._db.getAllMatching(OBJECT_STORE_NAME, {
index: INDEXED_PROP,
query: IDBKeyRange.only(this._queueName)
});
return await this._queueDb.getAllEntriesByQueueName(this._queueName);
}

@@ -169,3 +577,3 @@ /**

*
* WARNING: this method does not ensure the deleted enry belongs to this
* WARNING: this method does not ensure the deleted entry belongs to this
* queue (i.e. matches the `queueName`). But this limitation is acceptable

@@ -181,3 +589,3 @@ * as this class is not publicly exposed. An additional check would make

async deleteEntry(id) {
await this._db.delete(OBJECT_STORE_NAME, id);
await this._queueDb.deleteEntry(id);
}

@@ -188,3 +596,3 @@ /**

*
* @return {Promise<Object>}
* @return {Promise<QueueStoreEntry|undefined>}
* @private

@@ -194,41 +602,8 @@ */

async _removeEntry({
direction
}) {
const [entry] = await this._db.getAllMatching(OBJECT_STORE_NAME, {
direction,
index: INDEXED_PROP,
query: IDBKeyRange.only(this._queueName),
count: 1
});
async _removeEntry(entry) {
if (entry) {
await this.deleteEntry(entry.id);
return entry;
}
}
/**
* Upgrades the database given an `upgradeneeded` event.
*
* @param {Event} event
* @private
*/
_upgradeDb(event) {
const db = event.target.result;
if (event.oldVersion > 0 && event.oldVersion < DB_VERSION) {
if (db.objectStoreNames.contains(OBJECT_STORE_NAME)) {
db.deleteObjectStore(OBJECT_STORE_NAME);
}
}
const objStore = db.createObjectStore(OBJECT_STORE_NAME, {
autoIncrement: true,
keyPath: 'id'
});
objStore.createIndex(INDEXED_PROP, INDEXED_PROP, {
unique: false
});
return entry;
}

@@ -388,4 +763,4 @@

*
* @param {Object} queueStoreEntry
* @return {Object}
* @param {UnidentifiedQueueStoreEntry} queueStoreEntry
* @return {Queue}
* @private

@@ -469,3 +844,3 @@ */

*
* @param {Object} entry
* @param {QueueEntry} entry
* @param {Request} entry.request The request to store in the queue.

@@ -506,3 +881,3 @@ * @param {Object} [entry.metadata] Any metadata you want associated with the

*
* @param {Object} entry
* @param {QueueEntry} entry
* @param {Request} entry.request The request to store in the queue.

@@ -544,3 +919,3 @@ * @param {Object} [entry.metadata] Any metadata you want associated with the

*
* @return {Promise<Object>}
* @return {Promise<QueueEntry | undefined>}
*/

@@ -557,3 +932,3 @@

*
* @return {Promise<Object>}
* @return {Promise<QueueEntry | undefined>}
*/

@@ -569,3 +944,3 @@

*
* @return {Promise<Array<Object>>}
* @return {Promise<Array<QueueEntry>>}
*/

@@ -741,6 +1116,8 @@

} catch (error) {
syncError = error; // Rethrow the error. Note: the logic in the finally clause
// will run before this gets rethrown.
if (error instanceof Error) {
syncError = error; // Rethrow the error. Note: the logic in the finally clause
// will run before this gets rethrown.
throw syncError;
throw syncError;
}
} finally {

@@ -771,3 +1148,3 @@ // New items may have been added to the queue during the sync,

this._onSync({
void this._onSync({
queue: this

@@ -781,3 +1158,3 @@ });

*
* @return {Set}
* @return {Set<string>}
*

@@ -840,3 +1217,3 @@ * @private

}({}, workbox.core._private, 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-background-sync.dev.js.map

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

this.workbox=this.workbox||{},this.workbox.backgroundSync=function(t,e,s,i,n){"use strict";try{self["workbox:background-sync:6.1.5"]&&_()}catch(t){}const a="requests",r="queueName";class c{constructor(t){this.t=t,this.i=new n.DBWrapper("workbox-background-sync",3,{onupgradeneeded:this.h})}async pushEntry(t){delete t.id,t.queueName=this.t,await this.i.add(a,t)}async unshiftEntry(t){const[e]=await this.i.getAllMatching(a,{count:1});e?t.id=e.id-1:delete t.id,t.queueName=this.t,await this.i.add(a,t)}async popEntry(){return this.o({direction:"prev"})}async shiftEntry(){return this.o({direction:"next"})}async getAll(){return await this.i.getAllMatching(a,{index:r,query:IDBKeyRange.only(this.t)})}async deleteEntry(t){await this.i.delete(a,t)}async o({direction:t}){const[e]=await this.i.getAllMatching(a,{direction:t,index:r,query:IDBKeyRange.only(this.t),count:1});if(e)return await this.deleteEntry(e.id),e}h(t){const e=t.target.result;t.oldVersion>0&&t.oldVersion<3&&e.objectStoreNames.contains(a)&&e.deleteObjectStore(a);e.createObjectStore(a,{autoIncrement:!0,keyPath:"id"}).createIndex(r,r,{unique:!1})}}const h=["method","referrer","referrerPolicy","mode","credentials","cache","redirect","integrity","keepalive"];class o{constructor(t){"navigate"===t.mode&&(t.mode="same-origin"),this.u=t}static async fromRequest(t){const e={url:t.url,headers:{}};"GET"!==t.method&&(e.body=await t.clone().arrayBuffer());for(const[s,i]of t.headers.entries())e.headers[s]=i;for(const s of h)void 0!==t[s]&&(e[s]=t[s]);return new o(e)}toObject(){const t=Object.assign({},this.u);return t.headers=Object.assign({},this.u.headers),t.body&&(t.body=t.body.slice(0)),t}toRequest(){return new Request(this.u.url,this.u)}clone(){return new o(this.toObject())}}const u="workbox-background-sync",y=new Set,w=t=>{const e={request:new o(t.requestData).toRequest(),timestamp:t.timestamp};return t.metadata&&(e.metadata=t.metadata),e};class f{constructor(t,{onSync:s,maxRetentionTime:i}={}){if(this.l=!1,this.q=!1,y.has(t))throw new e.WorkboxError("duplicate-queue-name",{name:t});y.add(t),this.m=t,this.p=s||this.replayRequests,this.g=i||10080,this.R=new c(this.m),this.k()}get name(){return this.m}async pushRequest(t){await this.D(t,"push")}async unshiftRequest(t){await this.D(t,"unshift")}async popRequest(){return this._("pop")}async shiftRequest(){return this._("shift")}async getAll(){const t=await this.R.getAll(),e=Date.now(),s=[];for(const i of t){const t=60*this.g*1e3;e-i.timestamp>t?await this.R.deleteEntry(i.id):s.push(w(i))}return s}async D({request:t,metadata:e,timestamp:s=Date.now()},i){const n={requestData:(await o.fromRequest(t.clone())).toObject(),timestamp:s};e&&(n.metadata=e),await this.R[i+"Entry"](n),this.l?this.q=!0:await this.registerSync()}async _(t){const e=Date.now(),s=await this.R[t+"Entry"]();if(s){const i=60*this.g*1e3;return e-s.timestamp>i?this._(t):w(s)}}async replayRequests(){let t;for(;t=await this.shiftRequest();)try{await fetch(t.request.clone())}catch(s){throw await this.unshiftRequest(t),new e.WorkboxError("queue-replay-failed",{name:this.m})}}async registerSync(){if("sync"in self.registration)try{await self.registration.sync.register(`${u}:${this.m}`)}catch(t){}}k(){"sync"in self.registration?self.addEventListener("sync",(t=>{if(t.tag===`${u}:${this.m}`){const e=async()=>{let e;this.l=!0;try{await this.p({queue:this})}catch(t){throw e=t,e}finally{!this.q||e&&!t.lastChance||await this.registerSync(),this.l=!1,this.q=!1}};t.waitUntil(e())}})):this.p({queue:this})}static get v(){return y}}return t.BackgroundSyncPlugin=class{constructor(t,e){this.fetchDidFail=async({request:t})=>{await this.S.pushRequest({request:t})},this.S=new f(t,e)}},t.Queue=f,t}({},workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private);
this.workbox=this.workbox||{},this.workbox.backgroundSync=function(t,e,n,s){"use strict";try{self["workbox:background-sync:6.2.0-alpha.0"]&&_()}catch(t){}function r(){return(r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t}).apply(this,arguments)}let i,a;const o=new WeakMap,c=new WeakMap,u=new WeakMap,h=new WeakMap,y=new WeakMap;let w={get(t,e,n){if(t instanceof IDBTransaction){if("done"===e)return c.get(t);if("objectStoreNames"===e)return t.objectStoreNames||u.get(t);if("store"===e)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return d(t[e])},set:(t,e,n)=>(t[e]=n,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function f(t){return t!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(a||(a=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(m(this),e),d(o.get(this))}:function(...e){return d(t.apply(m(this),e))}:function(e,...n){const s=t.call(m(this),e,...n);return u.set(s,e.sort?e.sort():[e]),d(s)}}function l(t){return"function"==typeof t?f(t):(t instanceof IDBTransaction&&function(t){if(c.has(t))return;const e=new Promise(((e,n)=>{const s=()=>{t.removeEventListener("complete",r),t.removeEventListener("error",i),t.removeEventListener("abort",i)},r=()=>{e(),s()},i=()=>{n(t.error||new DOMException("AbortError","AbortError")),s()};t.addEventListener("complete",r),t.addEventListener("error",i),t.addEventListener("abort",i)}));c.set(t,e)}(t),e=t,(i||(i=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some((t=>e instanceof t))?new Proxy(t,w):t);var e}function d(t){if(t instanceof IDBRequest)return function(t){const e=new Promise(((e,n)=>{const s=()=>{t.removeEventListener("success",r),t.removeEventListener("error",i)},r=()=>{e(d(t.result)),s()},i=()=>{n(t.error),s()};t.addEventListener("success",r),t.addEventListener("error",i)}));return e.then((e=>{e instanceof IDBCursor&&o.set(e,t)})).catch((()=>{})),y.set(e,t),e}(t);if(h.has(t))return h.get(t);const e=l(t);return e!==t&&(h.set(t,e),y.set(e,t)),e}const m=t=>y.get(t);const p=["get","getKey","getAll","getAllKeys","count"],g=["put","add","delete","clear"],D=new Map;function b(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(D.get(e))return D.get(e);const n=e.replace(/FromIndex$/,""),s=e!==n,r=g.includes(n);if(!(n in(s?IDBIndex:IDBObjectStore).prototype)||!r&&!p.includes(n))return;const i=async function(t,...e){const i=this.transaction(t,r?"readwrite":"readonly");let a=i.store;return s&&(a=a.index(e.shift())),(await Promise.all([a[n](...e),r&&i.done]))[0]};return D.set(e,i),i}w=(t=>r({},t,{get:(e,n,s)=>b(e,n)||t.get(e,n,s),has:(e,n)=>!!b(e,n)||t.has(e,n)}))(w);const I="requests",B="queueName";class q{constructor(){this.t=null}async addEntry(t){const e=await this.getDb();await e.add(I,t)}async getFirstEntryId(){const t=await this.getDb(),e=await t.transaction(I).store.openCursor();return null==e?void 0:e.value.id}async getAllEntriesByQueueName(t){const e=await this.getDb(),n=await e.getAllFromIndex(I,B,IDBKeyRange.only(t));return n||new Array}async deleteEntry(t){const e=await this.getDb();await e.delete(I,t)}async getFirstEntryByQueueName(t){return await this.getEndEntryFromIndex(IDBKeyRange.only(t),"next")}async getLastEntryByQueueName(t){return await this.getEndEntryFromIndex(IDBKeyRange.only(t),"prev")}async getEndEntryFromIndex(t,e){const n=await this.getDb(),s=await n.transaction(I).store.index(B).openCursor(t,e);return null==s?void 0:s.value}async getDb(){return this.t||(this.t=await function(t,e,{blocked:n,upgrade:s,blocking:r,terminated:i}={}){const a=indexedDB.open(t,e),o=d(a);return s&&a.addEventListener("upgradeneeded",(t=>{s(d(a.result),t.oldVersion,t.newVersion,d(a.transaction))})),n&&a.addEventListener("blocked",(()=>n())),o.then((t=>{i&&t.addEventListener("close",(()=>i())),r&&t.addEventListener("versionchange",(()=>r()))})).catch((()=>{})),o}("workbox-background-sync",3,{upgrade:this.i})),this.t}i(t,e){e>0&&e<3&&t.objectStoreNames.contains(I)&&t.deleteObjectStore(I);t.createObjectStore(I,{autoIncrement:!0,keyPath:"id"}).createIndex(B,B,{unique:!1})}}class E{constructor(t){this.o=t,this.u=new q}async pushEntry(t){delete t.id,t.queueName=this.o,await this.u.addEntry(t)}async unshiftEntry(t){const e=await this.u.getFirstEntryId();e?t.id=e-1:delete t.id,t.queueName=this.o,await this.u.addEntry(t)}async popEntry(){return this.h(await this.u.getLastEntryByQueueName(this.o))}async shiftEntry(){return this.h(await this.u.getFirstEntryByQueueName(this.o))}async getAll(){return await this.u.getAllEntriesByQueueName(this.o)}async deleteEntry(t){await this.u.deleteEntry(t)}async h(t){return t&&await this.deleteEntry(t.id),t}}const k=["method","referrer","referrerPolicy","mode","credentials","cache","redirect","integrity","keepalive"];class R{constructor(t){"navigate"===t.mode&&(t.mode="same-origin"),this.l=t}static async fromRequest(t){const e={url:t.url,headers:{}};"GET"!==t.method&&(e.body=await t.clone().arrayBuffer());for(const[n,s]of t.headers.entries())e.headers[n]=s;for(const n of k)void 0!==t[n]&&(e[n]=t[n]);return new R(e)}toObject(){const t=Object.assign({},this.l);return t.headers=Object.assign({},this.l.headers),t.body&&(t.body=t.body.slice(0)),t}toRequest(){return new Request(this.l.url,this.l)}clone(){return new R(this.toObject())}}const v="workbox-background-sync",x=new Set,j=t=>{const e={request:new R(t.requestData).toRequest(),timestamp:t.timestamp};return t.metadata&&(e.metadata=t.metadata),e};class A{constructor(t,{onSync:n,maxRetentionTime:s}={}){if(this.m=!1,this.p=!1,x.has(t))throw new e.WorkboxError("duplicate-queue-name",{name:t});x.add(t),this.g=t,this.D=n||this.replayRequests,this.I=s||10080,this.B=new E(this.g),this.q()}get name(){return this.g}async pushRequest(t){await this.k(t,"push")}async unshiftRequest(t){await this.k(t,"unshift")}async popRequest(){return this.R("pop")}async shiftRequest(){return this.R("shift")}async getAll(){const t=await this.B.getAll(),e=Date.now(),n=[];for(const s of t){const t=60*this.I*1e3;e-s.timestamp>t?await this.B.deleteEntry(s.id):n.push(j(s))}return n}async k({request:t,metadata:e,timestamp:n=Date.now()},s){const r={requestData:(await R.fromRequest(t.clone())).toObject(),timestamp:n};e&&(r.metadata=e),await this.B[s+"Entry"](r),this.m?this.p=!0:await this.registerSync()}async R(t){const e=Date.now(),n=await this.B[t+"Entry"]();if(n){const s=60*this.I*1e3;return e-n.timestamp>s?this.R(t):j(n)}}async replayRequests(){let t;for(;t=await this.shiftRequest();)try{await fetch(t.request.clone())}catch(n){throw await this.unshiftRequest(t),new e.WorkboxError("queue-replay-failed",{name:this.g})}}async registerSync(){if("sync"in self.registration)try{await self.registration.sync.register(`${v}:${this.g}`)}catch(t){}}q(){"sync"in self.registration?self.addEventListener("sync",(t=>{if(t.tag===`${v}:${this.g}`){const e=async()=>{let e;this.m=!0;try{await this.D({queue:this})}catch(t){if(t instanceof Error)throw e=t,e}finally{!this.p||e&&!t.lastChance||await this.registerSync(),this.m=!1,this.p=!1}};t.waitUntil(e())}})):this.D({queue:this})}static get v(){return x}}return t.BackgroundSyncPlugin=class{constructor(t,e){this.fetchDidFail=async({request:t})=>{await this.j.pushRequest({request:t})},this.j=new A(t,e)}},t.Queue=A,t}({},workbox.core._private,workbox.core._private,workbox.core._private);
//# sourceMappingURL=workbox-background-sync.prod.js.map

@@ -1,13 +0,3 @@

import { RequestData } from './StorableRequest.js';
import '../_version.js';
export interface UnidentifiedQueueStoreEntry {
requestData: RequestData;
timestamp: number;
id?: number;
queueName?: string;
metadata?: object;
}
export interface QueueStoreEntry extends UnidentifiedQueueStoreEntry {
id: number;
}
import { UnidentifiedQueueStoreEntry, QueueStoreEntry } from './QueueDb.js';
/**

@@ -21,3 +11,3 @@ * A class to manage storing requests from a Queue in IndexedDB,

private readonly _queueName;
private readonly _db;
private readonly _queueDb;
/**

@@ -54,13 +44,13 @@ * Associates this instance with a Queue instance, so entries added can be

*
* @return {Promise<Object>}
* @return {Promise<QueueStoreEntry|undefined>}
* @private
*/
popEntry(): Promise<QueueStoreEntry>;
popEntry(): Promise<QueueStoreEntry | undefined>;
/**
* Removes and returns the first entry in the queue matching the `queueName`.
*
* @return {Promise<Object>}
* @return {Promise<QueueStoreEntry|undefined>}
* @private
*/
shiftEntry(): Promise<QueueStoreEntry>;
shiftEntry(): Promise<QueueStoreEntry | undefined>;
/**

@@ -77,3 +67,3 @@ * Returns all entries in the store matching the `queueName`.

*
* WARNING: this method does not ensure the deleted enry belongs to this
* WARNING: this method does not ensure the deleted entry belongs to this
* queue (i.e. matches the `queueName`). But this limitation is acceptable

@@ -91,15 +81,6 @@ * as this class is not publicly exposed. An additional check would make

*
* @return {Promise<Object>}
* @return {Promise<QueueStoreEntry|undefined>}
* @private
*/
_removeEntry({ direction }: {
direction?: IDBCursorDirection;
}): Promise<any>;
/**
* Upgrades the database given an `upgradeneeded` event.
*
* @param {Event} event
* @private
*/
private _upgradeDb;
_removeEntry(entry?: QueueStoreEntry): Promise<QueueStoreEntry | undefined>;
}

@@ -9,8 +9,4 @@ /*

import { assert } from 'workbox-core/_private/assert.js';
import { DBWrapper } from 'workbox-core/_private/DBWrapper.js';
import '../_version.js';
const DB_VERSION = 3;
const DB_NAME = 'workbox-background-sync';
const OBJECT_STORE_NAME = 'requests';
const INDEXED_PROP = 'queueName';
import { QueueDb } from './QueueDb.js';
/**

@@ -32,5 +28,3 @@ * A class to manage storing requests from a Queue in IndexedDB,

this._queueName = queueName;
this._db = new DBWrapper(DB_NAME, DB_VERSION, {
onupgradeneeded: this._upgradeDb,
});
this._queueDb = new QueueDb();
}

@@ -64,3 +58,3 @@ /**

entry.queueName = this._queueName;
await this._db.add(OBJECT_STORE_NAME, entry);
await this._queueDb.addEntry(entry);
}

@@ -91,8 +85,6 @@ /**

}
const [firstEntry] = await this._db.getAllMatching(OBJECT_STORE_NAME, {
count: 1,
});
if (firstEntry) {
const firstId = await this._queueDb.getFirstEntryId();
if (firstId) {
// Pick an ID one less than the lowest ID in the object store.
entry.id = firstEntry.id - 1;
entry.id = firstId - 1;
}

@@ -104,3 +96,3 @@ else {

entry.queueName = this._queueName;
await this._db.add(OBJECT_STORE_NAME, entry);
await this._queueDb.addEntry(entry);
}

@@ -110,7 +102,7 @@ /**

*
* @return {Promise<Object>}
* @return {Promise<QueueStoreEntry|undefined>}
* @private
*/
async popEntry() {
return this._removeEntry({ direction: 'prev' });
return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName));
}

@@ -120,7 +112,7 @@ /**

*
* @return {Promise<Object>}
* @return {Promise<QueueStoreEntry|undefined>}
* @private
*/
async shiftEntry() {
return this._removeEntry({ direction: 'next' });
return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName));
}

@@ -135,6 +127,3 @@ /**

async getAll() {
return await this._db.getAllMatching(OBJECT_STORE_NAME, {
index: INDEXED_PROP,
query: IDBKeyRange.only(this._queueName),
});
return await this._queueDb.getAllEntriesByQueueName(this._queueName);
}

@@ -144,3 +133,3 @@ /**

*
* WARNING: this method does not ensure the deleted enry belongs to this
* WARNING: this method does not ensure the deleted entry belongs to this
* queue (i.e. matches the `queueName`). But this limitation is acceptable

@@ -154,3 +143,3 @@ * as this class is not publicly exposed. An additional check would make

async deleteEntry(id) {
await this._db.delete(OBJECT_STORE_NAME, id);
await this._queueDb.deleteEntry(id);
}

@@ -161,36 +150,11 @@ /**

*
* @return {Promise<Object>}
* @return {Promise<QueueStoreEntry|undefined>}
* @private
*/
async _removeEntry({ direction }) {
const [entry] = await this._db.getAllMatching(OBJECT_STORE_NAME, {
direction,
index: INDEXED_PROP,
query: IDBKeyRange.only(this._queueName),
count: 1,
});
async _removeEntry(entry) {
if (entry) {
await this.deleteEntry(entry.id);
return entry;
}
return entry;
}
/**
* Upgrades the database given an `upgradeneeded` event.
*
* @param {Event} event
* @private
*/
_upgradeDb(event) {
const db = event.target.result;
if (event.oldVersion > 0 && event.oldVersion < DB_VERSION) {
if (db.objectStoreNames.contains(OBJECT_STORE_NAME)) {
db.deleteObjectStore(OBJECT_STORE_NAME);
}
}
const objStore = db.createObjectStore(OBJECT_STORE_NAME, {
autoIncrement: true,
keyPath: 'id',
});
objStore.createIndex(INDEXED_PROP, INDEXED_PROP, { unique: false });
}
}
{
"name": "workbox-background-sync",
"version": "6.1.5",
"version": "6.2.0-alpha.0",
"license": "MIT",

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

"dependencies": {
"workbox-core": "^6.1.5"
"idb": "^6.0.0",
"workbox-core": "^6.2.0-alpha.0"
},
"gitHead": "d559fc8b3240f723fd9721f3976797dcedf7112b"
"gitHead": "46af63c1780955345c117c63c8c8dd54f3d40220"
}

@@ -59,3 +59,3 @@ import './_version.js';

*
* @param {Object} entry
* @param {QueueEntry} entry
* @param {Request} entry.request The request to store in the queue.

@@ -77,3 +77,3 @@ * @param {Object} [entry.metadata] Any metadata you want associated with the

*
* @param {Object} entry
* @param {QueueEntry} entry
* @param {Request} entry.request The request to store in the queue.

@@ -96,3 +96,3 @@ * @param {Object} [entry.metadata] Any metadata you want associated with the

*
* @return {Promise<Object>}
* @return {Promise<QueueEntry | undefined>}
*/

@@ -105,3 +105,3 @@ popRequest(): Promise<QueueEntry | undefined>;

*
* @return {Promise<Object>}
* @return {Promise<QueueEntry | undefined>}
*/

@@ -113,5 +113,5 @@ shiftRequest(): Promise<QueueEntry | undefined>;

*
* @return {Promise<Array<Object>>}
* @return {Promise<Array<QueueEntry>>}
*/
getAll(): Promise<QueueEntry[]>;
getAll(): Promise<Array<QueueEntry>>;
/**

@@ -159,8 +159,8 @@ * Adds the entry to the QueueStore and registers for a sync event.

*
* @return {Set}
* @return {Set<string>}
*
* @private
*/
static get _queueNames(): Set<unknown>;
static get _queueNames(): Set<string>;
}
export { Queue };

@@ -23,4 +23,4 @@ /*

*
* @param {Object} queueStoreEntry
* @return {Object}
* @param {UnidentifiedQueueStoreEntry} queueStoreEntry
* @return {Queue}
* @private

@@ -91,3 +91,3 @@ */

*
* @param {Object} entry
* @param {QueueEntry} entry
* @param {Request} entry.request The request to store in the queue.

@@ -125,3 +125,3 @@ * @param {Object} [entry.metadata] Any metadata you want associated with the

*
* @param {Object} entry
* @param {QueueEntry} entry
* @param {Request} entry.request The request to store in the queue.

@@ -160,3 +160,3 @@ * @param {Object} [entry.metadata] Any metadata you want associated with the

*
* @return {Promise<Object>}
* @return {Promise<QueueEntry | undefined>}
*/

@@ -171,3 +171,3 @@ async popRequest() {

*
* @return {Promise<Object>}
* @return {Promise<QueueEntry | undefined>}
*/

@@ -181,3 +181,3 @@ async shiftRequest() {

*
* @return {Promise<Array<Object>>}
* @return {Promise<Array<QueueEntry>>}
*/

@@ -328,6 +328,8 @@ async getAll() {

catch (error) {
syncError = error;
// Rethrow the error. Note: the logic in the finally clause
// will run before this gets rethrown.
throw syncError;
if (error instanceof Error) {
syncError = error;
// Rethrow the error. Note: the logic in the finally clause
// will run before this gets rethrown.
throw syncError;
}
}

@@ -358,3 +360,3 @@ finally {

// every time the service worker starts up as a fallback.
this._onSync({ queue: this });
void this._onSync({ queue: this });
}

@@ -366,3 +368,3 @@ }

*
* @return {Set}
* @return {Set<string>}
*

@@ -369,0 +371,0 @@ * @private

// @ts-ignore
try{self['workbox:background-sync:6.1.5']&&_()}catch(e){}
try{self['workbox:background-sync:6.2.0-alpha.0']&&_()}catch(e){}

@@ -10,24 +10,5 @@ /*

import {assert} from 'workbox-core/_private/assert.js';
import {DBWrapper} from 'workbox-core/_private/DBWrapper.js';
import {RequestData} from './StorableRequest.js';
import '../_version.js';
import {UnidentifiedQueueStoreEntry, QueueStoreEntry, QueueDb} from './QueueDb.js';
const DB_VERSION = 3;
const DB_NAME = 'workbox-background-sync';
const OBJECT_STORE_NAME = 'requests';
const INDEXED_PROP = 'queueName';
export interface UnidentifiedQueueStoreEntry {
requestData: RequestData;
timestamp: number;
id?: number;
queueName?: string;
metadata?: object;
}
export interface QueueStoreEntry extends UnidentifiedQueueStoreEntry {
id: number;
}
/**

@@ -41,3 +22,3 @@ * A class to manage storing requests from a Queue in IndexedDB,

private readonly _queueName: string;
private readonly _db: DBWrapper;
private readonly _queueDb: QueueDb;

@@ -53,5 +34,3 @@ /**

this._queueName = queueName;
this._db = new DBWrapper(DB_NAME, DB_VERSION, {
onupgradeneeded: this._upgradeDb,
});
this._queueDb = new QueueDb();
}

@@ -68,3 +47,3 @@

*/
async pushEntry(entry: UnidentifiedQueueStoreEntry) {
async pushEntry(entry: UnidentifiedQueueStoreEntry): Promise<void> {
if (process.env.NODE_ENV !== 'production') {

@@ -89,3 +68,3 @@ assert!.isType(entry, 'object', {

await this._db.add!(OBJECT_STORE_NAME, entry);
await this._queueDb.addEntry(entry);
}

@@ -102,3 +81,3 @@

*/
async unshiftEntry(entry: UnidentifiedQueueStoreEntry) {
async unshiftEntry(entry: UnidentifiedQueueStoreEntry): Promise<void> {
if (process.env.NODE_ENV !== 'production') {

@@ -119,9 +98,7 @@ assert!.isType(entry, 'object', {

const [firstEntry] = await this._db.getAllMatching(OBJECT_STORE_NAME, {
count: 1,
});
const firstId = await this._queueDb.getFirstEntryId();
if (firstEntry) {
if (firstId) {
// Pick an ID one less than the lowest ID in the object store.
entry.id = firstEntry.id - 1;
entry.id = firstId - 1;
} else {

@@ -133,3 +110,3 @@ // Otherwise let the auto-incrementor assign the ID.

await this._db.add!(OBJECT_STORE_NAME, entry);
await this._queueDb.addEntry(entry);
}

@@ -140,7 +117,7 @@

*
* @return {Promise<Object>}
* @return {Promise<QueueStoreEntry|undefined>}
* @private
*/
async popEntry(): Promise<QueueStoreEntry> {
return this._removeEntry({direction: 'prev'});
async popEntry(): Promise<QueueStoreEntry | undefined> {
return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName));
}

@@ -151,7 +128,7 @@

*
* @return {Promise<Object>}
* @return {Promise<QueueStoreEntry|undefined>}
* @private
*/
async shiftEntry(): Promise<QueueStoreEntry> {
return this._removeEntry({direction: 'next'});
async shiftEntry(): Promise<QueueStoreEntry | undefined> {
return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName));
}

@@ -167,6 +144,3 @@

async getAll(): Promise<QueueStoreEntry[]> {
return await this._db.getAllMatching(OBJECT_STORE_NAME, {
index: INDEXED_PROP,
query: IDBKeyRange.only(this._queueName),
});
return await this._queueDb.getAllEntriesByQueueName(this._queueName);
}

@@ -177,3 +151,3 @@

*
* WARNING: this method does not ensure the deleted enry belongs to this
* WARNING: this method does not ensure the deleted entry belongs to this
* queue (i.e. matches the `queueName`). But this limitation is acceptable

@@ -186,4 +160,4 @@ * as this class is not publicly exposed. An additional check would make

*/
async deleteEntry(id: number) {
await this._db.delete!(OBJECT_STORE_NAME, id);
async deleteEntry(id: number): Promise<void> {
await this._queueDb.deleteEntry(id);
}

@@ -195,40 +169,11 @@

*
* @return {Promise<Object>}
* @return {Promise<QueueStoreEntry|undefined>}
* @private
*/
async _removeEntry({direction}: {direction?: IDBCursorDirection}) {
const [entry] = await this._db.getAllMatching(OBJECT_STORE_NAME, {
direction,
index: INDEXED_PROP,
query: IDBKeyRange.only(this._queueName),
count: 1,
});
async _removeEntry(entry?: QueueStoreEntry): Promise<QueueStoreEntry | undefined> {
if (entry) {
await this.deleteEntry(entry.id);
return entry;
}
return entry;
}
/**
* Upgrades the database given an `upgradeneeded` event.
*
* @param {Event} event
* @private
*/
private _upgradeDb(event: IDBVersionChangeEvent) {
const db = (event.target as IDBOpenDBRequest).result;
if (event.oldVersion > 0 && event.oldVersion < DB_VERSION) {
if (db.objectStoreNames.contains(OBJECT_STORE_NAME)) {
db.deleteObjectStore(OBJECT_STORE_NAME);
}
}
const objStore = db.createObjectStore(OBJECT_STORE_NAME, {
autoIncrement: true,
keyPath: 'id',
});
objStore.createIndex(INDEXED_PROP, INDEXED_PROP, {unique: false});
}
}

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

import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js';
import {UnidentifiedQueueStoreEntry, QueueStore} from './lib/QueueStore.js';
import {QueueStore} from './lib/QueueStore.js';
import {UnidentifiedQueueStoreEntry} from './lib/QueueDb.js';
import {StorableRequest} from './lib/StorableRequest.js';
import './_version.js';
// Give TypeScript the correct global.

@@ -38,2 +38,5 @@ declare let self: ServiceWorkerGlobalScope;

timestamp?: number;
// We could use Record<string, unknown> as a type but that would be a breaking
// change, better do it in next major release.
// eslint-disable-next-line @typescript-eslint/ban-types
metadata?: object;

@@ -45,3 +48,3 @@ }

const queueNames = new Set();
const queueNames = new Set<string>();

@@ -53,4 +56,4 @@ /**

*
* @param {Object} queueStoreEntry
* @return {Object}
* @param {UnidentifiedQueueStoreEntry} queueStoreEntry
* @return {Queue}
* @private

@@ -125,3 +128,3 @@ */

*/
get name() {
get name(): string {
return this._name;

@@ -134,3 +137,3 @@ }

*
* @param {Object} entry
* @param {QueueEntry} entry
* @param {Request} entry.request The request to store in the queue.

@@ -147,3 +150,3 @@ * @param {Object} [entry.metadata] Any metadata you want associated with the

*/
async pushRequest(entry: QueueEntry) {
async pushRequest(entry: QueueEntry): Promise<void> {
if (process.env.NODE_ENV !== 'production') {

@@ -171,3 +174,3 @@ assert!.isType(entry, 'object', {

*
* @param {Object} entry
* @param {QueueEntry} entry
* @param {Request} entry.request The request to store in the queue.

@@ -184,3 +187,3 @@ * @param {Object} [entry.metadata] Any metadata you want associated with the

*/
async unshiftRequest(entry: QueueEntry) {
async unshiftRequest(entry: QueueEntry): Promise<void> {
if (process.env.NODE_ENV !== 'production') {

@@ -209,5 +212,5 @@ assert!.isType(entry, 'object', {

*
* @return {Promise<Object>}
* @return {Promise<QueueEntry | undefined>}
*/
async popRequest() {
async popRequest(): Promise<QueueEntry | undefined> {
return this._removeRequest('pop');

@@ -221,5 +224,5 @@ }

*
* @return {Promise<Object>}
* @return {Promise<QueueEntry | undefined>}
*/
async shiftRequest() {
async shiftRequest(): Promise<QueueEntry | undefined> {
return this._removeRequest('shift');

@@ -232,5 +235,5 @@ }

*
* @return {Promise<Array<Object>>}
* @return {Promise<Array<QueueEntry>>}
*/
async getAll() {
async getAll(): Promise<Array<QueueEntry>> {
const allEntries = await this._queueStore.getAll();

@@ -254,3 +257,2 @@ const now = Date.now();

/**

@@ -270,3 +272,3 @@ * Adds the entry to the QueueStore and registers for a sync event.

timestamp = Date.now(),
}: QueueEntry, operation: 'push' | 'unshift') {
}: QueueEntry, operation: 'push' | 'unshift'): Promise<void> {
const storableRequest = await StorableRequest.fromRequest(request.clone());

@@ -333,3 +335,3 @@ const entry: UnidentifiedQueueStoreEntry = {

*/
async replayRequests() {
async replayRequests(): Promise<void> {
let entry;

@@ -363,3 +365,3 @@ while ((entry = await this.shiftRequest())) {

*/
async registerSync() {
async registerSync(): Promise<void> {
if ('sync' in self.registration) {

@@ -402,7 +404,9 @@ try {

} catch (error) {
syncError = error;
if (error instanceof Error) {
syncError = error;
// Rethrow the error. Note: the logic in the finally clause
// will run before this gets rethrown.
throw syncError;
// Rethrow the error. Note: the logic in the finally clause
// will run before this gets rethrown.
throw syncError;
}
} finally {

@@ -432,3 +436,3 @@ // New items may have been added to the queue during the sync,

// every time the service worker starts up as a fallback.
this._onSync({queue: this});
void this._onSync({queue: this});
}

@@ -441,7 +445,7 @@ }

*
* @return {Set}
* @return {Set<string>}
*
* @private
*/
static get _queueNames() {
static get _queueNames(): Set<string> {
return queueNames;

@@ -448,0 +452,0 @@ }

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