This commit is contained in:
Iliyan Angelov
2025-09-14 23:24:25 +03:00
commit c67067a2a4
71311 changed files with 6800714 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
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;
}
/**
* 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
*/
export declare class QueueDb {
private _db;
/**
* Add QueueStoreEntry to underlying db.
*
* @param {UnidentifiedQueueStoreEntry} entry
*/
addEntry(entry: UnidentifiedQueueStoreEntry): Promise<void>;
/**
* Returns the first entry id in the ObjectStore.
*
* @return {number | undefined}
*/
getFirstEntryId(): Promise<number | undefined>;
/**
* Get all the entries filtered by index
*
* @param queueName
* @return {Promise<QueueStoreEntry[]>}
*/
getAllEntriesByQueueName(queueName: string): Promise<QueueStoreEntry[]>;
/**
* Returns the number of entries filtered by index
*
* @param queueName
* @return {Promise<number>}
*/
getEntryCountByQueueName(queueName: string): Promise<number>;
/**
* Deletes a single entry by id.
*
* @param {number} id the id of the entry to be deleted
*/
deleteEntry(id: number): Promise<void>;
/**
*
* @param queueName
* @returns {Promise<QueueStoreEntry | undefined>}
*/
getFirstEntryByQueueName(queueName: string): Promise<QueueStoreEntry | undefined>;
/**
*
* @param queueName
* @returns {Promise<QueueStoreEntry | undefined>}
*/
getLastEntryByQueueName(queueName: string): Promise<QueueStoreEntry | undefined>;
/**
* 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
*/
getEndEntryFromIndex(query: IDBKeyRange, direction: IDBCursorDirection): Promise<QueueStoreEntry | undefined>;
/**
* Returns an open connection to the database.
*
* @private
*/
private getDb;
/**
* Upgrades QueueDB
*
* @param {IDBPDatabase<QueueDBSchema>} db
* @param {number} oldVersion
* @private
*/
private _upgradeDb;
}

View File

@@ -0,0 +1,145 @@
/*
Copyright 2021 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.
*/
import { openDB } from 'idb';
import '../_version.js';
const DB_VERSION = 3;
const DB_NAME = 'workbox-background-sync';
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
*/
export class QueueDb {
constructor() {
this._db = null;
}
/**
* Add QueueStoreEntry to underlying db.
*
* @param {UnidentifiedQueueStoreEntry} entry
*/
async addEntry(entry) {
const db = await this.getDb();
const tx = db.transaction(REQUEST_OBJECT_STORE_NAME, 'readwrite', {
durability: 'relaxed',
});
await tx.store.add(entry);
await tx.done;
}
/**
* 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 || cursor === void 0 ? 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();
}
/**
* Returns the number of entries filtered by index
*
* @param queueName
* @return {Promise<number>}
*/
async getEntryCountByQueueName(queueName) {
const db = await this.getDb();
return db.countFromIndex(REQUEST_OBJECT_STORE_NAME, QUEUE_NAME_INDEX, IDBKeyRange.only(queueName));
}
/**
* 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 || cursor === void 0 ? 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 });
}
}

View File

@@ -0,0 +1 @@
export * from './QueueDb.js';

View File

@@ -0,0 +1,83 @@
import { UnidentifiedQueueStoreEntry, QueueStoreEntry } from './QueueDb.js';
import '../_version.js';
/**
* A class to manage storing requests from a Queue in IndexedDB,
* indexed by their queue name for easier access.
*
* Most developers will not need to access this class directly;
* it is exposed for advanced use cases.
*/
export declare class QueueStore {
private readonly _queueName;
private readonly _queueDb;
/**
* Associates this instance with a Queue instance, so entries added can be
* identified by their queue name.
*
* @param {string} queueName
*/
constructor(queueName: string);
/**
* Append an entry last in the queue.
*
* @param {Object} entry
* @param {Object} entry.requestData
* @param {number} [entry.timestamp]
* @param {Object} [entry.metadata]
*/
pushEntry(entry: UnidentifiedQueueStoreEntry): Promise<void>;
/**
* Prepend an entry first in the queue.
*
* @param {Object} entry
* @param {Object} entry.requestData
* @param {number} [entry.timestamp]
* @param {Object} [entry.metadata]
*/
unshiftEntry(entry: UnidentifiedQueueStoreEntry): Promise<void>;
/**
* Removes and returns the last entry in the queue matching the `queueName`.
*
* @return {Promise<QueueStoreEntry|undefined>}
*/
popEntry(): Promise<QueueStoreEntry | undefined>;
/**
* Removes and returns the first entry in the queue matching the `queueName`.
*
* @return {Promise<QueueStoreEntry|undefined>}
*/
shiftEntry(): Promise<QueueStoreEntry | undefined>;
/**
* Returns all entries in the store matching the `queueName`.
*
* @param {Object} options See {@link workbox-background-sync.Queue~getAll}
* @return {Promise<Array<Object>>}
*/
getAll(): Promise<QueueStoreEntry[]>;
/**
* Returns the number of entries in the store matching the `queueName`.
*
* @param {Object} options See {@link workbox-background-sync.Queue~size}
* @return {Promise<number>}
*/
size(): Promise<number>;
/**
* Deletes the entry for the given ID.
*
* WARNING: this method does not ensure the deleted entry belongs to this
* queue (i.e. matches the `queueName`). But this limitation is acceptable
* as this class is not publicly exposed. An additional check would make
* this method slower than it needs to be.
*
* @param {number} id
*/
deleteEntry(id: number): Promise<void>;
/**
* Removes and returns the first or last entry in the queue (based on the
* `direction` argument) matching the `queueName`.
*
* @return {Promise<QueueStoreEntry|undefined>}
* @private
*/
_removeEntry(entry?: QueueStoreEntry): Promise<QueueStoreEntry | undefined>;
}

View File

@@ -0,0 +1,152 @@
/*
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.
*/
import { assert } from 'workbox-core/_private/assert.js';
import { QueueDb, } from './QueueDb.js';
import '../_version.js';
/**
* A class to manage storing requests from a Queue in IndexedDB,
* indexed by their queue name for easier access.
*
* Most developers will not need to access this class directly;
* it is exposed for advanced use cases.
*/
export class QueueStore {
/**
* Associates this instance with a Queue instance, so entries added can be
* identified by their queue name.
*
* @param {string} queueName
*/
constructor(queueName) {
this._queueName = queueName;
this._queueDb = new QueueDb();
}
/**
* Append an entry last in the queue.
*
* @param {Object} entry
* @param {Object} entry.requestData
* @param {number} [entry.timestamp]
* @param {Object} [entry.metadata]
*/
async pushEntry(entry) {
if (process.env.NODE_ENV !== 'production') {
assert.isType(entry, 'object', {
moduleName: 'workbox-background-sync',
className: 'QueueStore',
funcName: 'pushEntry',
paramName: 'entry',
});
assert.isType(entry.requestData, 'object', {
moduleName: 'workbox-background-sync',
className: 'QueueStore',
funcName: 'pushEntry',
paramName: 'entry.requestData',
});
}
// Don't specify an ID since one is automatically generated.
delete entry.id;
entry.queueName = this._queueName;
await this._queueDb.addEntry(entry);
}
/**
* Prepend an entry first in the queue.
*
* @param {Object} entry
* @param {Object} entry.requestData
* @param {number} [entry.timestamp]
* @param {Object} [entry.metadata]
*/
async unshiftEntry(entry) {
if (process.env.NODE_ENV !== 'production') {
assert.isType(entry, 'object', {
moduleName: 'workbox-background-sync',
className: 'QueueStore',
funcName: 'unshiftEntry',
paramName: 'entry',
});
assert.isType(entry.requestData, 'object', {
moduleName: 'workbox-background-sync',
className: 'QueueStore',
funcName: 'unshiftEntry',
paramName: 'entry.requestData',
});
}
const firstId = await this._queueDb.getFirstEntryId();
if (firstId) {
// Pick an ID one less than the lowest ID in the object store.
entry.id = firstId - 1;
}
else {
// Otherwise let the auto-incrementor assign the ID.
delete entry.id;
}
entry.queueName = this._queueName;
await this._queueDb.addEntry(entry);
}
/**
* Removes and returns the last entry in the queue matching the `queueName`.
*
* @return {Promise<QueueStoreEntry|undefined>}
*/
async popEntry() {
return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName));
}
/**
* Removes and returns the first entry in the queue matching the `queueName`.
*
* @return {Promise<QueueStoreEntry|undefined>}
*/
async shiftEntry() {
return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName));
}
/**
* Returns all entries in the store matching the `queueName`.
*
* @param {Object} options See {@link workbox-background-sync.Queue~getAll}
* @return {Promise<Array<Object>>}
*/
async getAll() {
return await this._queueDb.getAllEntriesByQueueName(this._queueName);
}
/**
* Returns the number of entries in the store matching the `queueName`.
*
* @param {Object} options See {@link workbox-background-sync.Queue~size}
* @return {Promise<number>}
*/
async size() {
return await this._queueDb.getEntryCountByQueueName(this._queueName);
}
/**
* Deletes the entry for the given ID.
*
* WARNING: this method does not ensure the deleted entry belongs to this
* queue (i.e. matches the `queueName`). But this limitation is acceptable
* as this class is not publicly exposed. An additional check would make
* this method slower than it needs to be.
*
* @param {number} id
*/
async deleteEntry(id) {
await this._queueDb.deleteEntry(id);
}
/**
* Removes and returns the first or last entry in the queue (based on the
* `direction` argument) matching the `queueName`.
*
* @return {Promise<QueueStoreEntry|undefined>}
* @private
*/
async _removeEntry(entry) {
if (entry) {
await this.deleteEntry(entry.id);
}
return entry;
}
}

View File

@@ -0,0 +1 @@
export * from './QueueStore.js';

View File

@@ -0,0 +1,53 @@
import { MapLikeObject } from 'workbox-core/types.js';
import '../_version.js';
export interface RequestData extends MapLikeObject {
url: string;
headers: MapLikeObject;
body?: ArrayBuffer;
}
/**
* A class to make it easier to serialize and de-serialize requests so they
* can be stored in IndexedDB.
*
* Most developers will not need to access this class directly;
* it is exposed for advanced use cases.
*/
declare class StorableRequest {
private readonly _requestData;
/**
* Converts a Request object to a plain object that can be structured
* cloned or JSON-stringified.
*
* @param {Request} request
* @return {Promise<StorableRequest>}
*/
static fromRequest(request: Request): Promise<StorableRequest>;
/**
* Accepts an object of request data that can be used to construct a
* `Request` but can also be stored in IndexedDB.
*
* @param {Object} requestData An object of request data that includes the
* `url` plus any relevant properties of
* [requestInit]{@link https://fetch.spec.whatwg.org/#requestinit}.
*/
constructor(requestData: RequestData);
/**
* Returns a deep clone of the instances `_requestData` object.
*
* @return {Object}
*/
toObject(): RequestData;
/**
* Converts this instance to a Request.
*
* @return {Request}
*/
toRequest(): Request;
/**
* Creates and returns a deep clone of the instance.
*
* @return {StorableRequest}
*/
clone(): StorableRequest;
}
export { StorableRequest };

View File

@@ -0,0 +1,121 @@
/*
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.
*/
import { assert } from 'workbox-core/_private/assert.js';
import '../_version.js';
const serializableProperties = [
'method',
'referrer',
'referrerPolicy',
'mode',
'credentials',
'cache',
'redirect',
'integrity',
'keepalive',
];
/**
* A class to make it easier to serialize and de-serialize requests so they
* can be stored in IndexedDB.
*
* Most developers will not need to access this class directly;
* it is exposed for advanced use cases.
*/
class StorableRequest {
/**
* Converts a Request object to a plain object that can be structured
* cloned or JSON-stringified.
*
* @param {Request} request
* @return {Promise<StorableRequest>}
*/
static async fromRequest(request) {
const requestData = {
url: request.url,
headers: {},
};
// Set the body if present.
if (request.method !== 'GET') {
// Use ArrayBuffer to support non-text request bodies.
// NOTE: we can't use Blobs becuse Safari doesn't support storing
// Blobs in IndexedDB in some cases:
// https://github.com/dfahlander/Dexie.js/issues/618#issuecomment-398348457
requestData.body = await request.clone().arrayBuffer();
}
// Convert the headers from an iterable to an object.
for (const [key, value] of request.headers.entries()) {
requestData.headers[key] = value;
}
// Add all other serializable request properties
for (const prop of serializableProperties) {
if (request[prop] !== undefined) {
requestData[prop] = request[prop];
}
}
return new StorableRequest(requestData);
}
/**
* Accepts an object of request data that can be used to construct a
* `Request` but can also be stored in IndexedDB.
*
* @param {Object} requestData An object of request data that includes the
* `url` plus any relevant properties of
* [requestInit]{@link https://fetch.spec.whatwg.org/#requestinit}.
*/
constructor(requestData) {
if (process.env.NODE_ENV !== 'production') {
assert.isType(requestData, 'object', {
moduleName: 'workbox-background-sync',
className: 'StorableRequest',
funcName: 'constructor',
paramName: 'requestData',
});
assert.isType(requestData.url, 'string', {
moduleName: 'workbox-background-sync',
className: 'StorableRequest',
funcName: 'constructor',
paramName: 'requestData.url',
});
}
// If the request's mode is `navigate`, convert it to `same-origin` since
// navigation requests can't be constructed via script.
if (requestData['mode'] === 'navigate') {
requestData['mode'] = 'same-origin';
}
this._requestData = requestData;
}
/**
* Returns a deep clone of the instances `_requestData` object.
*
* @return {Object}
*/
toObject() {
const requestData = Object.assign({}, this._requestData);
requestData.headers = Object.assign({}, this._requestData.headers);
if (requestData.body) {
requestData.body = requestData.body.slice(0);
}
return requestData;
}
/**
* Converts this instance to a Request.
*
* @return {Request}
*/
toRequest() {
return new Request(this._requestData.url, this._requestData);
}
/**
* Creates and returns a deep clone of the instance.
*
* @return {StorableRequest}
*/
clone() {
return new StorableRequest(this.toObject());
}
}
export { StorableRequest };

View File

@@ -0,0 +1 @@
export * from './StorableRequest.js';