From dbb7ff8e176f13c49f5a9947892de0c4f4668fb2 Mon Sep 17 00:00:00 2001 From: Kwok Chi Leong Date: Sat, 16 Nov 2019 06:03:40 +0800 Subject: [PATCH] [workbox] Added type definitions for all packages (#40277) * [workbox-core] Added type definitions * [workbox-core] Updated ts-doc * [workbox-core] Added types.d.ts * [workbox-core] Removed TSDoc * [workbox-core] Moved some types * [workbox-core] Bug fixes * [workbox-expiration] Added type definitions * [workbox-strategies] Added type definitions * [workbox-strategies] Change "es6" to "es2015" * [workbox-precaching] Added type definitions * [workbox-precaching] Added missing method * [workbox-core] Moved some files to a sub-folder * [workbox-core] Moved some files to a sub-folder * [workbox-precaching] Moved some file to sub-folder * [workbox-core] Added generic type support * [workbox-routing] Added type definitions * [workbox-routing] Changed from "es6" to "es2015" * [workbox-background-sync] Added type definitions * [workbox-google-analytics] Added type definitions * [workbox-cacheable-response] Added type definition * [workbox-broadcast-update] Added type definitions * [workbox-range-requests] Added type definitions * [workbox-streams] Added type definitions * [workbox-streams] Added "use strict" to tests * [workbox-navigation-preload] Added type definition * [workbox-precaching] Added the missing type def... * Added the missing type definitions * [workbox-precaching] Commented the upcoming properties * [workbox-routing] Added the missing type definitions * [workbox-strategies] Changed package references * [workbox-expiration] Added the missing tests * [workbox-strategies] Updated tests * [workbox-background-sync] Fixed wrong file name * [workbox-google-analytics] Updated tests * [workbox-cacheable-response] Fixed the incorrectly named files * [workbox-broadcast-update] Fixed the incorrectly named files * [workbox-broadcast-update] Added the missing function * [workbox-broadcast-update] Fixed typo * [workbox-navigation-preload] Updated tests * [workbox-range-requests] Fixed the incorrectly named files * [workbox-streams] Updated tests * [workbox-core] Updated tests * [workbox-window] Updated tests and moved some files * [workbox-window] Updated "es6" to "es2015" * [workbox-sw] Updated definition to make use of the newly added definitions * [workbox] Updated "Definitions by" field * [workbox-sw] Updated rules * [workbox] Updated version numbers * [workbox-window] Fixed version number --- types/workbox-background-sync/Plugin.d.ts | 11 + types/workbox-background-sync/Queue.d.ts | 21 + types/workbox-background-sync/index.d.ts | 8 + types/workbox-background-sync/tsconfig.json | 26 + types/workbox-background-sync/tslint.json | 6 + .../workbox-background-sync-tests.ts | 62 + .../BroadcastCacheUpdate.d.ts | 20 + types/workbox-broadcast-update/Plugin.d.ts | 11 + .../broadcastUpdate.d.ts | 7 + types/workbox-broadcast-update/index.d.ts | 9 + types/workbox-broadcast-update/tsconfig.json | 27 + types/workbox-broadcast-update/tslint.json | 1 + .../workbox-broadcast-update-tests.ts | 54 + .../CacheableResponse.d.ts | 9 + types/workbox-cacheable-response/Plugin.d.ts | 11 + types/workbox-cacheable-response/index.d.ts | 8 + .../workbox-cacheable-response/tsconfig.json | 26 + types/workbox-cacheable-response/tslint.json | 1 + .../workbox-cacheable-response-tests.ts | 41 + types/workbox-core/cacheNames.d.ts | 9 + types/workbox-core/clientsClaim.d.ts | 1 + types/workbox-core/index.d.ts | 13 + .../registerQuotaErrorCallback.d.ts | 1 + types/workbox-core/setCacheNameDetails.d.ts | 9 + types/workbox-core/skipWaiting.d.ts | 1 + types/workbox-core/tsconfig.json | 30 + types/workbox-core/tslint.json | 1 + types/workbox-core/types/WorkboxPlugin.d.ts | 80 + types/workbox-core/workbox-core-tests.ts | 76 + types/workbox-expiration/CacheExpiration.d.ts | 12 + types/workbox-expiration/Plugin.d.ts | 18 + types/workbox-expiration/index.d.ts | 8 + types/workbox-expiration/tsconfig.json | 26 + types/workbox-expiration/tslint.json | 1 + .../workbox-expiration-tests.ts | 57 + types/workbox-google-analytics/index.d.ts | 7 + .../workbox-google-analytics/initialize.d.ts | 7 + types/workbox-google-analytics/tsconfig.json | 25 + types/workbox-google-analytics/tslint.json | 1 + .../workbox-google-analytics-tests.ts | 21 + types/workbox-navigation-preload/disable.d.ts | 1 + types/workbox-navigation-preload/enable.d.ts | 1 + types/workbox-navigation-preload/index.d.ts | 9 + .../isSupported.d.ts | 1 + .../workbox-navigation-preload/tsconfig.json | 27 + types/workbox-navigation-preload/tslint.json | 1 + .../workbox-navigation-preload-tests.ts | 42 + .../PrecacheController.d.ts | 22 + types/workbox-precaching/addPlugins.d.ts | 3 + types/workbox-precaching/addRoute.d.ts | 5 + .../cleanupOutdatedCaches.d.ts | 1 + .../workbox-precaching/getCacheKeyForURL.d.ts | 1 + types/workbox-precaching/index.d.ts | 18 + types/workbox-precaching/precache.d.ts | 5 + .../workbox-precaching/precacheAndRoute.d.ts | 6 + types/workbox-precaching/tsconfig.json | 36 + types/workbox-precaching/tslint.json | 1 + .../types/CleanupResult.d.ts | 3 + .../types/FetchListenerOptions.d.ts | 8 + .../types/InstallResult.d.ts | 4 + .../types/PrecacheEntry.d.ts | 5 + .../types/URLManipulation.d.ts | 1 + .../workbox-precaching-tests.ts | 123 + types/workbox-range-requests/Plugin.d.ts | 6 + .../createPartialResponse.d.ts | 1 + types/workbox-range-requests/index.d.ts | 8 + types/workbox-range-requests/tsconfig.json | 26 + types/workbox-range-requests/tslint.json | 1 + .../workbox-range-requests-tests.ts | 29 + types/workbox-routing/NavigationRoute.d.ts | 13 + types/workbox-routing/RegExpRoute.d.ts | 8 + types/workbox-routing/Route.d.ts | 10 + types/workbox-routing/Router.d.ts | 39 + types/workbox-routing/index.d.ts | 18 + .../registerNavigationRoute.d.ts | 7 + types/workbox-routing/registerRoute.d.ts | 13 + types/workbox-routing/setCatchHandler.d.ts | 3 + types/workbox-routing/setDefaultHandler.d.ts | 3 + types/workbox-routing/tsconfig.json | 35 + types/workbox-routing/tslint.json | 7 + types/workbox-routing/types/HTTPMethod.d.ts | 1 + types/workbox-routing/types/RouteHandler.d.ts | 14 + .../types/RouteMatchCallback.d.ts | 7 + .../workbox-routing/workbox-routing-tests.ts | 164 ++ types/workbox-strategies/CacheFirst.d.ts | 20 + types/workbox-strategies/CacheOnly.d.ts | 19 + types/workbox-strategies/NetworkFirst.d.ts | 21 + types/workbox-strategies/NetworkOnly.d.ts | 19 + .../StaleWhileRevalidate.d.ts | 20 + types/workbox-strategies/index.d.ts | 13 + types/workbox-strategies/tsconfig.json | 30 + types/workbox-strategies/tslint.json | 1 + .../types/MakeRequestCallback.d.ts | 8 + .../workbox-strategies-tests.ts | 112 + types/workbox-streams/concatenate.d.ts | 8 + .../concatenateToResponse.d.ts | 8 + types/workbox-streams/index.d.ts | 12 + types/workbox-streams/isSupported.d.ts | 1 + types/workbox-streams/strategy.d.ts | 10 + types/workbox-streams/tsconfig.json | 29 + types/workbox-streams/tslint.json | 1 + types/workbox-streams/types/StreamSource.d.ts | 1 + .../workbox-streams/workbox-streams-tests.ts | 57 + types/workbox-sw/index.d.ts | 2079 +---------------- types/workbox-sw/tsconfig.json | 11 +- types/workbox-sw/tslint.json | 6 +- types/workbox-sw/workbox-sw-tests.ts | 33 +- types/workbox-window/Workbox.d.ts | 121 +- types/workbox-window/index.d.ts | 8 +- types/workbox-window/messageSW.d.ts | 13 +- types/workbox-window/tsconfig.json | 5 +- types/workbox-window/types/WorkboxEvent.d.ts | 7 + .../workbox-window/types/WorkboxEventMap.d.ts | 29 + .../workbox-window/utils/EventTargetShim.d.ts | 19 +- types/workbox-window/utils/WorkboxEvent.d.ts | 25 - types/workbox-window/workbox-window-tests.ts | 75 +- 116 files changed, 2092 insertions(+), 2229 deletions(-) create mode 100644 types/workbox-background-sync/Plugin.d.ts create mode 100644 types/workbox-background-sync/Queue.d.ts create mode 100644 types/workbox-background-sync/index.d.ts create mode 100644 types/workbox-background-sync/tsconfig.json create mode 100644 types/workbox-background-sync/tslint.json create mode 100644 types/workbox-background-sync/workbox-background-sync-tests.ts create mode 100644 types/workbox-broadcast-update/BroadcastCacheUpdate.d.ts create mode 100644 types/workbox-broadcast-update/Plugin.d.ts create mode 100644 types/workbox-broadcast-update/broadcastUpdate.d.ts create mode 100644 types/workbox-broadcast-update/index.d.ts create mode 100644 types/workbox-broadcast-update/tsconfig.json create mode 100644 types/workbox-broadcast-update/tslint.json create mode 100644 types/workbox-broadcast-update/workbox-broadcast-update-tests.ts create mode 100644 types/workbox-cacheable-response/CacheableResponse.d.ts create mode 100644 types/workbox-cacheable-response/Plugin.d.ts create mode 100644 types/workbox-cacheable-response/index.d.ts create mode 100644 types/workbox-cacheable-response/tsconfig.json create mode 100644 types/workbox-cacheable-response/tslint.json create mode 100644 types/workbox-cacheable-response/workbox-cacheable-response-tests.ts create mode 100644 types/workbox-core/cacheNames.d.ts create mode 100644 types/workbox-core/clientsClaim.d.ts create mode 100644 types/workbox-core/index.d.ts create mode 100644 types/workbox-core/registerQuotaErrorCallback.d.ts create mode 100644 types/workbox-core/setCacheNameDetails.d.ts create mode 100644 types/workbox-core/skipWaiting.d.ts create mode 100644 types/workbox-core/tsconfig.json create mode 100644 types/workbox-core/tslint.json create mode 100644 types/workbox-core/types/WorkboxPlugin.d.ts create mode 100644 types/workbox-core/workbox-core-tests.ts create mode 100644 types/workbox-expiration/CacheExpiration.d.ts create mode 100644 types/workbox-expiration/Plugin.d.ts create mode 100644 types/workbox-expiration/index.d.ts create mode 100644 types/workbox-expiration/tsconfig.json create mode 100644 types/workbox-expiration/tslint.json create mode 100644 types/workbox-expiration/workbox-expiration-tests.ts create mode 100644 types/workbox-google-analytics/index.d.ts create mode 100644 types/workbox-google-analytics/initialize.d.ts create mode 100644 types/workbox-google-analytics/tsconfig.json create mode 100644 types/workbox-google-analytics/tslint.json create mode 100644 types/workbox-google-analytics/workbox-google-analytics-tests.ts create mode 100644 types/workbox-navigation-preload/disable.d.ts create mode 100644 types/workbox-navigation-preload/enable.d.ts create mode 100644 types/workbox-navigation-preload/index.d.ts create mode 100644 types/workbox-navigation-preload/isSupported.d.ts create mode 100644 types/workbox-navigation-preload/tsconfig.json create mode 100644 types/workbox-navigation-preload/tslint.json create mode 100644 types/workbox-navigation-preload/workbox-navigation-preload-tests.ts create mode 100644 types/workbox-precaching/PrecacheController.d.ts create mode 100644 types/workbox-precaching/addPlugins.d.ts create mode 100644 types/workbox-precaching/addRoute.d.ts create mode 100644 types/workbox-precaching/cleanupOutdatedCaches.d.ts create mode 100644 types/workbox-precaching/getCacheKeyForURL.d.ts create mode 100644 types/workbox-precaching/index.d.ts create mode 100644 types/workbox-precaching/precache.d.ts create mode 100644 types/workbox-precaching/precacheAndRoute.d.ts create mode 100644 types/workbox-precaching/tsconfig.json create mode 100644 types/workbox-precaching/tslint.json create mode 100644 types/workbox-precaching/types/CleanupResult.d.ts create mode 100644 types/workbox-precaching/types/FetchListenerOptions.d.ts create mode 100644 types/workbox-precaching/types/InstallResult.d.ts create mode 100644 types/workbox-precaching/types/PrecacheEntry.d.ts create mode 100644 types/workbox-precaching/types/URLManipulation.d.ts create mode 100644 types/workbox-precaching/workbox-precaching-tests.ts create mode 100644 types/workbox-range-requests/Plugin.d.ts create mode 100644 types/workbox-range-requests/createPartialResponse.d.ts create mode 100644 types/workbox-range-requests/index.d.ts create mode 100644 types/workbox-range-requests/tsconfig.json create mode 100644 types/workbox-range-requests/tslint.json create mode 100644 types/workbox-range-requests/workbox-range-requests-tests.ts create mode 100644 types/workbox-routing/NavigationRoute.d.ts create mode 100644 types/workbox-routing/RegExpRoute.d.ts create mode 100644 types/workbox-routing/Route.d.ts create mode 100644 types/workbox-routing/Router.d.ts create mode 100644 types/workbox-routing/index.d.ts create mode 100644 types/workbox-routing/registerNavigationRoute.d.ts create mode 100644 types/workbox-routing/registerRoute.d.ts create mode 100644 types/workbox-routing/setCatchHandler.d.ts create mode 100644 types/workbox-routing/setDefaultHandler.d.ts create mode 100644 types/workbox-routing/tsconfig.json create mode 100644 types/workbox-routing/tslint.json create mode 100644 types/workbox-routing/types/HTTPMethod.d.ts create mode 100644 types/workbox-routing/types/RouteHandler.d.ts create mode 100644 types/workbox-routing/types/RouteMatchCallback.d.ts create mode 100644 types/workbox-routing/workbox-routing-tests.ts create mode 100644 types/workbox-strategies/CacheFirst.d.ts create mode 100644 types/workbox-strategies/CacheOnly.d.ts create mode 100644 types/workbox-strategies/NetworkFirst.d.ts create mode 100644 types/workbox-strategies/NetworkOnly.d.ts create mode 100644 types/workbox-strategies/StaleWhileRevalidate.d.ts create mode 100644 types/workbox-strategies/index.d.ts create mode 100644 types/workbox-strategies/tsconfig.json create mode 100644 types/workbox-strategies/tslint.json create mode 100644 types/workbox-strategies/types/MakeRequestCallback.d.ts create mode 100644 types/workbox-strategies/workbox-strategies-tests.ts create mode 100644 types/workbox-streams/concatenate.d.ts create mode 100644 types/workbox-streams/concatenateToResponse.d.ts create mode 100644 types/workbox-streams/index.d.ts create mode 100644 types/workbox-streams/isSupported.d.ts create mode 100644 types/workbox-streams/strategy.d.ts create mode 100644 types/workbox-streams/tsconfig.json create mode 100644 types/workbox-streams/tslint.json create mode 100644 types/workbox-streams/types/StreamSource.d.ts create mode 100644 types/workbox-streams/workbox-streams-tests.ts create mode 100644 types/workbox-window/types/WorkboxEvent.d.ts create mode 100644 types/workbox-window/types/WorkboxEventMap.d.ts delete mode 100644 types/workbox-window/utils/WorkboxEvent.d.ts diff --git a/types/workbox-background-sync/Plugin.d.ts b/types/workbox-background-sync/Plugin.d.ts new file mode 100644 index 0000000000..ee9ef53525 --- /dev/null +++ b/types/workbox-background-sync/Plugin.d.ts @@ -0,0 +1,11 @@ +import { + FetchDidFailCallback, + WorkboxPlugin, +} from "workbox-core/types/WorkboxPlugin"; + +import { QueueOptions } from "./Queue"; + +export class Plugin implements WorkboxPlugin { + constructor(name: string, options?: QueueOptions); + fetchDidFail: FetchDidFailCallback; +} diff --git a/types/workbox-background-sync/Queue.d.ts b/types/workbox-background-sync/Queue.d.ts new file mode 100644 index 0000000000..67257dd4c9 --- /dev/null +++ b/types/workbox-background-sync/Queue.d.ts @@ -0,0 +1,21 @@ +export class Queue { + constructor(name: string, options?: QueueOptions); + readonly name: string; + getAll(): Promise; + popRequest(): Promise; + pushRequest(entry: QueueEntry): Promise; + registerSync(): Promise; + shiftRequest(): Promise; + unshiftRequest(entry: QueueEntry): Promise; +} + +export interface QueueOptions { + maxRetentionTime?: number; + onSync?: () => void; +} + +export interface QueueEntry { + request: Request; + metadata?: Metadata; + timestamp?: number; +} diff --git a/types/workbox-background-sync/index.d.ts b/types/workbox-background-sync/index.d.ts new file mode 100644 index 0000000000..3c12450eec --- /dev/null +++ b/types/workbox-background-sync/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for workbox-background-sync 4.3 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export * from "./Plugin"; +export * from "./Queue"; diff --git a/types/workbox-background-sync/tsconfig.json b/types/workbox-background-sync/tsconfig.json new file mode 100644 index 0000000000..c27666d4f6 --- /dev/null +++ b/types/workbox-background-sync/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "Plugin.d.ts", + "Queue.d.ts", + "workbox-background-sync-tests.ts" + ] +} diff --git a/types/workbox-background-sync/tslint.json b/types/workbox-background-sync/tslint.json new file mode 100644 index 0000000000..71ee04c4e1 --- /dev/null +++ b/types/workbox-background-sync/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/workbox-background-sync/workbox-background-sync-tests.ts b/types/workbox-background-sync/workbox-background-sync-tests.ts new file mode 100644 index 0000000000..b0945d68eb --- /dev/null +++ b/types/workbox-background-sync/workbox-background-sync-tests.ts @@ -0,0 +1,62 @@ +/* tslint:disable:comment-format no-namespace */ + +"use strict"; + +import { + Plugin, + Queue, + QueueEntry, + QueueOptions, +} from "workbox-background-sync"; + +//============================================================================== +// WorkboxBackgroundSync.Queue +//============================================================================== + +export namespace QueueTest { + declare const name: string; + declare const options: QueueOptions; + + // $ExpectType Queue + new Queue(name); + // $ExpectType Queue + new Queue(name, options); + + declare const queue: Queue; + declare const queueEntry: QueueEntry; + + // $ExpectType string + queue.name; + + // $ExpectType Promise[]> + queue.getAll(); + + // $ExpectType Promise> + queue.popRequest(); + + // $ExpectType Promise + queue.pushRequest(queueEntry); + + // $ExpectType Promise + queue.registerSync(); + + // $ExpectType Promise> + queue.shiftRequest(); + + // $ExpectType Promise + queue.unshiftRequest(queueEntry); +} + +//============================================================================== +// WorkboxBackgroundSync.Plugin +//============================================================================== + +export namespace BackgroundSyncPluginTest { + declare const name: string; + declare const options: QueueOptions; + + // $ExpectType Plugin + new Plugin(name); + // $ExpectType Plugin + new Plugin(name, options); +} diff --git a/types/workbox-broadcast-update/BroadcastCacheUpdate.d.ts b/types/workbox-broadcast-update/BroadcastCacheUpdate.d.ts new file mode 100644 index 0000000000..ff874e5d86 --- /dev/null +++ b/types/workbox-broadcast-update/BroadcastCacheUpdate.d.ts @@ -0,0 +1,20 @@ +export class BroadcastCacheUpdate { + constructor(options?: BroadcastCacheUpdateOptions); + notifyIfUpdated(options: BroadcastCacheUpdate.NotifyIfUpdatedOptions): Promise; +} + +export namespace BroadcastCacheUpdate { + interface NotifyIfUpdatedOptions { + cacheName: string; + newResponse: Response; + oldResponse?: Response; + url: string; + event?: Event; + } +} + +export interface BroadcastCacheUpdateOptions { + channelName?: string; + deferNoticationTimeout?: number; + headersToCheck?: string[]; +} diff --git a/types/workbox-broadcast-update/Plugin.d.ts b/types/workbox-broadcast-update/Plugin.d.ts new file mode 100644 index 0000000000..dde741950b --- /dev/null +++ b/types/workbox-broadcast-update/Plugin.d.ts @@ -0,0 +1,11 @@ +import { + CacheDidUpdateCallback, + WorkboxPlugin, +} from "workbox-core/types/WorkboxPlugin"; + +import { BroadcastCacheUpdateOptions } from "./BroadcastCacheUpdate"; + +export class Plugin implements WorkboxPlugin { + constructor(options?: BroadcastCacheUpdateOptions); + cacheDidUpdate: CacheDidUpdateCallback; +} diff --git a/types/workbox-broadcast-update/broadcastUpdate.d.ts b/types/workbox-broadcast-update/broadcastUpdate.d.ts new file mode 100644 index 0000000000..17bcfcb603 --- /dev/null +++ b/types/workbox-broadcast-update/broadcastUpdate.d.ts @@ -0,0 +1,7 @@ +export function broadcastUpdate(options: BroadcastUpdateOptions): Promise; + +export interface BroadcastUpdateOptions { + cacheName: string; + url: string; + channel?: string; +} diff --git a/types/workbox-broadcast-update/index.d.ts b/types/workbox-broadcast-update/index.d.ts new file mode 100644 index 0000000000..dbcfb87bad --- /dev/null +++ b/types/workbox-broadcast-update/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for workbox-broadcast-update 4.3 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export * from "./BroadcastCacheUpdate"; +export * from "./Plugin"; +export * from "./broadcastUpdate"; diff --git a/types/workbox-broadcast-update/tsconfig.json b/types/workbox-broadcast-update/tsconfig.json new file mode 100644 index 0000000000..394c44f1b1 --- /dev/null +++ b/types/workbox-broadcast-update/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "BroadcastCacheUpdate.d.ts", + "Plugin.d.ts", + "broadcastUpdate.d.ts", + "workbox-broadcast-update-tests.ts" + ] +} diff --git a/types/workbox-broadcast-update/tslint.json b/types/workbox-broadcast-update/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/workbox-broadcast-update/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/workbox-broadcast-update/workbox-broadcast-update-tests.ts b/types/workbox-broadcast-update/workbox-broadcast-update-tests.ts new file mode 100644 index 0000000000..70818c8b28 --- /dev/null +++ b/types/workbox-broadcast-update/workbox-broadcast-update-tests.ts @@ -0,0 +1,54 @@ +/* tslint:disable:comment-format no-namespace */ + +"use strict"; + +import { + BroadcastCacheUpdate, + BroadcastCacheUpdateOptions, + BroadcastUpdateOptions, + Plugin, + broadcastUpdate, +} from "workbox-broadcast-update"; + +//============================================================================== +// WorkboxBroadcastUpdate.BroadcastCacheUpdate +//============================================================================== + +export namespace BroadcastCacheUpdateTest { + declare const options: BroadcastCacheUpdateOptions; + + // $ExpectType BroadcastCacheUpdate + new BroadcastCacheUpdate(); + // $ExpectType BroadcastCacheUpdate + new BroadcastCacheUpdate(options); + + declare const broadcast: BroadcastCacheUpdate; + declare const notifyOptions: BroadcastCacheUpdate.NotifyIfUpdatedOptions; + + // $ExpectType Promise + broadcast.notifyIfUpdated(notifyOptions); +} + +//============================================================================== +// WorkboxBroadcastUpdate.Plugin +//============================================================================== + +export namespace BroadcastUpdatePluginTest { + declare const options: BroadcastCacheUpdateOptions; + + // $ExpectType Plugin + new Plugin(); + // $ExpectType Plugin + new Plugin(options); +} + +//============================================================================== +// WorkboxBroadcastUpdate.broadcastUpdate +//============================================================================== + +export namespace BroadcastUpdateTest { + declare const options: BroadcastUpdateOptions; + + // $ExpectType Promise + broadcastUpdate(options); +} diff --git a/types/workbox-cacheable-response/CacheableResponse.d.ts b/types/workbox-cacheable-response/CacheableResponse.d.ts new file mode 100644 index 0000000000..5b8085b59a --- /dev/null +++ b/types/workbox-cacheable-response/CacheableResponse.d.ts @@ -0,0 +1,9 @@ +export class CacheableResponse { + constructor(config?: CacheableResponseConfig); + isResponseCacheable(response: Response): boolean; +} + +export interface CacheableResponseConfig { + headers?: Record; + statuses?: number[]; +} diff --git a/types/workbox-cacheable-response/Plugin.d.ts b/types/workbox-cacheable-response/Plugin.d.ts new file mode 100644 index 0000000000..73cdd108d5 --- /dev/null +++ b/types/workbox-cacheable-response/Plugin.d.ts @@ -0,0 +1,11 @@ +import { + CacheWillUpdateCallback, + WorkboxPlugin, +} from "workbox-core/types/WorkboxPlugin"; + +import { CacheableResponseConfig } from "./CacheableResponse"; + +export class Plugin implements WorkboxPlugin { + constructor(config?: CacheableResponseConfig); + cacheWillUpdate: CacheWillUpdateCallback; +} diff --git a/types/workbox-cacheable-response/index.d.ts b/types/workbox-cacheable-response/index.d.ts new file mode 100644 index 0000000000..6f85a9a88d --- /dev/null +++ b/types/workbox-cacheable-response/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for workbox-cacheable-response 4.3 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export * from "./CacheableResponse"; +export * from "./Plugin"; diff --git a/types/workbox-cacheable-response/tsconfig.json b/types/workbox-cacheable-response/tsconfig.json new file mode 100644 index 0000000000..ed8d13cec2 --- /dev/null +++ b/types/workbox-cacheable-response/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "CacheableResponse.d.ts", + "Plugin.d.ts", + "workbox-cacheable-response-tests.ts" + ] +} diff --git a/types/workbox-cacheable-response/tslint.json b/types/workbox-cacheable-response/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/workbox-cacheable-response/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/workbox-cacheable-response/workbox-cacheable-response-tests.ts b/types/workbox-cacheable-response/workbox-cacheable-response-tests.ts new file mode 100644 index 0000000000..130618ea55 --- /dev/null +++ b/types/workbox-cacheable-response/workbox-cacheable-response-tests.ts @@ -0,0 +1,41 @@ +/* tslint:disable:comment-format no-namespace */ + +"use strict"; + +import { + CacheableResponse, + CacheableResponseConfig, + Plugin, +} from "workbox-cacheable-response"; + +//============================================================================== +// WorkboxCacheableResponse.CacheableResponse +//============================================================================== + +export namespace CacheableResponseTest { + declare const config: CacheableResponseConfig; + + // $ExpectType CacheableResponse + new CacheableResponse(); + // $ExpectType CacheableResponse + new CacheableResponse(config); + + declare const cacheable: CacheableResponse; + declare const response: Response; + + // $ExpectType boolean + cacheable.isResponseCacheable(response); +} + +//============================================================================== +// WorkboxCacheableResponse.Plugin +//============================================================================== + +export namespace CacheableResponsePluginTest { + declare const config: CacheableResponseConfig; + + // $ExpectType Plugin + new Plugin(); + // $ExpectType Plugin + new Plugin(config); +} diff --git a/types/workbox-core/cacheNames.d.ts b/types/workbox-core/cacheNames.d.ts new file mode 100644 index 0000000000..6168a5d09c --- /dev/null +++ b/types/workbox-core/cacheNames.d.ts @@ -0,0 +1,9 @@ +export const cacheNames: CacheNames; + +export interface CacheNames { + readonly googleAnalytics: string; + readonly precache: string; + readonly prefix: string; + readonly runtime: string; + readonly suffix: string; +} diff --git a/types/workbox-core/clientsClaim.d.ts b/types/workbox-core/clientsClaim.d.ts new file mode 100644 index 0000000000..006f661047 --- /dev/null +++ b/types/workbox-core/clientsClaim.d.ts @@ -0,0 +1 @@ +export function clientsClaim(): void; diff --git a/types/workbox-core/index.d.ts b/types/workbox-core/index.d.ts new file mode 100644 index 0000000000..26f4ad0e80 --- /dev/null +++ b/types/workbox-core/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for workbox-core 4.3 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export * from "./cacheNames"; +export * from "./clientsClaim"; +export * from "./registerQuotaErrorCallback"; +export * from "./setCacheNameDetails"; +export * from "./skipWaiting"; + +export { WorkboxPlugin } from "./types/WorkboxPlugin"; diff --git a/types/workbox-core/registerQuotaErrorCallback.d.ts b/types/workbox-core/registerQuotaErrorCallback.d.ts new file mode 100644 index 0000000000..c02222f6cd --- /dev/null +++ b/types/workbox-core/registerQuotaErrorCallback.d.ts @@ -0,0 +1 @@ +export function registerQuotaErrorCallback(callback: () => void): void; diff --git a/types/workbox-core/setCacheNameDetails.d.ts b/types/workbox-core/setCacheNameDetails.d.ts new file mode 100644 index 0000000000..4d72039eb0 --- /dev/null +++ b/types/workbox-core/setCacheNameDetails.d.ts @@ -0,0 +1,9 @@ +export interface CacheNameDetails { + googleAnalytics: string; + precache: string; + prefix: string; + runtime: string; + suffix: string; +} + +export function setCacheNameDetails(details: Partial): void; diff --git a/types/workbox-core/skipWaiting.d.ts b/types/workbox-core/skipWaiting.d.ts new file mode 100644 index 0000000000..4588a26654 --- /dev/null +++ b/types/workbox-core/skipWaiting.d.ts @@ -0,0 +1 @@ +export function skipWaiting(): void; diff --git a/types/workbox-core/tsconfig.json b/types/workbox-core/tsconfig.json new file mode 100644 index 0000000000..a003697473 --- /dev/null +++ b/types/workbox-core/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cacheNames.d.ts", + "clientsClaim.d.ts", + "registerQuotaErrorCallback.d.ts", + "setCacheNameDetails.d.ts", + "skipWaiting.d.ts", + "types/WorkboxPlugin.d.ts", + "workbox-core-tests.ts" + ] +} diff --git a/types/workbox-core/tslint.json b/types/workbox-core/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/workbox-core/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/workbox-core/types/WorkboxPlugin.d.ts b/types/workbox-core/types/WorkboxPlugin.d.ts new file mode 100644 index 0000000000..c5c1ffdd1e --- /dev/null +++ b/types/workbox-core/types/WorkboxPlugin.d.ts @@ -0,0 +1,80 @@ +export interface WorkboxPlugin { + cacheDidUpdate?: CacheDidUpdateCallback; + cacheKeyWillBeUsed?: CacheKeyWillBeUsedCallback; + cacheWillUpdate?: CacheWillUpdateCallback; + cachedResponseWillBeUsed?: CachedResponseWillBeUsedCallback; + fetchDidFail?: FetchDidFailCallback; + fetchDidSucceed?: FetchDidSucceedCallback; + requestWillFetch?: RequestWillFetchCallback; +} + +export interface CacheDidUpdateCallback { + (param: CacheDidUpdateCallbackParam): Promise; +} + +export interface CacheDidUpdateCallbackParam { + cacheName: string; + newResponse: Response; + oldResponse?: Response | null; + request: Request; + event?: Event; +} + +export interface CacheKeyWillBeUsedCallback { + (param: CacheKeyWillBeUsedCallbackParam): Promise; +} + +export interface CacheKeyWillBeUsedCallbackParam { + request: Request; + mode: string; +} + +export interface CacheWillUpdateCallback { + (param: CacheWillUpdateCallbackParamParam): Promise; +} + +export interface CacheWillUpdateCallbackParamParam { + request: Request; + response: Response; + event?: ExtendableEvent; +} + +export interface CachedResponseWillBeUsedCallback { + (param: CachedResponseWillBeUsedCallbackParam): Promise; +} + +export interface CachedResponseWillBeUsedCallbackParam { + cacheName: string; + cachedResponse?: Response; + matchOptions?: CacheQueryOptions; + request: Request; + event?: ExtendableEvent; +} + +export interface FetchDidFailCallback { + (param: FetchDidFailCallbackParam): Promise; +} + +export interface FetchDidFailCallbackParam { + error: Error; + originalRequest: Request; + request: Request; + event?: ExtendableEvent; +} + +export interface FetchDidSucceedCallback { + (param: FetchDidSucceedCallbackParam): Promise; +} + +export interface FetchDidSucceedCallbackParam { + request: Request; + response: Response; +} + +export interface RequestWillFetchCallback { + (param: RequestWillFetchCallbackParam): Promise; +} + +export interface RequestWillFetchCallbackParam { + request: Request; +} diff --git a/types/workbox-core/workbox-core-tests.ts b/types/workbox-core/workbox-core-tests.ts new file mode 100644 index 0000000000..62a792a721 --- /dev/null +++ b/types/workbox-core/workbox-core-tests.ts @@ -0,0 +1,76 @@ +/* tslint:disable:comment-format no-namespace */ + +"use strict"; + +import { + CacheNameDetails, + cacheNames, + clientsClaim, + registerQuotaErrorCallback, + setCacheNameDetails, + skipWaiting, +} from "workbox-core"; + +//============================================================================== +// WorkboxCore.cacheNames +//============================================================================== + +export namespace CacheNamesTest { + // $ExpectType CacheNames + cacheNames; + + // $ExpectType string + cacheNames.googleAnalytics; + + // $ExpectType string + cacheNames.precache; + + // $ExpectType string + cacheNames.prefix; + + // $ExpectType string + cacheNames.runtime; + + // $ExpectType string + cacheNames.suffix; +} + +//============================================================================== +// WorkboxCore.clientsClaim +//============================================================================== + +export namespace ClientsClaimTest { + // $ExpectType void + clientsClaim(); +} + +//============================================================================== +// WorkboxCore.registerQuotaErrorCallback +//============================================================================== + +export namespace RegisterQuotaErrorCallbackTest { + declare const callback: () => void; + + // $ExpectType void + registerQuotaErrorCallback(callback); +} + +//============================================================================== +// WorkboxCore.setCacheNameDetails +//============================================================================== + +export namespace SetCacheNameDetailsTest { + declare const details: CacheNameDetails; + + // $ExpectType void + setCacheNameDetails(details); +} + +//============================================================================== +// WorkboxCore.skipWaiting +//============================================================================== + +export namespace SkipWaitingTest { + // $ExpectType void + skipWaiting(); +} diff --git a/types/workbox-expiration/CacheExpiration.d.ts b/types/workbox-expiration/CacheExpiration.d.ts new file mode 100644 index 0000000000..22b04cfe92 --- /dev/null +++ b/types/workbox-expiration/CacheExpiration.d.ts @@ -0,0 +1,12 @@ +export class CacheExpiration { + constructor(cacheName: string, config?: CacheExpirationConfig); + delete(): Promise; + expireEntries(): Promise; + isURLExpired(url: string): Promise; + updateTimestamp(url: string): Promise; +} + +export interface CacheExpirationConfig { + maxAgeSeconds?: number; + maxEntries?: number; +} diff --git a/types/workbox-expiration/Plugin.d.ts b/types/workbox-expiration/Plugin.d.ts new file mode 100644 index 0000000000..8c1454c467 --- /dev/null +++ b/types/workbox-expiration/Plugin.d.ts @@ -0,0 +1,18 @@ +import { + CacheDidUpdateCallback, + CachedResponseWillBeUsedCallback, + WorkboxPlugin, +} from "workbox-core/types/WorkboxPlugin"; + +export class Plugin implements WorkboxPlugin { + constructor(config?: ExpirationPluginConfig); + cacheDidUpdate: CacheDidUpdateCallback; + cachedResponseWillBeUsed: CachedResponseWillBeUsedCallback; + deleteCacheAndMetadata(): Promise; +} + +export interface ExpirationPluginConfig { + maxAgeSeconds?: number; + maxEntries?: number; + purgeOnQuotaError?: boolean; +} diff --git a/types/workbox-expiration/index.d.ts b/types/workbox-expiration/index.d.ts new file mode 100644 index 0000000000..3d62de160e --- /dev/null +++ b/types/workbox-expiration/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for workbox-expiration 4.3 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export * from "./CacheExpiration"; +export * from "./Plugin"; diff --git a/types/workbox-expiration/tsconfig.json b/types/workbox-expiration/tsconfig.json new file mode 100644 index 0000000000..8b23d30ff7 --- /dev/null +++ b/types/workbox-expiration/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "CacheExpiration.d.ts", + "Plugin.d.ts", + "workbox-expiration-tests.ts" + ] +} diff --git a/types/workbox-expiration/tslint.json b/types/workbox-expiration/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/workbox-expiration/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/workbox-expiration/workbox-expiration-tests.ts b/types/workbox-expiration/workbox-expiration-tests.ts new file mode 100644 index 0000000000..0ddb080f68 --- /dev/null +++ b/types/workbox-expiration/workbox-expiration-tests.ts @@ -0,0 +1,57 @@ +/* tslint:disable:comment-format no-namespace */ + +"use strict"; + +import { + CacheExpiration, + CacheExpirationConfig, + ExpirationPluginConfig, + Plugin, +} from "workbox-expiration"; + +//============================================================================== +// WorkboxExpiration.CacheExpiration +//============================================================================== + +export namespace CacheExpirationTest { + declare const cacheName: string; + declare const config: CacheExpirationConfig; + + // $ExpectType CacheExpiration + new CacheExpiration(cacheName); + // $ExpectType CacheExpiration + new CacheExpiration(cacheName, config); + + declare const expiration: CacheExpiration; + declare const cachedURL: string; + + // $ExpectType Promise + expiration.delete(); + + // $ExpectType Promise + expiration.expireEntries(); + + // $ExpectType Promise + expiration.isURLExpired(cachedURL); + + // $ExpectType Promise + expiration.updateTimestamp(cachedURL); +} + +//============================================================================== +// WorkboxExpiration.Plugin +//============================================================================== + +export namespace ExpirationPluginTest { + declare const config: ExpirationPluginConfig; + + // $ExpectType Plugin + new Plugin(); + // $ExpectType Plugin + new Plugin(config); + + declare const plugin: Plugin; + + // $ExpectType Promise + plugin.deleteCacheAndMetadata(); +} diff --git a/types/workbox-google-analytics/index.d.ts b/types/workbox-google-analytics/index.d.ts new file mode 100644 index 0000000000..37b67a3ff6 --- /dev/null +++ b/types/workbox-google-analytics/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for workbox-google-analytics 4.3 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export * from "./initialize"; diff --git a/types/workbox-google-analytics/initialize.d.ts b/types/workbox-google-analytics/initialize.d.ts new file mode 100644 index 0000000000..4a122bb4b9 --- /dev/null +++ b/types/workbox-google-analytics/initialize.d.ts @@ -0,0 +1,7 @@ +export function initialize(options?: InitializeOptions): void; + +export interface InitializeOptions { + cacheName?: string; + parameterOverrides?: Record; + hitFilter?: (params: URLSearchParams) => void; +} diff --git a/types/workbox-google-analytics/tsconfig.json b/types/workbox-google-analytics/tsconfig.json new file mode 100644 index 0000000000..c34b15873d --- /dev/null +++ b/types/workbox-google-analytics/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "initialize.d.ts", + "workbox-google-analytics-tests.ts" + ] +} diff --git a/types/workbox-google-analytics/tslint.json b/types/workbox-google-analytics/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/workbox-google-analytics/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/workbox-google-analytics/workbox-google-analytics-tests.ts b/types/workbox-google-analytics/workbox-google-analytics-tests.ts new file mode 100644 index 0000000000..f2a6c3f4f9 --- /dev/null +++ b/types/workbox-google-analytics/workbox-google-analytics-tests.ts @@ -0,0 +1,21 @@ +/* tslint:disable:comment-format no-namespace */ + +"use strict"; + +import { + InitializeOptions, + initialize, +} from "workbox-google-analytics"; + +//============================================================================== +// WorkboxGoogleAnalytics.initialize +//============================================================================== + +export namespace InitializeTest { + declare const options: InitializeOptions; + + // $ExpectType void + initialize(); + // $ExpectType void + initialize(options); +} diff --git a/types/workbox-navigation-preload/disable.d.ts b/types/workbox-navigation-preload/disable.d.ts new file mode 100644 index 0000000000..4435d5fd89 --- /dev/null +++ b/types/workbox-navigation-preload/disable.d.ts @@ -0,0 +1 @@ +export function disable(): void; diff --git a/types/workbox-navigation-preload/enable.d.ts b/types/workbox-navigation-preload/enable.d.ts new file mode 100644 index 0000000000..24ca3c8d00 --- /dev/null +++ b/types/workbox-navigation-preload/enable.d.ts @@ -0,0 +1 @@ +export function enable(headerValue?: string): void; diff --git a/types/workbox-navigation-preload/index.d.ts b/types/workbox-navigation-preload/index.d.ts new file mode 100644 index 0000000000..2e00b2d543 --- /dev/null +++ b/types/workbox-navigation-preload/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for workbox-navigation-preload 4.3 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export * from "./disable"; +export * from "./enable"; +export * from "./isSupported"; diff --git a/types/workbox-navigation-preload/isSupported.d.ts b/types/workbox-navigation-preload/isSupported.d.ts new file mode 100644 index 0000000000..d67c72b658 --- /dev/null +++ b/types/workbox-navigation-preload/isSupported.d.ts @@ -0,0 +1 @@ +export function isSupported(): boolean; diff --git a/types/workbox-navigation-preload/tsconfig.json b/types/workbox-navigation-preload/tsconfig.json new file mode 100644 index 0000000000..d9762739cf --- /dev/null +++ b/types/workbox-navigation-preload/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "disable.d.ts", + "enable.d.ts", + "isSupported.d.ts", + "workbox-navigation-preload-tests.ts" + ] +} diff --git a/types/workbox-navigation-preload/tslint.json b/types/workbox-navigation-preload/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/workbox-navigation-preload/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/workbox-navigation-preload/workbox-navigation-preload-tests.ts b/types/workbox-navigation-preload/workbox-navigation-preload-tests.ts new file mode 100644 index 0000000000..1f7e0ffea1 --- /dev/null +++ b/types/workbox-navigation-preload/workbox-navigation-preload-tests.ts @@ -0,0 +1,42 @@ +/* tslint:disable:comment-format no-namespace */ + +"use strict"; + +import { + disable, + enable, + isSupported, +} from "workbox-navigation-preload"; + +declare const headerValue: string; + +//============================================================================== +// WorkboxNavigationPreload.disable +//============================================================================== + +export namespace DisableTest { + // $ExpectType void + disable(); +} + +//============================================================================== +// WorkboxNavigationPreload.enable +//============================================================================== + +export namespace EnableTest { + declare const header: string; + + // $ExpectType void + enable(); + // $ExpectType void + enable(header); +} + +//============================================================================== +// WorkboxNavigationPreload.isSupported +//============================================================================== + +export namespace IsSupportedTest { + // $ExpectType boolean + isSupported(); +} diff --git a/types/workbox-precaching/PrecacheController.d.ts b/types/workbox-precaching/PrecacheController.d.ts new file mode 100644 index 0000000000..080a808589 --- /dev/null +++ b/types/workbox-precaching/PrecacheController.d.ts @@ -0,0 +1,22 @@ +import { WorkboxPlugin } from "workbox-core/types/WorkboxPlugin"; + +import { CleanupResult } from "./types/CleanupResult"; +import { InstallResult } from "./types/InstallResult"; +import { PrecacheEntry } from "./types/PrecacheEntry"; + +export class PrecacheController { + constructor(cacheName?: string); + activate(): Promise; + addToCacheList(entries: Array): void; + getCacheKeyForURL(url: string): string; + getCachedURLs(): string[]; + getURLsToCacheKeys(): Record; + install(options?: PrecacheController.InstallOptions): Promise; +} + +export namespace PrecacheController { + interface InstallOptions { + event?: FetchEvent; + plugins?: WorkboxPlugin[]; + } +} diff --git a/types/workbox-precaching/addPlugins.d.ts b/types/workbox-precaching/addPlugins.d.ts new file mode 100644 index 0000000000..ec3c8c956b --- /dev/null +++ b/types/workbox-precaching/addPlugins.d.ts @@ -0,0 +1,3 @@ +import { WorkboxPlugin } from "workbox-core/types/WorkboxPlugin"; + +export function addPlugins(newPlugins: WorkboxPlugin[]): void; diff --git a/types/workbox-precaching/addRoute.d.ts b/types/workbox-precaching/addRoute.d.ts new file mode 100644 index 0000000000..745f1aacef --- /dev/null +++ b/types/workbox-precaching/addRoute.d.ts @@ -0,0 +1,5 @@ +import { FetchListenerOptions } from "./types/FetchListenerOptions"; + +export function addRoute(options?: FetchListenerOptions): void; + +export * from "./types/FetchListenerOptions"; diff --git a/types/workbox-precaching/cleanupOutdatedCaches.d.ts b/types/workbox-precaching/cleanupOutdatedCaches.d.ts new file mode 100644 index 0000000000..fa881efd78 --- /dev/null +++ b/types/workbox-precaching/cleanupOutdatedCaches.d.ts @@ -0,0 +1 @@ +export function cleanupOutdatedCaches(): void; diff --git a/types/workbox-precaching/getCacheKeyForURL.d.ts b/types/workbox-precaching/getCacheKeyForURL.d.ts new file mode 100644 index 0000000000..024479db86 --- /dev/null +++ b/types/workbox-precaching/getCacheKeyForURL.d.ts @@ -0,0 +1 @@ +export function getCacheKeyForURL(url: string): string; diff --git a/types/workbox-precaching/index.d.ts b/types/workbox-precaching/index.d.ts new file mode 100644 index 0000000000..f1e820cb39 --- /dev/null +++ b/types/workbox-precaching/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for workbox-precaching 4.3 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export * from "./PrecacheController"; +export * from "./addPlugins"; +export { addRoute } from "./addRoute"; +export * from "./cleanupOutdatedCaches"; +export * from "./getCacheKeyForURL"; +export { precache } from "./precache"; +export { precacheAndRoute } from "./precacheAndRoute"; + +export * from "./types/CleanupResult"; +export * from "./types/FetchListenerOptions"; +export * from "./types/PrecacheEntry"; +export * from "./types/URLManipulation"; diff --git a/types/workbox-precaching/precache.d.ts b/types/workbox-precaching/precache.d.ts new file mode 100644 index 0000000000..65df7f35a0 --- /dev/null +++ b/types/workbox-precaching/precache.d.ts @@ -0,0 +1,5 @@ +import { PrecacheEntry } from "./types/PrecacheEntry"; + +export function precache(entries: Array): void; + +export * from "./types/PrecacheEntry"; diff --git a/types/workbox-precaching/precacheAndRoute.d.ts b/types/workbox-precaching/precacheAndRoute.d.ts new file mode 100644 index 0000000000..6fb54b51f3 --- /dev/null +++ b/types/workbox-precaching/precacheAndRoute.d.ts @@ -0,0 +1,6 @@ +import { FetchListenerOptions } from "./types/FetchListenerOptions"; +import { PrecacheEntry } from "./types/PrecacheEntry"; + +export function precacheAndRoute(entries: Array, options?: FetchListenerOptions): void; + +export * from "./types/PrecacheEntry"; diff --git a/types/workbox-precaching/tsconfig.json b/types/workbox-precaching/tsconfig.json new file mode 100644 index 0000000000..cf0937f208 --- /dev/null +++ b/types/workbox-precaching/tsconfig.json @@ -0,0 +1,36 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "PrecacheController.d.ts", + "addPlugins.d.ts", + "addRoute.d.ts", + "cleanupOutdatedCaches.d.ts", + "getCacheKeyForURL.d.ts", + "precache.d.ts", + "precacheAndRoute.d.ts", + "types/CleanupResult.d.ts", + "types/FetchListenerOptions.d.ts", + "types/InstallResult.d.ts", + "types/PrecacheEntry.d.ts", + "types/URLManipulation.d.ts", + "workbox-precaching-tests.ts" + ] +} diff --git a/types/workbox-precaching/tslint.json b/types/workbox-precaching/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/workbox-precaching/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/workbox-precaching/types/CleanupResult.d.ts b/types/workbox-precaching/types/CleanupResult.d.ts new file mode 100644 index 0000000000..b2611d1c6a --- /dev/null +++ b/types/workbox-precaching/types/CleanupResult.d.ts @@ -0,0 +1,3 @@ +export interface CleanupResult { + deletedCacheRequests: string[]; +} diff --git a/types/workbox-precaching/types/FetchListenerOptions.d.ts b/types/workbox-precaching/types/FetchListenerOptions.d.ts new file mode 100644 index 0000000000..37897cba57 --- /dev/null +++ b/types/workbox-precaching/types/FetchListenerOptions.d.ts @@ -0,0 +1,8 @@ +import { URLManipulation } from "./URLManipulation"; + +export interface FetchListenerOptions { + cleanURLs?: boolean; + directoryIndex?: string; + ignoreURLParametersMatching?: RegExp[]; + urlManipulation?: URLManipulation; +} diff --git a/types/workbox-precaching/types/InstallResult.d.ts b/types/workbox-precaching/types/InstallResult.d.ts new file mode 100644 index 0000000000..b475356878 --- /dev/null +++ b/types/workbox-precaching/types/InstallResult.d.ts @@ -0,0 +1,4 @@ +export interface InstallResult { + notUpdatedURLs: string[]; + updatedURLs: string[]; +} diff --git a/types/workbox-precaching/types/PrecacheEntry.d.ts b/types/workbox-precaching/types/PrecacheEntry.d.ts new file mode 100644 index 0000000000..5a29ee32a5 --- /dev/null +++ b/types/workbox-precaching/types/PrecacheEntry.d.ts @@ -0,0 +1,5 @@ +export interface PrecacheEntry { + url: string; + // integrity?: string; + revision?: string; +} diff --git a/types/workbox-precaching/types/URLManipulation.d.ts b/types/workbox-precaching/types/URLManipulation.d.ts new file mode 100644 index 0000000000..531bf13383 --- /dev/null +++ b/types/workbox-precaching/types/URLManipulation.d.ts @@ -0,0 +1 @@ +export type URLManipulation = (url: { url: URL }) => URL[]; diff --git a/types/workbox-precaching/workbox-precaching-tests.ts b/types/workbox-precaching/workbox-precaching-tests.ts new file mode 100644 index 0000000000..f3c8e03a4e --- /dev/null +++ b/types/workbox-precaching/workbox-precaching-tests.ts @@ -0,0 +1,123 @@ +/* tslint:disable:comment-format no-namespace */ + +"use strict"; + +import { WorkboxPlugin } from "workbox-core/types/WorkboxPlugin"; +import { + FetchListenerOptions, + PrecacheController, + PrecacheEntry, + addPlugins, + addRoute, + cleanupOutdatedCaches, + getCacheKeyForURL, + precache, + precacheAndRoute +} from "workbox-precaching"; + +//============================================================================== +// WorkboxPrecaching.PrecacheController +//============================================================================== + +export namespace PrecacheControllerTest { + declare const cacheName: string; + + // $ExpectType PrecacheController + new PrecacheController(); + // $ExpectType PrecacheController + new PrecacheController(cacheName); + + declare const controller: PrecacheController; + declare const cacheEntries: Array; + declare const cachedURL: string; + declare const installOptions: PrecacheController.InstallOptions; + + // $ExpectType Promise + controller.activate(); + + // $ExpectType void + controller.addToCacheList(cacheEntries); + + // $ExpectType string + controller.getCacheKeyForURL(cachedURL); + + // $ExpectType string[] + controller.getCachedURLs(); + + // $ExpectType Record + controller.getURLsToCacheKeys(); + + // $ExpectType Promise + controller.install(); + // $ExpectType Promise + controller.install(installOptions); +} + +//============================================================================== +// WorkboxPrecaching.addPlugins +//============================================================================== + +export namespace AddPluginsTest { + declare const plugins: WorkboxPlugin[]; + + // $ExpectType void + addPlugins(plugins); +} + +//============================================================================== +// WorkboxPrecaching.addRoute +//============================================================================== + +export namespace AddRouteTest { + declare const options: FetchListenerOptions; + + // $ExpectType void + addRoute(); + // $ExpectType void + addRoute(options); +} + +//============================================================================== +// WorkboxPrecaching.cleanupOutdatedCaches +//============================================================================== + +export namespace CleanupOutdatedCachesTest { + // $ExpectType void + cleanupOutdatedCaches(); +} + +//============================================================================== +// WorkboxPrecaching.getCacheKeyForURL +//============================================================================== + +export namespace GetCacheKeyForURLTest { + declare const url: string; + + // $ExpectType string + getCacheKeyForURL(url); +} + +//============================================================================== +// WorkboxPrecaching.precache +//============================================================================== + +export namespace PrecacheTest { + declare const entries: Array; + + // $ExpectType void + precache(entries); +} + +//============================================================================== +// WorkboxPrecaching.precacheAndRoute +//============================================================================== + +export namespace PrecacheAndRoute { + declare const entries: Array; + declare const options: FetchListenerOptions; + + // $ExpectType void + precacheAndRoute(entries); + // $ExpectType void + precacheAndRoute(entries, options); +} diff --git a/types/workbox-range-requests/Plugin.d.ts b/types/workbox-range-requests/Plugin.d.ts new file mode 100644 index 0000000000..e40fd84176 --- /dev/null +++ b/types/workbox-range-requests/Plugin.d.ts @@ -0,0 +1,6 @@ +import { CachedResponseWillBeUsedCallback, WorkboxPlugin } from "workbox-core/types/WorkboxPlugin"; + +export class Plugin implements WorkboxPlugin { + constructor(); + cachedResponseWillBeUsed: CachedResponseWillBeUsedCallback; +} diff --git a/types/workbox-range-requests/createPartialResponse.d.ts b/types/workbox-range-requests/createPartialResponse.d.ts new file mode 100644 index 0000000000..bbbec6688a --- /dev/null +++ b/types/workbox-range-requests/createPartialResponse.d.ts @@ -0,0 +1 @@ +export function createPartialResponse(request: Request, originalResponse: Response): Promise; diff --git a/types/workbox-range-requests/index.d.ts b/types/workbox-range-requests/index.d.ts new file mode 100644 index 0000000000..2e4872a8bd --- /dev/null +++ b/types/workbox-range-requests/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for workbox-range-requests 4.3 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export * from "./Plugin"; +export * from "./createPartialResponse"; diff --git a/types/workbox-range-requests/tsconfig.json b/types/workbox-range-requests/tsconfig.json new file mode 100644 index 0000000000..c1f02965b5 --- /dev/null +++ b/types/workbox-range-requests/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "Plugin.d.ts", + "createPartialResponse.d.ts", + "workbox-range-requests-tests.ts" + ] +} diff --git a/types/workbox-range-requests/tslint.json b/types/workbox-range-requests/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/workbox-range-requests/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/workbox-range-requests/workbox-range-requests-tests.ts b/types/workbox-range-requests/workbox-range-requests-tests.ts new file mode 100644 index 0000000000..b4ac09f07f --- /dev/null +++ b/types/workbox-range-requests/workbox-range-requests-tests.ts @@ -0,0 +1,29 @@ +/* tslint:disable:comment-format no-namespace */ + +"use strict"; + +import { + Plugin, + createPartialResponse, +} from "workbox-range-requests"; + +//============================================================================== +// WorkboxRangeRequests.Plugin +//============================================================================== + +export namespace RangeRequestsPluginTest { + // $ExpectType Plugin + new Plugin(); +} + +//============================================================================== +// WorkboxRangeRequests.createPartialResponse +//============================================================================== + +export namespace CreatePartialResponseTest { + declare const request: Request; + declare const response: Response; + + // $ExpectType Promise + createPartialResponse(request, response); +} diff --git a/types/workbox-routing/NavigationRoute.d.ts b/types/workbox-routing/NavigationRoute.d.ts new file mode 100644 index 0000000000..df07094d46 --- /dev/null +++ b/types/workbox-routing/NavigationRoute.d.ts @@ -0,0 +1,13 @@ +import { Route } from "./Route"; + +import { HTTPMethod } from "./types/HTTPMethod"; +import { RouteHandler } from "./types/RouteHandler"; + +export class NavigationRoute extends Route { + constructor(handler: RouteHandler, options?: NavigationRouteOptions); +} + +export interface NavigationRouteOptions { + whitelist?: RegExp[]; + blacklist?: RegExp[]; +} diff --git a/types/workbox-routing/RegExpRoute.d.ts b/types/workbox-routing/RegExpRoute.d.ts new file mode 100644 index 0000000000..32c3580f54 --- /dev/null +++ b/types/workbox-routing/RegExpRoute.d.ts @@ -0,0 +1,8 @@ +import { Route } from "./Route"; + +import { HTTPMethod } from "./types/HTTPMethod"; +import { RouteHandler } from "./types/RouteHandler"; + +export class RegExpRoute extends Route { + constructor(regExp: RegExp, handler: RouteHandler, method?: HTTPMethod); +} diff --git a/types/workbox-routing/Route.d.ts b/types/workbox-routing/Route.d.ts new file mode 100644 index 0000000000..a5b9ec785c --- /dev/null +++ b/types/workbox-routing/Route.d.ts @@ -0,0 +1,10 @@ +import { HTTPMethod } from "./types/HTTPMethod"; +import { RouteHandler } from "./types/RouteHandler"; +import { RouteMatchCallback } from "./types/RouteMatchCallback"; + +export class Route { + readonly handler: RouteHandler; + readonly match: RouteMatchCallback; + readonly method: HTTPMethod; + constructor(match: RouteMatchCallback, handler: RouteHandler, method?: HTTPMethod); +} diff --git a/types/workbox-routing/Router.d.ts b/types/workbox-routing/Router.d.ts new file mode 100644 index 0000000000..74099e80cb --- /dev/null +++ b/types/workbox-routing/Router.d.ts @@ -0,0 +1,39 @@ +import { Route } from "./Route"; + +import { HTTPMethod } from "./types/HTTPMethod"; +import { RouteHandler } from "./types/RouteHandler"; + +export class Router { + constructor(); + readonly routes: Map; + addCacheListener(): void; + addFetchListener(): void; + findMatchingRoute(options: Router.FindMatchingRouteOptions): {} | Router.FindMatchingRouteReturn; + handleRequest(options: Router.HandleRequestOptions): Promise; + registerRoute(route: Route): void; + setCatchHandler(handler: RouteHandler): void; + setDefaultHandler(handler: RouteHandler): void; + unregisterRoute(route: Route): void; +} + +export namespace Router { + interface FindMatchingRouteOptions extends HandleRequestOptions { + url: URL; + } + + interface FindMatchingRouteReturn { + params: any; // Exclude | undefined; <-- TypeScript 2.8 + route: Route; + } + + interface HandleRequestOptions { + request: Request; + event?: FetchEvent; + } +} + +export {}; + +// type Exclude = T extends U ? never : T; + +// type Falsy = false | 0 | "" | null | undefined ; diff --git a/types/workbox-routing/index.d.ts b/types/workbox-routing/index.d.ts new file mode 100644 index 0000000000..93f0c572a7 --- /dev/null +++ b/types/workbox-routing/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for workbox-routing 4.3 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export * from "./NavigationRoute"; +export * from "./RegExpRoute"; +export * from "./Route"; +export * from "./Router"; +export * from "./registerNavigationRoute"; +export * from "./registerRoute"; +export * from "./setCatchHandler"; +export * from "./setDefaultHandler"; + +export * from "./types/HTTPMethod"; +export * from "./types/RouteHandler"; +export * from "./types/RouteMatchCallback"; diff --git a/types/workbox-routing/registerNavigationRoute.d.ts b/types/workbox-routing/registerNavigationRoute.d.ts new file mode 100644 index 0000000000..7ed67cde4a --- /dev/null +++ b/types/workbox-routing/registerNavigationRoute.d.ts @@ -0,0 +1,7 @@ +import { NavigationRoute, NavigationRouteOptions } from "./NavigationRoute"; + +export function registerNavigationRoute(cachedAssetUrl: string, options?: RegisterNavigationRouteOptions): NavigationRoute; + +export interface RegisterNavigationRouteOptions extends NavigationRouteOptions { + cacheName?: string; +} diff --git a/types/workbox-routing/registerRoute.d.ts b/types/workbox-routing/registerRoute.d.ts new file mode 100644 index 0000000000..4fa08ac157 --- /dev/null +++ b/types/workbox-routing/registerRoute.d.ts @@ -0,0 +1,13 @@ +import { RegExpRoute } from "./RegExpRoute"; +import { Route } from "./Route"; + +import { HTTPMethod } from "./types/HTTPMethod"; +import { RouteHandler } from "./types/RouteHandler"; +import { RouteMatchCallback } from "./types/RouteMatchCallback"; + +export function registerRoute(capture: string, handler?: RouteHandler, method?: HTTPMethod): Route; +export function registerRoute(capture: RegExp, handler?: RouteHandler, method?: HTTPMethod): RegExpRoute; +export function registerRoute(capture: RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod): Route; +export function registerRoute(capture: RegisterRouteCapture, handler?: RouteHandler, method?: HTTPMethod): Route; + +export type RegisterRouteCapture = string | RegExp | RouteMatchCallback | Route; diff --git a/types/workbox-routing/setCatchHandler.d.ts b/types/workbox-routing/setCatchHandler.d.ts new file mode 100644 index 0000000000..0f0fbafaa5 --- /dev/null +++ b/types/workbox-routing/setCatchHandler.d.ts @@ -0,0 +1,3 @@ +import { RouteHandler } from "./types/RouteHandler"; + +export function setCatchHandler(handler: RouteHandler): void; diff --git a/types/workbox-routing/setDefaultHandler.d.ts b/types/workbox-routing/setDefaultHandler.d.ts new file mode 100644 index 0000000000..517da939dd --- /dev/null +++ b/types/workbox-routing/setDefaultHandler.d.ts @@ -0,0 +1,3 @@ +import { RouteHandler } from "./types/RouteHandler"; + +export function setDefaultHandler(handler: RouteHandler): void; diff --git a/types/workbox-routing/tsconfig.json b/types/workbox-routing/tsconfig.json new file mode 100644 index 0000000000..6b6dcc8f6a --- /dev/null +++ b/types/workbox-routing/tsconfig.json @@ -0,0 +1,35 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "NavigationRoute.d.ts", + "RegExpRoute.d.ts", + "Route.d.ts", + "Router.d.ts", + "registerNavigationRoute.d.ts", + "registerRoute.d.ts", + "setCatchHandler.d.ts", + "setDefaultHandler.d.ts", + "types/HTTPMethod.d.ts", + "types/RouteHandler.d.ts", + "types/RouteMatchCallback.d.ts", + "workbox-routing-tests.ts" + ] +} diff --git a/types/workbox-routing/tslint.json b/types/workbox-routing/tslint.json new file mode 100644 index 0000000000..01fb10795d --- /dev/null +++ b/types/workbox-routing/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-class": false, + "no-unnecessary-generics": false + } +} diff --git a/types/workbox-routing/types/HTTPMethod.d.ts b/types/workbox-routing/types/HTTPMethod.d.ts new file mode 100644 index 0000000000..267d4920f0 --- /dev/null +++ b/types/workbox-routing/types/HTTPMethod.d.ts @@ -0,0 +1 @@ +export type HTTPMethod = "DELETE" | "GET" | "HEAD" | "PATCH" | "POST" | "PUT"; diff --git a/types/workbox-routing/types/RouteHandler.d.ts b/types/workbox-routing/types/RouteHandler.d.ts new file mode 100644 index 0000000000..aa969ae32a --- /dev/null +++ b/types/workbox-routing/types/RouteHandler.d.ts @@ -0,0 +1,14 @@ +export type RouteHandler = RouteHandlerCallback | RouteHandlerObject; + +export interface RouteHandlerObject { + handle: RouteHandlerCallback; +} + +export type RouteHandlerCallback = (context: RouteHandlerCallbackContext) => Promise; + +export interface RouteHandlerCallbackContext { + url: URL; + event?: FetchEvent; + params?: string[] | Record; + request?: Request; +} diff --git a/types/workbox-routing/types/RouteMatchCallback.d.ts b/types/workbox-routing/types/RouteMatchCallback.d.ts new file mode 100644 index 0000000000..8ba0fd4c48 --- /dev/null +++ b/types/workbox-routing/types/RouteMatchCallback.d.ts @@ -0,0 +1,7 @@ +export type RouteMatchCallback = (options: RouteMatchCallbackOptions) => R; + +export interface RouteMatchCallbackOptions { + url: URL; + event?: ExtendableEvent; + request?: Request; +} diff --git a/types/workbox-routing/workbox-routing-tests.ts b/types/workbox-routing/workbox-routing-tests.ts new file mode 100644 index 0000000000..b6b2d0f446 --- /dev/null +++ b/types/workbox-routing/workbox-routing-tests.ts @@ -0,0 +1,164 @@ +/* tslint:disable:comment-format no-namespace */ + +"use strict"; + +import { + HTTPMethod, + NavigationRoute, + NavigationRouteOptions, + RegExpRoute, + RegisterNavigationRouteOptions, + RegisterRouteCapture, + Route, + RouteHandler, + RouteMatchCallback, + Router, + registerNavigationRoute, + registerRoute, + setCatchHandler, + setDefaultHandler +} from "workbox-routing"; + +declare const findMatchingRouteOptions: Router.FindMatchingRouteOptions; +declare const handleRequestOptions: Router.HandleRequestOptions; +declare const httpMethod: HTTPMethod; +declare const routeHandler: RouteHandler; +declare const routeMatchCallback: RouteMatchCallback; + +//============================================================================== +// WorkboxRouting.NavigationRoute +//============================================================================== + +export namespace NavigationRouteTest { + declare const handler: RouteHandler; + declare const options: NavigationRouteOptions; + + // $ExpectType NavigationRoute + new NavigationRoute(handler); + // $ExpectType NavigationRoute + new NavigationRoute(handler, options); +} + +//============================================================================== +// WorkboxRouting.RegExpRoute +//============================================================================== + +export namespace RegExpRouteTest { + declare const handler: RouteHandler; + declare const method: HTTPMethod; + declare const regExp: RegExp; + + // $ExpectType RegExpRoute + new RegExpRoute(regExp, handler); + // $ExpectType RegExpRoute + new RegExpRoute(regExp, handler, method); +} + +//============================================================================== +// WorkboxRouting.Route +//============================================================================== + +export namespace RouteTest { + declare const handler: RouteHandler; + declare const match: RouteMatchCallback; + declare const method: HTTPMethod; + + // $ExpectType Route + new Route(match, handler); + // $ExpectType Route + new Route(match, handler, method); +} + +//============================================================================== +// WorkboxRouting.Router +//============================================================================== + +export namespace RouterTest { + // $ExpectType Router + new Router(); + + declare const router: Router; + declare const findMatchingRouteOptions: Router.FindMatchingRouteOptions; + declare const handleRequestOptions: Router.HandleRequestOptions; + declare const route: Route; + + // $ExpectType Map[]> + router.routes; + + // $ExpectType void + router.addCacheListener(); + + // $ExpectType void + router.addFetchListener(); + + // $ExpectType {} | FindMatchingRouteReturn + router.findMatchingRoute(findMatchingRouteOptions); + + // $ExpectType Promise + router.handleRequest(handleRequestOptions); + + // $ExpectType void + router.registerRoute(route); + + // $ExpectType void + router.setCatchHandler(routeHandler); + + // $ExpectType void + router.setDefaultHandler(routeHandler); + + // $ExpectType void + router.unregisterRoute(route); +} + +//============================================================================== +// WorkboxRouting.registerRoute +//============================================================================== + +export namespace RegisterNavigationRouteTest { + declare const url: string; + declare const options: RegisterNavigationRouteOptions; + + // $ExpectType NavigationRoute + registerNavigationRoute(url); + // $ExpectType NavigationRoute + registerNavigationRoute(url, options); +} + +//============================================================================== +// WorkboxRouting.registerRoute +//============================================================================== + +export namespace RegisterRouteTest { + declare const capture: RegisterRouteCapture; + declare const handler: RouteHandler; + declare const method: HTTPMethod; + + // $ExpectType Route + registerRoute(capture); + // $ExpectType Route + registerRoute(capture, handler); + // $ExpectType Route + registerRoute(capture, handler, method); +} + +//============================================================================== +// WorkboxRouting.setCatchHandler +//============================================================================== + +export namespace SetCatchHandler { + declare const handler: RouteHandler; + + // $ExpectType void + setCatchHandler(handler); +} + +//============================================================================== +// WorkboxRouting.setDefaultHandler +//============================================================================== + +export namespace SetDefaultHandler { + declare const handler: RouteHandler; + + // $ExpectType void + setDefaultHandler(handler); +} diff --git a/types/workbox-strategies/CacheFirst.d.ts b/types/workbox-strategies/CacheFirst.d.ts new file mode 100644 index 0000000000..0191d8c715 --- /dev/null +++ b/types/workbox-strategies/CacheFirst.d.ts @@ -0,0 +1,20 @@ +import { WorkboxPlugin } from "workbox-core/types/WorkboxPlugin"; +import { + RouteHandlerCallback, + RouteHandlerObject, +} from "workbox-routing"; + +import { MakeRequestCallback } from "./types/MakeRequestCallback"; + +export class CacheFirst implements RouteHandlerObject { + constructor(options?: CacheFirstOptions); + handle: RouteHandlerCallback; + makeRequest: MakeRequestCallback; +} + +export interface CacheFirstOptions { + cacheName?: string; + fetchOptions?: RequestInit; + matchOptions?: CacheQueryOptions; + plugins?: WorkboxPlugin[]; +} diff --git a/types/workbox-strategies/CacheOnly.d.ts b/types/workbox-strategies/CacheOnly.d.ts new file mode 100644 index 0000000000..7fc0625ff6 --- /dev/null +++ b/types/workbox-strategies/CacheOnly.d.ts @@ -0,0 +1,19 @@ +import { WorkboxPlugin } from "workbox-core/types/WorkboxPlugin"; +import { + RouteHandlerCallback, + RouteHandlerObject, +} from "workbox-routing"; + +import { MakeRequestCallback } from "./types/MakeRequestCallback"; + +export class CacheOnly implements RouteHandlerObject { + constructor(options?: CacheOnlyOptions); + handle: RouteHandlerCallback; + makeRequest: MakeRequestCallback; +} + +export interface CacheOnlyOptions { + cacheName?: string; + matchOptions?: CacheQueryOptions; + plugins?: WorkboxPlugin[]; +} diff --git a/types/workbox-strategies/NetworkFirst.d.ts b/types/workbox-strategies/NetworkFirst.d.ts new file mode 100644 index 0000000000..fcf878254c --- /dev/null +++ b/types/workbox-strategies/NetworkFirst.d.ts @@ -0,0 +1,21 @@ +import { WorkboxPlugin } from "workbox-core/types/WorkboxPlugin"; +import { + RouteHandlerCallback, + RouteHandlerObject, +} from "workbox-routing"; + +import { MakeRequestCallback } from "./types/MakeRequestCallback"; + +export class NetworkFirst implements RouteHandlerObject { + constructor(options?: NetworkFirstOptions); + handle: RouteHandlerCallback; + makeRequest: MakeRequestCallback; +} + +export interface NetworkFirstOptions { + cacheName?: string; + fetchOptions?: RequestInit; + matchOptions?: CacheQueryOptions; + networkTimeoutSeconds?: number; + plugins?: WorkboxPlugin[]; +} diff --git a/types/workbox-strategies/NetworkOnly.d.ts b/types/workbox-strategies/NetworkOnly.d.ts new file mode 100644 index 0000000000..6d1ad8147b --- /dev/null +++ b/types/workbox-strategies/NetworkOnly.d.ts @@ -0,0 +1,19 @@ +import { WorkboxPlugin } from "workbox-core/types/WorkboxPlugin"; +import { + RouteHandlerCallback, + RouteHandlerObject, +} from "workbox-routing"; + +import { MakeRequestCallback } from "./types/MakeRequestCallback"; + +export class NetworkOnly implements RouteHandlerObject { + constructor(options?: NetworkOnlyOptions); + handle: RouteHandlerCallback; + makeRequest: MakeRequestCallback; +} + +export interface NetworkOnlyOptions { + cacheName?: string; + fetchOptions?: RequestInit; + plugins?: WorkboxPlugin[]; +} diff --git a/types/workbox-strategies/StaleWhileRevalidate.d.ts b/types/workbox-strategies/StaleWhileRevalidate.d.ts new file mode 100644 index 0000000000..c9b6957b13 --- /dev/null +++ b/types/workbox-strategies/StaleWhileRevalidate.d.ts @@ -0,0 +1,20 @@ +import { WorkboxPlugin } from "workbox-core/types/WorkboxPlugin"; +import { + RouteHandlerCallback, + RouteHandlerObject, +} from "workbox-routing"; + +import { MakeRequestCallback } from "./types/MakeRequestCallback"; + +export class StaleWhileRevalidate implements RouteHandlerObject { + constructor(options?: StaleWhileRevalidateOptions); + handle: RouteHandlerCallback; + makeRequest: MakeRequestCallback; +} + +export interface StaleWhileRevalidateOptions { + cacheName?: string; + fetchOptions?: RequestInit; + matchOptions?: CacheQueryOptions; + plugins?: WorkboxPlugin[]; +} diff --git a/types/workbox-strategies/index.d.ts b/types/workbox-strategies/index.d.ts new file mode 100644 index 0000000000..f520df9a10 --- /dev/null +++ b/types/workbox-strategies/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for workbox-strategies 4.3 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export * from "./CacheFirst"; +export * from "./CacheOnly"; +export * from "./NetworkFirst"; +export * from "./NetworkOnly"; +export * from "./StaleWhileRevalidate"; + +export * from "./types/MakeRequestCallback"; diff --git a/types/workbox-strategies/tsconfig.json b/types/workbox-strategies/tsconfig.json new file mode 100644 index 0000000000..5c01d42700 --- /dev/null +++ b/types/workbox-strategies/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "CacheFirst.d.ts", + "CacheOnly.d.ts", + "NetworkFirst.d.ts", + "NetworkOnly.d.ts", + "StaleWhileRevalidate.d.ts", + "types/MakeRequestCallback.d.ts", + "workbox-strategies-tests.ts" + ] +} diff --git a/types/workbox-strategies/tslint.json b/types/workbox-strategies/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/workbox-strategies/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/workbox-strategies/types/MakeRequestCallback.d.ts b/types/workbox-strategies/types/MakeRequestCallback.d.ts new file mode 100644 index 0000000000..96a4b20237 --- /dev/null +++ b/types/workbox-strategies/types/MakeRequestCallback.d.ts @@ -0,0 +1,8 @@ +export interface MakeRequestCallback { + (options: MakeRequestCallbackOptions): Promise; +} + +export interface MakeRequestCallbackOptions { + request: string | Request; + event?: ExtendableEvent; +} diff --git a/types/workbox-strategies/workbox-strategies-tests.ts b/types/workbox-strategies/workbox-strategies-tests.ts new file mode 100644 index 0000000000..36c0017167 --- /dev/null +++ b/types/workbox-strategies/workbox-strategies-tests.ts @@ -0,0 +1,112 @@ +/* tslint:disable:comment-format no-namespace */ + +"use strict"; + +import { + CacheFirst, + CacheFirstOptions, + CacheOnly, + CacheOnlyOptions, + MakeRequestCallbackOptions, + NetworkFirst, + NetworkFirstOptions, + NetworkOnly, + NetworkOnlyOptions, + StaleWhileRevalidate, + StaleWhileRevalidateOptions, +} from "workbox-strategies"; + +//============================================================================== +// WorkboxStrategies.CacheFirst +//============================================================================== + +export namespace CacheFirstTest { + declare const options: CacheFirstOptions; + + // $ExpectType CacheFirst + new CacheFirst(); + // $ExpectType CacheFirst + new CacheFirst(options); + + declare const cacheFirst: CacheFirst; + declare const makeRequestOptions: MakeRequestCallbackOptions; + + // $ExpectType Promise + cacheFirst.makeRequest(makeRequestOptions); +} + +//============================================================================== +// WorkboxStrategies.CacheOnly +//============================================================================== + +export namespace CacheOnlyTest { + declare const options: CacheOnlyOptions; + + // $ExpectType CacheOnly + new CacheOnly(); + // $ExpectType CacheOnly + new CacheOnly(options); + + declare const cacheOnly: CacheOnly; + declare const makeRequestOptions: MakeRequestCallbackOptions; + + // $ExpectType Promise + cacheOnly.makeRequest(makeRequestOptions); +} + +//============================================================================== +// WorkboxStrategies.NetworkFirst +//============================================================================== + +export namespace NetworkFirstTest { + declare const options: NetworkFirstOptions; + + // $ExpectType NetworkFirst + new NetworkFirst(); + // $ExpectType NetworkFirst + new NetworkFirst(options); + + declare const networkFirst: NetworkFirst; + declare const makeRequestOptions: MakeRequestCallbackOptions; + + // $ExpectType Promise + networkFirst.makeRequest(makeRequestOptions); +} + +//============================================================================== +// WorkboxStrategies.NetworkOnly +//============================================================================== + +export namespace NetworkOnlyTest { + declare const options: NetworkOnlyOptions; + + // $ExpectType NetworkOnly + new NetworkOnly(); + // $ExpectType NetworkOnly + new NetworkOnly(options); + + declare const networkOnly: NetworkOnly; + declare const makeRequestOptions: MakeRequestCallbackOptions; + + // $ExpectType Promise + networkOnly.makeRequest(makeRequestOptions); +} + +//============================================================================== +// WorkboxStrategies.StaleWhileRevalidateTest +//============================================================================== + +export namespace StaleWhileRevalidateTest { + declare const options: StaleWhileRevalidateOptions; + + // $ExpectType StaleWhileRevalidate + new StaleWhileRevalidate(); + // $ExpectType StaleWhileRevalidate + new StaleWhileRevalidate(options); + + declare const staleWhileRevalidate: StaleWhileRevalidate; + declare const makeRequestOptions: MakeRequestCallbackOptions; + + // $ExpectType Promise + staleWhileRevalidate.makeRequest(makeRequestOptions); +} diff --git a/types/workbox-streams/concatenate.d.ts b/types/workbox-streams/concatenate.d.ts new file mode 100644 index 0000000000..3b043bf621 --- /dev/null +++ b/types/workbox-streams/concatenate.d.ts @@ -0,0 +1,8 @@ +import { StreamSource } from "./types/StreamSource"; + +export function concatenate(sourcePromises: Array>): ConcatenateReturn; + +export interface ConcatenateReturn { + done: Promise; + stream: ReadableStream; +} diff --git a/types/workbox-streams/concatenateToResponse.d.ts b/types/workbox-streams/concatenateToResponse.d.ts new file mode 100644 index 0000000000..14497d7847 --- /dev/null +++ b/types/workbox-streams/concatenateToResponse.d.ts @@ -0,0 +1,8 @@ +import { StreamSource } from "./types/StreamSource"; + +export function concatenateToResponse(sourcePromises: Array>, headersInit?: HeadersInit): ConcatenateToResponseReturn; + +export interface ConcatenateToResponseReturn { + done: Promise; + response: Response; +} diff --git a/types/workbox-streams/index.d.ts b/types/workbox-streams/index.d.ts new file mode 100644 index 0000000000..541d3164d7 --- /dev/null +++ b/types/workbox-streams/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for workbox-streams 4.3 +// Project: https://github.com/GoogleChrome/workbox +// Definitions by: Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +export * from "./concatenate"; +export * from "./concatenateToResponse"; +export * from "./isSupported"; +export * from "./strategy"; + +export * from "./types/StreamSource"; diff --git a/types/workbox-streams/isSupported.d.ts b/types/workbox-streams/isSupported.d.ts new file mode 100644 index 0000000000..d67c72b658 --- /dev/null +++ b/types/workbox-streams/isSupported.d.ts @@ -0,0 +1 @@ +export function isSupported(): boolean; diff --git a/types/workbox-streams/strategy.d.ts b/types/workbox-streams/strategy.d.ts new file mode 100644 index 0000000000..11aa75eda3 --- /dev/null +++ b/types/workbox-streams/strategy.d.ts @@ -0,0 +1,10 @@ +import { + RouteHandlerCallback, + RouteHandlerCallbackContext +} from "workbox-routing"; + +import { StreamSource } from "./types/StreamSource"; + +export function strategy(sourceFunctions: StreamsHandlerCallback[], headersInit?: HeadersInit): RouteHandlerCallback; + +export type StreamsHandlerCallback = (options: RouteHandlerCallbackContext) => Promise | StreamSource; diff --git a/types/workbox-streams/tsconfig.json b/types/workbox-streams/tsconfig.json new file mode 100644 index 0000000000..70206380a5 --- /dev/null +++ b/types/workbox-streams/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es2015", + "webworker" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "concatenate.d.ts", + "concatenateToResponse.d.ts", + "isSupported.d.ts", + "strategy.d.ts", + "types/StreamSource.d.ts", + "workbox-streams-tests.ts" + ] +} diff --git a/types/workbox-streams/tslint.json b/types/workbox-streams/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/workbox-streams/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/workbox-streams/types/StreamSource.d.ts b/types/workbox-streams/types/StreamSource.d.ts new file mode 100644 index 0000000000..e7766a0380 --- /dev/null +++ b/types/workbox-streams/types/StreamSource.d.ts @@ -0,0 +1 @@ +export type StreamSource = Response | BodyInit | ReadableStream; diff --git a/types/workbox-streams/workbox-streams-tests.ts b/types/workbox-streams/workbox-streams-tests.ts new file mode 100644 index 0000000000..e5d8524b93 --- /dev/null +++ b/types/workbox-streams/workbox-streams-tests.ts @@ -0,0 +1,57 @@ +/* tslint:disable:comment-format no-namespace */ + +"use strict"; + +import { + StreamSource, + StreamsHandlerCallback, + concatenate, + concatenateToResponse, + isSupported, + strategy +} from "workbox-streams"; + +//============================================================================== +// WorkboxStreams.concatenate +//============================================================================== + +export namespace ConcatenateTest { + declare const sources: Array>; + + // $ExpectType ConcatenateReturn + concatenate(sources); +} + +//============================================================================== +// WorkboxStreams.concatenateToResponse +//============================================================================== + +export namespace ConcatenateToResponseTest { + declare const sources: Array>; + + // $ExpectType ConcatenateToResponseReturn + concatenateToResponse(sources); +} + +//============================================================================== +// WorkboxStreams.concatenate +//============================================================================== + +export namespace IsSupportedTest { + // $ExpectType boolean + isSupported(); +} + +//============================================================================== +// WorkboxStreams.strategy +//============================================================================== + +export namespace StrategyTest { + declare const headers: HeadersInit; + declare const sources: StreamsHandlerCallback[]; + + // $ExpectType RouteHandlerCallback + strategy(sources); + // $ExpectType RouteHandlerCallback + strategy(sources, headers); +} diff --git a/types/workbox-sw/index.d.ts b/types/workbox-sw/index.d.ts index 6069a0e4ec..c1f3cd08f0 100644 --- a/types/workbox-sw/index.d.ts +++ b/types/workbox-sw/index.d.ts @@ -1,2043 +1,48 @@ -// Type definitions for workbox-sw 4.2 +// Type definitions for workbox-sw 4.3 // Project: https://github.com/GoogleChrome/workbox // Definitions by: Frederik Wessberg +// Jason Kwok // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 -/** - * ===== BroadcastCacheUpdate ===== - */ - -interface BroadcastCacheUpdateOptions { - /** - * The name that will be used when creating the `BroadcastChannel`, - * which defaults to 'workbox' (the channel name used by the `workbox-window` package). - */ - channelName: string; - - /** - * A list of headers that will be used to determine whether the responses differ. - */ - headersToCheck: string[]; - - /** - * The amount of time to wait for a ready message from the window on navigation requests - * before sending the update. - */ - deferNoticationTimeout: number; -} - -interface NotifyIfUpdatedOptions { - /** - * Cached response to compare. - */ - oldResponse: Response; - - /** - * Possibly updated response to compare. - */ - newResponse: Response; - - /** - * The URL of the request. - */ - url: string; - - /** - * Name of the cache the responses belong to. This is included in the broadcast message. - */ - cacheName: string; - - /** - * An optional event that triggered this possible cache update. - */ - event?: Event; -} - -/** - * Uses the [Broadcast Channel API]{@link https://developers.google.com/web/updates/2016/09/broadcastchannel} - * to notify interested parties when a cached response has been updated. - * In browsers that do not support the Broadcast Channel API, the instance - * falls back to sending the update via `postMessage()` to all window clients. - * - * For efficiency's sake, the underlying response bodies are not compared; - * only specific response headers are checked. - */ -declare class BroadcastCacheUpdate { - /** - * Compare two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response) and send a message via the - * {@link https://developers.google.com/web/updates/2016/09/broadcastchannel|Broadcast Channel API} - * if they differ. - * Neither of the Responses can be {@link http://stackoverflow.com/questions/39109789|opaque}. - * - * @param {NotifyIfUpdatedOptions} options - * @returns {Promise} Resolves once the update is sent. - */ - notifyIfUpdated (options: NotifyIfUpdatedOptions): Promise; +import * as WorkboxBackgroundSync from "workbox-background-sync"; +import * as WorkboxBroadcastUpdate from "workbox-broadcast-update"; +import * as WorkboxCacheableResponse from "workbox-cacheable-response"; +import * as WorkboxCore from "workbox-core"; +import * as WorkboxExpiration from "workbox-expiration"; +import * as WorkboxGoogleAnalytics from "workbox-google-analytics"; +import * as WorkboxNavigationPreload from "workbox-navigation-preload"; +import * as WorkboxPrecaching from "workbox-precaching"; +import * as WorkboxRangeRequests from "workbox-range-requests"; +import * as WorkboxRouting from "workbox-routing"; +import * as WorkboxStrategies from "workbox-strategies"; +import * as WorkboxStreams from "workbox-streams"; + +declare global { + namespace workbox { + const backgroundSync: typeof WorkboxBackgroundSync; + const broadcastUpdate: typeof WorkboxBroadcastUpdate; + const cacheableResponse: typeof WorkboxCacheableResponse; + const core: typeof WorkboxCore; + const expiration: typeof WorkboxExpiration; + const googleAnalytics: typeof WorkboxGoogleAnalytics; + const navigationPreload: typeof WorkboxNavigationPreload; + const precaching: typeof WorkboxPrecaching; + const rangeRequests: typeof WorkboxRangeRequests; + const routing: typeof WorkboxRouting; + const strategies: typeof WorkboxStrategies; + const streams: typeof WorkboxStreams; + + function loadModule(moduleName: string): void; + + function setConfig(options?: WorkboxOptions): void; + + interface WorkboxOptions { + debug?: boolean; + modulePathCb?: ModulePathCallback; + modulePathPrefix?: string; + } + + type ModulePathCallback = (moduleName: string, debug: boolean) => string; + } } - -/** - * Construct a BroadcastCacheUpdate instance with a specific channelName to broadcast messages on - */ -interface BroadcastCacheUpdateConstructor { - /** - * Construct a BroadcastCacheUpdate instance with a specific `channelName` to - * broadcast messages on - * @param {Partial} options - * @return {BroadcastCacheUpdate} - */ - new (options?: Partial): BroadcastCacheUpdate; -} - -/** - * ===== CacheableResponse ===== - */ - -interface CacheableResponseOptions { - /** - * One or more status codes that a `Response` can have and be considered cacheable. - */ - statuses: number[]; - /** - * A mapping of header names and expected values that a `Response` can have and be considered cacheable. - * If multiple headers are provided, only one needs to be present. - */ - headers: Record; -} - -/** - * This class allows you to set up rules determining what status codes and/or headers need to be present in order for a - * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to be considered cacheable. - */ -declare class CacheableResponse { - /** - * Checks a response to see whether it's cacheable or not, based on this object's configuration. - * @param {Response} response - The response whose cacheability is being checked. - * @returns {boolean} `true` if the `Response` is cacheable, and `false` otherwise. - */ - isResponseCacheable (response: Response): boolean; -} - -interface CacheableResponseConstructor { - /** - * To construct a new CacheableResponse instance you must provide at least - * one of the `config` properties. - * - * If both `statuses` and `headers` are specified, then both conditions must - * be met for the `Response` to be considered cacheable. - * @param {Partial} options - * @return {CacheableResponse} - */ - new (options: Partial): CacheableResponse; -} - -/** - * ===== CacheExpiration ===== - */ - -interface CacheExpirationOptions { - /** - * The maximum number of entries to cache. - * Entries used the least will be removed as the maximum is reached. - */ - maxEntries: number; - - /** - * The maximum age of an entry before it's treated as stale and removed. - */ - maxAgeSeconds: number; -} - -/** - * The `CacheExpiration` class allows you define an expiration and / or limit on the number of responses - * stored in a [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache). - */ -declare class CacheExpiration { - /** - * Expires entries for the given cache and given criteria. - * @returns {Promise} - */ - expireEntries (): Promise; - - /** - * Can be used to check if a URL has expired or not before it's used. - * This requires a look up from IndexedDB, so can be slow. - * - * Note: This method will not remove the cached entry, call - * `expireEntries()` to remove indexedDB and Cache entries. - * @param {string} url - * @returns {Promise} - */ - isURLExpired (url: string): Promise; - - /** - * Update the timestamp for the given URL. This ensures the when - * removing entries based on maximum entries, most recently used - * is accurate or when expiring, the timestamp is up-to-date. - * @param {string} url - * @returns {Promise} - */ - updateTimestamp (url: string): Promise; - - /** - * Removes the IndexedDB object store used to keep track of - * cache expiration metadata. - * @return {Promise} - */ - delete (): Promise; -} - -interface CacheExpirationConstructor { - /** - * To construct a new CacheExpiration instance you must provide at least - * one of the `config` properties. - * @param {string} cacheName - Name of the cache to apply restrictions to. - * @param {Partial} config - * @return {CacheExpiration} - */ - new (cacheName: string, config: Partial): CacheExpiration; -} - -/** - * ===== Strategies ===== - */ - -interface CacheStrategyHandleOptions { - /** - * The request to run this strategy for. - */ - request: Request; - - /** - * The event that triggered the request. - */ - event: FetchEvent; -} - -interface CacheStrategyMakeRequestOptions { - /** - * Either a [`Request`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Request} object, - * or a string URL, corresponding to the request to be made. - */ - request: Request|string; - - /** - * If provided, `event.waitUntil()` will - * be called automatically to extend the service worker's lifetime. - */ - event?: FetchEvent; -} - -declare class CacheStrategy { - /** - * This method will perform a request strategy and follows an API that will work with the Workbox Router. - * @param {CacheStrategyHandleOptions} input - * @returns {Promise} - */ - handle (input: CacheStrategyHandleOptions): Promise; - - /** - * This method can be used to perform a make a standalone request outside the - * context of the Workbox Router. - * - * See "[Advanced Recipes](https://developers.google.com/web/tools/workbox/guides/advanced-recipes#make-requests)" - * for more usage information. - * @param {CacheStrategyMakeRequestOptions} input - * @returns {Promise} - */ - makeRequest (input: CacheStrategyMakeRequestOptions): Promise; -} - -/** - * ===== CacheOnly strategy ===== - */ - -interface CacheOnlyOptions { - /** - * Cache name to store and retrieve requests. Defaults to cache names provided by workbox-core. - */ - cacheName: string; - /** - * [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins} - * to use in conjunction with this caching strategy. - */ - plugins: Plugin[]; - - /** - * [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions) - */ - matchOptions: CacheQueryOptions; -} - -/** - * An implementation of a - * [cache-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-only} - * request strategy. - * - * This class is useful if you want to take advantage of any - * [Workbox plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}. - * - * If there is no cache match, this will throw a `WorkboxError` exception. - */ -declare class CacheOnly extends CacheStrategy { -} - -interface CacheOnlyConstructor { - /** - * Instantiates a new CacheOnly strategy - * @param {Partial} options - * @return {CacheOnly} - */ - new (options?: Partial): CacheOnly; -} - -/** - * ===== CacheFirst strategy ===== - */ - -interface CacheFirstOptions extends CacheOnlyOptions { - /** - * Values passed along to the - * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters) - */ - fetchOptions: RequestInit; -} - -/** - * An implementation of a [cache-first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network} - * request strategy. - * - * A cache first strategy is useful for assets that have been revisioned, - * such as URLs like `/styles/example.a8f5f1.css`, since they - * can be cached for long periods of time. - * - * If the network request fails, and there is no cache match, this will throw - * a `WorkboxError` exception. - */ -declare class CacheFirst extends CacheStrategy { -} - -interface CacheFirstConstructor { - /** - * Instantiates a new CacheFirst strategy - * @param {Partial} options - * @return {CacheFirst} - */ - new (options?: Partial): CacheFirst; -} - -/** - * ===== NetworkOnly strategy ===== - */ - -interface NetworkOnlyOptions extends CacheFirstOptions { -} - -/** - * An implementation of a - * [network-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-only} - * request strategy. - * - * This class is useful if you want to take advantage of any - * [Workbox plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}. - * - * If the network request fails, this will throw a `WorkboxError` exception. - */ -declare class NetworkOnly extends CacheStrategy { -} - -interface NetworkOnlyConstructor { - /** - * Instantiates a new NetworkOnly strategy - * @param {Partial} options - * @return {NetworkOnly} - */ - new (options?: Partial): NetworkOnly; -} - -/** - * ===== NetworkFirst strategy ===== - */ - -interface NetworkFirstOptions extends CacheFirstOptions { - /** - * If set, any network requests - * that fail to respond within the timeout will fallback to the cache. - */ - networkTimeoutSeconds: number; -} - -/** - * An implementation of a - * [network first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-falling-back-to-cache} - * request strategy. - * - * By default, this strategy will cache responses with a 200 status code as - * well as [opaque responses]{@link https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests}. - * Opaque responses are are cross-origin requests where the response doesn't - * support [CORS]{@link https://enable-cors.org/}. - * - * If the network request fails, and there is no cache match, this will throw - * a `WorkboxError` exception. - */ -declare class NetworkFirst extends CacheStrategy { -} - -interface NetworkFirstConstructor { - /** - * Instantiates a new NetworkFirst strategy - * @param {Partial} options - * @return {NetworkFirst} - */ - new (options?: Partial): NetworkFirst; -} - -/** - * ===== StaleWhileRevalidate strategy ===== - */ - -interface StaleWhileRevalidateOptions extends CacheFirstOptions { -} - -/** - * An implementation of a - * [stale-while-revalidate]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#stale-while-revalidate} - * request strategy. - * - * Resources are requested from both the cache and the network in parallel. - * The strategy will respond with the cached version if available, otherwise - * wait for the network response. The cache is updated with the network response - * with each successful request. - * - * By default, this strategy will cache responses with a 200 status code as - * well as [opaque responses]{@link https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests}. - * Opaque responses are are cross-origin requests where the response doesn't - * support [CORS]{@link https://enable-cors.org/}. - * - * If the network request fails, and there is no cache match, this will throw - * a `WorkboxError` exception. - */ -declare class StaleWhileRevalidate extends CacheStrategy { -} - -interface StaleWhileRevalidateConstructor { - /** - * Instantiates a new StaleWhileRevalidate strategy - * @param {Partial} options - * @return {StaleWhileRevalidate} - */ - new (options?: Partial): StaleWhileRevalidate; -} - -/** - * ===== MatchCallback ===== - */ - -interface MatchContext extends URLContext { - /** - * The service workers' fetch event. - */ - event: FetchEvent; -} - -/** - * To signify a match, return anything other than null. Return null if the route shouldn't match. - */ -type MatchCallback = (context: MatchContext) => {}|null; - -/** - * ===== HandlerCallback ===== - */ - -interface HandlerContext extends MatchContext { - /** - * Parameters returned by the Route's match callback function. This will be undefined if nothing was returned. - */ - params?: {}; -} - -/** - * The "handler" callback is called when a service worker's fetch event has been matched by a Route. This callback should return a Promise that resolves with a Response. - * If a value is returned by the match callback it will be passed in as the context.params argument. - */ -type HandlerCallback = CacheStrategy|((context: HandlerContext) => Promise); - -/** - * ===== NavigationRoute ===== - */ - -interface NavigationRouteOptions { - /** - * If any of these patterns match, - * the route will not handle the request (even if a whitelist RegExp matches). - */ - blacklist: RegExp[]; - - /** - * If any of these patterns match the URL's pathname and search parameter, - * the route will handle the request (assuming the blacklist doesn't match). - */ - whitelist: RegExp[]; -} - -/** - * NavigationRoute makes it easy to create a Route that matches for browser - * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}. - * - * It will only match incoming Requests whose - * [`mode`]{@link https://fetch.spec.whatwg.org/#concept-request-mode} - * is set to `navigate`. - * - * You can optionally only apply this route to a subset of navigation requests - * by using one or both of the `blacklist` and `whitelist` parameters. - */ -declare class NavigationRoute { -} - -interface NavigationRouteConstructor { - /** - * If both `blacklist` and `whitelist` are provided, the `blacklist` will - * take precedence and the request will not match this route. - * - * The regular expressions in `whitelist` and `blacklist` - * are matched against the concatenated - * [`pathname`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname} - * and [`search`]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search} - * portions of the requested URL. - * @param {HandlerCallback} handler - * @param {Partial} options - * @returns {NavigationRoute} - */ - new (handler: HandlerCallback, options: Partial): NavigationRoute; -} - -/** - * ===== BroadcastUpdatePlugin ===== - */ - -/** - * This plugin will automatically broadcast a message whenever a cached response is updated. - */ -declare class BroadcastUpdatePlugin { -} - -interface BroadcastUpdatePluginConstructor { - /** - * Construct a BroadcastCacheUpdate instance with the passed options and - * calls its `notifyIfUpdated()` method whenever the plugin's - * `cacheDidUpdate` callback is invoked. - * @param {Partial} options - * @return {BroadcastUpdatePlugin} - */ - new (options?: Partial): BroadcastUpdatePlugin; -} - -/** - * ===== RangeRequestsPlugin ===== - */ - -/** - * The range request plugin makes it easy for a request with a 'Range' header to - * be fulfilled by a cached response. - * - * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback - * and returning the appropriate subset of the cached response body. - */ -declare class RangeRequestsPlugin { -} - -interface RangeRequestsPluginConstructor { - /** - * Instantiates a new RangeRequestsPlugin - * @return {RangeRequestsPlugin} - */ - new (): RangeRequestsPlugin; -} - -/** - * ===== CacheableResponsePlugin ===== - */ - -/** - * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it - * easier to add in cacheability checks to requests made via Workbox's built-in - * strategies. - */ -declare class CacheableResponsePlugin { -} - -interface CacheableResponsePluginConstructor { - /** - * To construct a new cacheable response Plugin instance you must provide at - * least one of the `config` properties. - * - * If both `statuses` and `headers` are specified, then both conditions must - * be met for the `Response` to be considered cacheable. - * @param {Partial} config - * @return {CacheableResponsePlugin} - */ - new (config: Partial): CacheableResponsePlugin; -} - -/** - * ===== BackgroundSyncPlugin ===== - */ - -/** - * A class implementing the `fetchDidFail` lifecycle callback. This makes it - * easier to add failed requests to a background sync Queue. - */ -declare class BackgroundSyncPlugin { -} - -interface BackgroundSyncPluginConstructor { - /** - * Instantiates a new BackgroundSyncPlugin - * @param {*} queueArgs - Args to forward to the composed Queue instance. - * @return {BackgroundSyncPlugin} - */ - new (...queueArgs: any[]): BackgroundSyncPlugin; -} - -/** - * ===== ExpirationPlugin ===== - */ - -interface CacheExpirationPluginOptions extends CacheExpirationOptions { - /** - * Whether to opt this cache in to automatic deletion - * if the available storage quota has been exceeded. - */ - purgeOnQuotaError: boolean; -} - -/** - * This plugin can be used in the Workbox APIs to regularly enforce a - * limit on the age and / or the number of cached requests. - * - * Whenever a cached request is used or updated, this plugin will look - * at the used Cache and remove any old or extra requests. - * - * When using `maxAgeSeconds`, requests may be used *once* after expiring - * because the expiration clean up will not have occurred until *after* the - * cached request has been used. If the request has a "Date" header, then - * a light weight expiration check is performed and the request will not be - * used immediately. - * - * When using `maxEntries`, the last request to be used will be the request - * that is removed from the Cache. - */ -declare class ExpirationPlugin { - /** - * This is a helper method that performs two operations: - * - * - Deletes *all* the underlying Cache instances associated with this plugin - * instance, by calling caches.delete() on your behalf. - * - Deletes the metadata from IndexedDB used to keep track of expiration - * details for each Cache instance. - * - * When using cache expiration, calling this method is preferable to calling - * `caches.delete()` directly, since this will ensure that the IndexedDB - * metadata is also cleanly removed and open IndexedDB instances are deleted. - * - * Note that if you're *not* using cache expiration for a given cache, calling - * `caches.delete()` and passing in the cache's name should be sufficient. - * There is no Workbox-specific method needed for cleanup in that case. - * @return {Promise} - */ - deleteCacheAndMetadata(): Promise; -} - -interface ExpirationPluginConstructor { - /** - * Instantiates a new ExpirationPlugin - * @param {Partial} config - * @return {ExpirationPlugin} - */ - new (config: Partial): ExpirationPlugin; -} - -/** - * ===== ExpirationPlugin ===== - */ - -type Plugin = BroadcastUpdatePlugin|RangeRequestsPlugin|CacheableResponsePlugin|BackgroundSyncPlugin|ExpirationPlugin|WorkboxPlugin; - -/** - * ===== BackgroundSync ===== - */ - -interface StorableRequestOptions { - url: string; - - /** - * See: https://fetch.spec.whatwg.org/#requestinit - */ - requestInit: RequestInit; -} - -/** - * A class to make it easier to serialize and de-serialize requests so they can be stored in IndexedDB. - * @private - */ -declare class StorableRequest { - /** - * Returns a deep clone of the instances `_requestData` object. - * @private - * @return {StorableRequestOptions} - */ - toObject (): StorableRequestOptions; - - /** - * Converts this instance to a Request. - * @private - * @return {Request} - */ - toRequest (): Request; - - /** - * Creates and returns a deep clone of the instance. - * @private - * @return {StorableRequest} - */ - clone (): StorableRequest; -} - -/** - * ===== PrecacheController ===== - */ - -interface CleanupResult { - /** - * List of URLs that were deleted from the precache cache. - */ - deletedCacheRequests: string[]; - /** - * List of URLs that were deleted from the precache cache. - */ - deletedRevisionDetails: string[]; -} - -interface InstallOptions { - /** - * The install event (if needed). - */ - event: Event; - - /** - * Plugins to be used for fetching and caching during install. - */ - plugins: Plugin[]; -} - -interface PrecacheEntry { - url: string; - revision: string; -} - -interface InstallResult { - /** - * List of entries supplied for precaching that were precached. - */ - updatedEntries: (string|PrecacheEntry)[]; - - /** - * List of entries supplied for precaching that were already precached. - */ - notUpdatedEntries: (string|PrecacheEntry)[]; -} - -/** - * Performs efficient precaching of assets. - */ -declare class PrecacheController { - /** - * Deletes assets that are no longer present in the current precache manifest. - * Call this method from the service worker activate event. - * @returns {Promise} - */ - activate (): Promise; - - /** - * This method will add items to the precache list, removing duplicates - * and ensuring the information is valid. - * @param {(string | PrecacheEntry)[]} entries - Array of entries to precache. - */ - addToCacheList (entries: (string|PrecacheEntry)[]): void; - - /** - * Returns a mapping of a precached URL to the corresponding cache key, taking - * into account the revision information for the URL. - * - * @returns {Map} A URL to cache key mapping. - */ - getURLsToCacheKeys(): Map; - - /** - * Returns the cache key used for storing a given URL. If that URL is - * unversioned, like `/index.html', then the cache key will be the original - * URL with a search parameter appended to it. - * - * @param {string} url A URL whose cache key you want to look up. - * @returns {string} The versioned URL that corresponds to a cache key - * for the original URL, or undefined if that URL isn't precached. - */ - getCacheKeyForURL(url: string): string; - - /** - * Returns a list of all the URLs that have been precached by the current - * service worker. - * @returns {string[]} An array of URLs. - */ - getCachedUrls (): string[]; - - /** - * Precaches new and updated assets. Call this method from the service worker - * install event. - * @param {Partial} options - * @returns {Promise} - */ - install (options?: Partial): Promise; -} - -interface PrecacheControllerConstructor { - /** - * Create a new PrecacheController. - * @param {string} cacheName - An optional name for the cache, to override the default precache name. - * @return {PrecacheController} - */ - new (cacheName?: string): PrecacheController; -} - -/** - * ===== Queue ===== - */ - -interface QueueOptions { - /** - * A function that gets invoked whenever the 'sync' event fires. The function is invoked with an object - * containing the `queue` property (referencing this instance), and you - * can use the callback to customize the replay behavior of the queue. - * When not set the `replayRequests()` method is called. - * Note: if the replay fails after a sync event, make sure you throw an - * error, so the browser knows to retry the sync event later. - */ - onSync: (queue: { queue: Queue }) => void; - - /** - * The amount of time (in minutes) a request may be retried. After this amount of time has - * passed, the request will be deleted from the queue. - */ - maxRetentionTime: number; -} - -interface QueueEntry { - /** - * The request to store in the queue. - */ - request: Request; - - /** - * Any metadata you want associated with the - * stored request. When requests are replayed you'll have access to this - * metadata object in case you need to modify the request beforehand. - */ - metadata: any; - - /** - * The timestamp (Epoch time in milliseconds) when the request was first added to the queue. - * This is used along with `maxRetentionTime` to remove outdated requests. - * In general you don't need to set this value, as it's automatically set for you (defaulting to `Date.now()`), - * but you can update it if you don't want particular requests to expire. - */ - timestamp: number; -} - -/** - * A class to manage storing failed requests in IndexedDB and retrying them - * later. All parts of the storing and replaying process are observable via - * callbacks. - */ -declare class Queue { - readonly name: string; - - /** - * Stores the passed request in IndexedDB (with its timestamp and any - * metadata) at the end of the queue. - * @param {QueueEntry} entry - * @returns {Promise} - */ - pushRequest (entry: QueueEntry): Promise; - - /** - * Stores the passed request in IndexedDB (with its timestamp and any - * metadata) at the beginning of the queue. - * @param {QueueEntry} entry - * @return {Promise} - */ - unshiftRequest (entry: QueueEntry): Promise; - - /** - * Removes and returns the last request in the queue (along with its - * timestamp and any metadata). The returned object takes the form: - * `{request, timestamp, metadata}`. - * @return {Promise} - */ - popRequest (): Promise; - - /** - * Removes and returns the first request in the queue (along with its - * timestamp and any metadata). The returned object takes the form: - * `{request, timestamp, metadata}`. - * @return {Promise} - */ - shiftRequest (): Promise; - - /** - * Loops through each request in the queue and attempts to re-fetch it. - * If any request fails to re-fetch, it's put back in the same position in - * the queue (which registers a retry for the next sync event). - * @returns {Promise} - */ - replayRequests (): Promise; - - /** - * Registers a sync event with a tag unique to this instance. - * @return {Promise} - */ - registerSync (): Promise; -} - -/** - * Creates an instance of Queue with the given options - */ -interface QueueConstructor { - /** - * Creates an instance of Queue with the given options - * @param {string} name - The unique name for this queue. This name must be unique as it's used to register sync events - * and store requests in IndexedDB specific to this instance. An error will be thrown if a duplicate - * name is detected. - * @param {Partial} options - * @return {Queue} - */ - new (name: string, options?: Partial): Queue; -} - -/** - * ===== Route ===== - */ - -/** - * A `Route` consists of a pair of callback functions, "match" and "handler". - * The "match" callback determine if a route should be used to "handle" a - * request by returning a non-falsy value if it can. The "handler" callback - * is called when there is a match and should return a Promise that resolves - * to a `Response`. - */ -declare class Route { -} - -interface RouteConstructor { - /** - * Constructor for Route class. - * @param {MatchCallback} match - A callback function that determines whether the route matches a given `fetch` event by returning a non-falsy value. - * @param {HandlerCallback} handler - A callback function that returns a Promise resolving to a Response. - * @param {string} [method="GET"] - The HTTP method to match the Route - * @returns {Route} - */ - new (match: MatchCallback, handler: HandlerCallback, method?: string): Route; -} - -/** - * ===== RegExpRoute ===== - */ - -/** - * RegExpRoute makes it easy to create a regular expression based Route. - * - * For same-origin requests the RegExp only needs to match part of the URL. For - * requests against third-party servers, you must define a RegExp that matches - * the start of the URL. - * - * [See the module docs for info.]{@link https://developers.google.com/web/tools/workbox/modules/workbox-routing} - */ -declare class RegExpRoute extends Route { -} - -interface RegExpRouteConstructor { - /** - * - * @param {RegExp} regExp - The regular expression to match against URLs. - * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. - * @param {string} [method] - The HTTP method to match the Route against. - * @returns {RegExpRoute} - */ - - /** - * If the regular expression contains - * [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references}, - * the captured values will be passed to the handler's `params` - * argument. - * @param {RegExp} regExp - The regular expression to match against URLs. - * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. - * @param {string} [method="GET"] - The HTTP method to match the Route against. - * @return {RegExpRoute} - */ - new (regExp: RegExp, handler: HandlerCallback, method?: string): RegExpRoute; -} - -/** - * ===== Router ===== - */ - -interface HandleRequestOptions { - /** - * The request to handle (this is usually from a fetch event, but it does not have to be). - */ - request: Request; - - /** - * The event that triggered the request, if applicable. - */ - event?: FetchEvent; -} - -interface FindMatchingRouteOptions { - url: URL; - - /** - * The request to match. - */ - request: Request; - - /** - * The corresponding event (unless N/A). - */ - event?: FetchEvent; -} - -interface FindMatchingRouteResult { - route: Route; - params: URLSearchParams; -} - -/** - * The Router can be used to process a FetchEvent through one or more - * Routes responding with a Request if - * a matching route exists. - * - * If no route matches a given a request, the Router will use a "default" - * handler if one is defined. - * - * Should the matching Route throw an error, the Router will use a "catch" - * handler if one is defined to gracefully deal with issues and respond with a - * Request. - * - * If a request matches multiple routes, the **earliest** registered route will - * be used to respond to the request. - */ -declare class Router { - /** - * A `Map` of HTTP method name ('GET', etc.) to an array of all the corresponding `Route` - * instances that are registered. - * @type {Map} - */ - readonly routes: Map; - - /** - * Adds a fetch event listener to respond to events when a route matches - * the event's request. - */ - addFetchListener(): void; - - /** - * Adds a message event listener for URLs to cache from the window. - * This is useful to cache resources loaded on the page prior to when the - * service worker started controlling it. - * - * The format of the message data sent from the window should be as follows. - * Where the `urlsToCache` array may consist of URL strings or an array of - * URL string + `requestInit` object (the same as you'd pass to `fetch()`). - * - * ``` - * { - * type: 'CACHE_URLS', - * payload: { - * urlsToCache: [ - * './script1.js', - * './script2.js', - * ['./script3.js', {mode: 'no-cors'}], - * ], - * }, - * } - * ``` - */ - addCacheListener (): void; - - /** - * Apply the routing rules to a FetchEvent object to get a Response from an - * appropriate Route's handler. - * @param {HandleRequestOptions} options - * @returns {Promise?} A promise is returned if a registered route can handle the request. If there is no matching route and there's no `defaultHandler`, `undefined` is returned. - */ - handleRequest (options: HandleRequestOptions): Promise|undefined; - - /** - * Checks a request and URL (and optionally an event) against the list of - * registered routes, and if there's a match, returns the corresponding - * route along with any params generated by the match. - * @param {FindMatchingRouteOptions} options - * @return {Partial} - */ - findMatchingRoute (options: FindMatchingRouteOptions): Partial; - - /** - * Define a default `handler` that's called when no routes explicitly - * match the incoming request. - * - * Without a default handler, unmatched requests will go against the - * network as if there were no service worker present. - * @param {HandlerCallback} handler - * @param {workbox.routing.Route~handlerCallback} handler A callback function that returns a Promise resulting in a Response. - */ - setDefaultHandler (handler: HandlerCallback): void; - - /** - * If a Route throws an error while handling a request, this `handler` - * will be called and given a chance to provide a response. - * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. - */ - setCatchHandler (handler: HandlerCallback): void; - - /** - * Registers a route with the router. - * @param {Route} route - The route to register. - */ - registerRoute (route: Route): void; - - /** - * Unregisters a route with the router. - * @param {Route} route - The route to unregister. - */ - unregisterRoute (route: Route): void; -} - -interface RouterConstructor { - /** - * Initializes a new Router. - * @return {Router} - */ - new (): Router; -} - -/** - * ===== CoreNamespace ===== - */ - -interface CacheNames { - precache: string; - runtime: string; - prefix: string; - suffix: string; - googleAnalytics: string; -} - -/** - * All of the Workbox service worker libraries use workbox-core for shared code as well as setting default values that need to be shared (like cache names). - */ -declare class CoreNamespace { - /** - * Get the current cache names and prefix/suffix used by Workbox. - * - * `cacheNames.precache` is used for precached assets, - * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to - * store `analytics.js`, and `cacheNames.runtime` is used for everything else. - * - * `cacheNames.prefix` can be used to retrieve just the current prefix value. - * `cacheNames.suffix` can be used to retrieve just the current suffix value. - */ - static readonly cacheNames: CacheNames; - - /** - * Claim any currently available clients once the service worker - * becomes active. This is normally used in conjunction with `skipWaiting()`. - */ - static clientsClaim (): void; - - /** - * Adds a function to the set of callbacks that will be executed when there's - * a quota error. - * @param {() => *} callback - */ - static registerQuotaErrorCallback (callback: () => any): void; - - /** - * Modifies the default cache names used by the Workbox packages. - * Cache names are generated as `--`. - * @param {Partial} details - */ - static setCacheNameDetails (details: Partial): void; - - /** - * Force a service worker to become active, instead of waiting. This is - * normally used in conjunction with `clientsClaim()`. - */ - static skipWaiting (): void; -} - -/** - * ===== PrecachingNamespace ===== - */ - -interface URLContext { - /** - * The request's URL. - */ - url: URL; -} - -/** - * The "urlManipulation" callback can be used to determine if there are any additional permutations of a URL that should be used to check against the available precached files. - * For example, Workbox supports checking for '/index.html' when the URL '/' is provided. This callback allows additional, custom checks. - * @param {URLContext} context - * @returns {URL[]} To add additional urls to test, return an Array of URL's. Please note that these should not be Strings, but URL objects. - */ -type UrlManipulation = (context: URLContext) => URL[]; - -interface RouteOptions { - /** - * The `directoryIndex` will check cache entries for a URLs ending with '/' to see if there is a hit when - * appending the `directoryIndex` value. - */ - directoryIndex: string|null; - - /** - * An array of regex's to remove search params when looking for a cache match. - */ - ignoreUrlParametersMatching: RegExp[]; - - /** - * The `cleanURLs` option will check the cache for the URL with a `.html` added to the end of the end. - */ - cleanUrls: boolean; - - /** - * This is a function that should take a URL and return an array of - * alternative URL's that should be checked for precache matches. - */ - urlManipulation: UrlManipulation; -} - -/** - * Most consumers of this module will want to use the precacheAndRoute() method to add assets to the Cache and respond to network requests with these cached assets. - * If you require finer grained control, you can use the PrecacheController to determine when performed. - */ -declare class PrecachingNamespace { - /** - * Add plugins to precaching. - * @param {Plugin[]} newPlugins - */ - static addPlugins (newPlugins: Plugin[]): void; - - /** - * Add a `fetch` listener to the service worker that will respond to - * [network requests]{@link https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests} - * with precached assets. - * - * Requests for assets that aren't precached, the `FetchEvent` will not be - * responded to, allowing the event to fall through to other `fetch` event - * listeners. - * @param {Partial} [route] - */ - static addRoute (route?: Partial): void; - - /** - * Adds an `activate` event listener which will clean up incompatible - * precaches that were created by older versions of Workbox. - */ - static cleanupOutdatedCaches (): void; - - /** - * Takes in a URL, and returns the corresponding URL that could be used to - * lookup the entry in the precache. - * - * If a relative URL is provided, the location of the service worker file will - * be used as the base. - * - * For precached entries without revision information, the cache key will be the - * same as the original URL. - * - * For precached entries with revision information, the cache key will be the - * original URL with the addition of a query parameter used for keeping track of - * the revision info. - * @param {string} url - The URL whose cache key to look up. - * @returns {string} The cache key that corresponds to that URL. - */ - static getCacheKeyForURL (url: string): string; - - /** - * Adds items to the precache list, removing any duplicates and - * stores the files in the - * "precache cache" when the service - * worker installs. - * - * This method can be called multiple times. - * - * Please note: This method **will not** serve any of the cached files for you. - * It only precaches files. To respond to a network request you call - * addRoute(). - * - * If you have a single array of files to precache, you can just call - * precacheAndRoute(). - * @param {(string | PrecacheEntry)[]} entries - Array of entries to precache. - */ - static precache (entries: (string|PrecacheEntry)[]): void; - - /** - * This method will add entries to the precache list and add a route to - * respond to fetch events. - * - * This is a convenience method that will call precache() and - * addRoute() in a single call. - * @param {(string | PrecacheEntry)[]} entries - Array of entries to precache. - * @param {Partial} [options] - see addRoute() options - */ - static precacheAndRoute (entries: (string|PrecacheEntry)[], options?: Partial): void; - - /** - * Performs efficient precaching of assets. - */ - static readonly PrecacheController: PrecacheControllerConstructor; -} - -/** - * ===== RoutingNamespace ===== - */ - -interface RegisterNavigationRouteOptions extends NavigationRouteOptions { - /** - * Cache name to store and retrieve requests. Defaults to precache cache name provided by `cacheNames`. - */ - cacheName: string; -} - -declare class RoutingNamespace { - /** - * NavigationRoute makes it easy to create a Route that matches for browser - * [navigation requests]{@link https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests}. - * - * It will only match incoming Requests whose - * [`mode`]{@link https://fetch.spec.whatwg.org/#concept-request-mode} - * is set to `navigate`. - * - * You can optionally only apply this route to a subset of navigation requests - * by using one or both of the `blacklist` and `whitelist` parameters. - */ - static readonly NavigationRoute: NavigationRouteConstructor; - - /** - * RegExpRoute makes it easy to create a regular expression based - * Route. - * - * For same-origin requests the RegExp only needs to match part of the URL. For - * requests against third-party servers, you must define a RegExp that matches - * the start of the URL. - * - * [See the module docs for info.]{@link https://developers.google.com/web/tools/workbox/modules/workbox-routing} - */ - static readonly RegExpRoute: RegExpRouteConstructor; - - /** - * Registers a route that will return a precached file for a navigation - * request. This is useful for the - * [application shell pattern]{@link https://developers.google.com/web/fundamentals/architecture/app-shell}. - * - * When determining the URL of the precached HTML document, you will likely need - * to call `workbox.precaching.getCacheKeyForURL(originalUrl)`, to account for - * the fact that Workbox's precaching naming conventions often results in URL - * cache keys that contain extra revisioning info. - * - * This method will generate a NavigationRoute and call Router.registerRoute() on a singleton Router instance. - * @param {string} cachedAssetUrl - The cache key to use for the HTML file. - * @param {Partial} [options] - * @returns {NavigationRoute} Returns the generated Route. - */ - static registerNavigationRoute (cachedAssetUrl: string, options?: Partial): NavigationRoute; - - /** - * Easily register a RegExp, string, or function with a caching - * strategy to a singleton Router instance. - * - * This method will generate a Route for you if needed and - * call Router.registerRoute(). - * @param {string | RegExp | MatchCallback | Route} capture - If the capture param is a `Route`, all other arguments will be ignored. - * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. - * @param {string} [method="GET"] - The HTTP method to match the Route against. - * @returns {Route} The generated `Route` (Useful for unregistering). - */ - static registerRoute (capture: string|RegExp|MatchCallback|Route, handler: HandlerCallback, method?: string): Route; - - /** - * A `Route` consists of a pair of callback functions, "match" and "handler". - * The "match" callback determine if a route should be used to "handle" a - * request by returning a non-falsy value if it can. The "handler" callback - * is called when there is a match and should return a Promise that resolves - * to a `Response`. - */ - static readonly Route: RouteConstructor; - - /** - * The Router can be used to process a FetchEvent through one or more - * Routes responding with a Request if - * a matching route exists. - * - * If no route matches a given a request, the Router will use a "default" - * handler if one is defined. - * - * Should the matching Route throw an error, the Router will use a "catch" - * handler if one is defined to gracefully deal with issues and respond with a - * Request. - * - * If a request matches multiple routes, the **earliest** registered route will - * be used to respond to the request. - */ - static readonly Router: RouterConstructor; - - /** - * If a Route throws an error while handling a request, this `handler` - * will be called and given a chance to provide a response. - * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. - */ - static setCatchHandler (handler: HandlerCallback): void; - - /** - * Define a default `handler` that's called when no routes explicitly - * match the incoming request. - * - * Without a default handler, unmatched requests will go against the - * network as if there were no service worker present. - * @param {HandlerCallback} handler - A callback function that returns a Promise resulting in a Response. - */ - static setDefaultHandler (handler: HandlerCallback): Promise; -} - -/** - * ===== StrategiesNamespace ===== - */ - -interface StrategyOptions { - /** - * Name of cache to use for caching (both lookup and updating). - */ - cacheName: string; - - /** - * Defining this object will add a cache expiration plugins to this strategy. - */ - cacheExpiration: Partial; - - /** - * The Plugins to use along with the Strategy - */ - plugins: Plugin[]; -} - -/** - * There are common caching strategies that most service workers will need and use. This module provides simple implementations of these strategies. - */ -declare class StrategiesNamespace { - /** - * An implementation of a [cache-first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network} - * request strategy. - * - * A cache first strategy is useful for assets that have been revisioned, - * such as URLs like `/styles/example.a8f5f1.css`, since they - * can be cached for long periods of time. - * - * If the network request fails, and there is no cache match, this will throw - * a `WorkboxError` exception. - */ - static readonly CacheFirst: CacheFirstConstructor; - - /** - * An implementation of a - * [cache-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-only} - * request strategy. - * - * This class is useful if you want to take advantage of any - * [Workbox plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}. - * - * If there is no cache match, this will throw a `WorkboxError` exception. - */ - static readonly CacheOnly: CacheOnlyConstructor; - - /** - * An implementation of a - * [network first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-falling-back-to-cache} - * request strategy. - * - * By default, this strategy will cache responses with a 200 status code as - * well as [opaque responses]{@link https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests}. - * Opaque responses are are cross-origin requests where the response doesn't - * support [CORS]{@link https://enable-cors.org/}. - * - * If the network request fails, and there is no cache match, this will throw - * a `WorkboxError` exception. - */ - static readonly NetworkFirst: NetworkFirstConstructor; - - /** - * An implementation of a - * [network-only]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-only} - * request strategy. - * - * This class is useful if you want to take advantage of any - * [Workbox plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}. - * - * If the network request fails, this will throw a `WorkboxError` exception. - */ - static readonly NetworkOnly: NetworkOnlyConstructor; - - /** - * An implementation of a - * [stale-while-revalidate]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#stale-while-revalidate} - * request strategy. - * - * Resources are requested from both the cache and the network in parallel. - * The strategy will respond with the cached version if available, otherwise - * wait for the network response. The cache is updated with the network response - * with each successful request. - * - * By default, this strategy will cache responses with a 200 status code as - * well as [opaque responses]{@link https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests}. - * Opaque responses are are cross-origin requests where the response doesn't - * support [CORS]{@link https://enable-cors.org/}. - * - * If the network request fails, and there is no cache match, this will throw - * a `WorkboxError` exception. - */ - static readonly StaleWhileRevalidate: StaleWhileRevalidateConstructor; - - /** - * Instantiates a new CacheFirst strategy - * @deprecated use new workbox.strategies.CacheFirst() syntax - * @param {Partial} [options] - * @returns {HandlerCallback} - */ - static cacheFirst (options?: Partial): HandlerCallback; - - /** - * Instantiates a new CacheOnly strategy - * @deprecated use new workbox.strategies.CacheOnly() syntax - * @param {Partial} [options] - * @returns {HandlerCallback} - */ - static cacheOnly (options?: Partial): HandlerCallback; - - /** - * Instantiates a new NetworkFirst strategy - * @deprecated use new workbox.strategies.NetworkFirst() syntax - * @param {Partial} [options] - * @returns {HandlerCallback} - */ - static networkFirst (options?: Partial): HandlerCallback; - - /** - * Instantiates a new NetworkOnly strategy - * @deprecated use new workbox.strategies.NetworkOnly() syntax - * @param {Partial} [options] - * @returns {HandlerCallback} - */ - static networkOnly (options?: Partial): HandlerCallback; - - /** - * Instantiates a new StaleWhileRevalidate strategy - * @deprecated use new workbox.strategies.StaleWhileRevalidate() syntax - * @param {Partial} [options] - * @returns {StaleWhileRevalidate} - */ - static staleWhileRevalidate (options?: Partial): HandlerCallback; -} - -/** - * ===== StreamsNamespace ===== - */ - -type StreamSource = Response|ReadableStream|BodyInit; - -interface ConcatenateResult { - done: Promise; - stream: ReadableStream; -} - -interface ConcatenateToResponseResult { - done: Promise; - response: Response; -} - -declare class StreamsNamespace { - /** - * Takes multiple source Promises, each of which could resolve to a Response, a - * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit). - * - * Returns an object exposing a ReadableStream with each individual stream's - * data returned in sequence, along with a Promise which signals when the - * stream is finished (useful for passing to a FetchEvent's waitUntil()). - * @param {Promise[]} sourcePromises - Array of Promise containing StreamSource - * @returns {ConcatenateResult} - */ - static concatenate (sourcePromises: Promise[]): ConcatenateResult; - - /** - * Takes multiple source Promises, each of which could resolve to a Response, a - * ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit), - * along with a - * [HeadersInit](https://fetch.spec.whatwg.org/#typedefdef-headersinit). - * - * Returns an object exposing a Response whose body consists of each individual - * stream's data returned in sequence, along with a Promise which signals when - * the stream is finished (useful for passing to a FetchEvent's waitUntil()). - * @param {Promise[]} sourcePromises - Array of Promise containing StreamSource - * @param {HeadersInit} [headersInit] - If there's no `Content-Type` specified, `'text/html'` will be used by default. - * @returns {ConcatenateToResponseResult} - */ - static concatenateToResponse (sourcePromises: Promise[], headersInit?: HeadersInit): ConcatenateToResponseResult; - - /** - * This is a utility method that determines whether the current browser supports - * the features required to create streamed responses. Currently, it checks if - * [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream) - * can be created. - * @returns {boolean} `true`, if the current browser meets the requirements for streaming responses, and `false` otherwise. - */ - static isSupported (): boolean; - - /** - * A shortcut to create a strategy that could be dropped-in to Workbox's router. - * - * On browsers that do not support constructing new `ReadableStream`s, this - * strategy will automatically wait for all the `sourceFunctions` to complete, - * and create a final response that concatenates their values together. - * @param {HandlerCallback[]} sourceFunctions - Each function should return a StreamSource (or a Promise which resolves to one). - * @param {HeadersInit} headersInit - If there's no `Content-Type` specified, `'text/html'` will be used by default. - * @returns {HandlerCallback} - */ - static strategy (sourceFunctions: HandlerCallback[], headersInit?: HeadersInit): HandlerCallback; -} - -/** - * ===== ExpirationNamespace ===== - */ - -declare class ExpirationNamespace { - /** - * The `CacheExpiration` class allows you define an expiration and / or - * limit on the number of responses stored in a [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache). - */ - static readonly CacheExpiration: CacheExpirationConstructor; - - /** - * This plugin can be used in the Workbox APIs to regularly enforce a - * limit on the age and / or the number of cached requests. - * - * Whenever a cached request is used or updated, this plugin will look - * at the used Cache and remove any old or extra requests. - * - * When using `maxAgeSeconds`, requests may be used *once* after expiring - * because the expiration clean up will not have occurred until *after* the - * cached request has been used. If the request has a "Date" header, then - * a light weight expiration check is performed and the request will not be - * used immediately. - * - * When using `maxEntries`, the last request to be used will be the request - * that is removed from the Cache. - */ - static readonly Plugin: ExpirationPluginConstructor; -} - -/** - * ===== BackgroundSyncNamespace ===== - */ - -declare class BackgroundSyncNamespace { - /** - * A class implementing the `fetchDidFail` lifecycle callback. This makes it - * easier to add failed requests to a background sync Queue. - */ - static readonly Plugin: BackgroundSyncPluginConstructor; - - /** - * A class to manage storing failed requests in IndexedDB and retrying them - * later. All parts of the storing and replaying process are observable via - * callbacks. - */ - static readonly Queue: QueueConstructor; -} - -/** - * ===== GoogleAnalyticsNamespace ===== - */ - -interface GoogleAnalyticsInitializeOptions { - /** - * The cache name to store and retrieve analytics.js. - * Defaults to the cache names provided by `workbox-core`. - */ - cacheName: string; - - /** - * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters), - * expressed as key/value pairs, to be added to replayed Google Analytics - * requests. This can be used to, e.g., set a custom dimension indicating - * that the request was replayed. - */ - parameterOverrides: Record; - - /** - * A function that allows you to modify the hit parameters prior to replaying - * the hit. The function is invoked with the original hit's URLSearchParams - * object as its only argument. - * @param {URLSearchParams} params - */ - hitFilter (params: URLSearchParams): void; -} - -declare class GoogleAnalyticsNamespace { - /** - * - * @param {Partial} options - */ - static initialize (options?: Partial): void; -} - -/** - * ===== NavigationPreloadNamespace ===== - */ - -declare class NavigationPreloadNamespace { - /** - * If the browser supports Navigation Preload, then this will disable it. - */ - static disable (): void; - - /** - * If the browser supports Navigation Preload, then this will enable it. - * @param {string} [headerValue] - Optionally, allows developers to - * [override](https://developers.google.com/web/updates/2017/02/navigation-preload#changing_the_header) - * the value of the `Service-Worker-Navigation-Preload` header which will be sent to the server when making - * the navigation request. - */ - static enable (headerValue?: string): void; - - /** - * @return {boolean} Whether or not the current browser supports enabling navigation preload. - */ - static isSupported (): boolean; -} - -/** - * ===== CacheableResponseNamespace ===== - */ - -declare class CacheableResponseNamespace { - /** - * This class allows you to set up rules determining what - * status codes and/or headers need to be present in order for a - * [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) - * to be considered cacheable. - */ - static readonly CacheableResponse: CacheableResponseConstructor; - - /** - * A class implementing the `cacheWillUpdate` lifecycle callback. This makes it - * easier to add in cacheability checks to requests made via Workbox's built-in - * strategies. - */ - static readonly Plugin: CacheableResponsePluginConstructor; -} - -/** - * ===== BroadcastUpdateNamespace ===== - */ - -interface BroadcastUpdateOptions { - /** - * The name of the cache in which the updated `Response` was stored. - */ - cacheName: string; - - /** - * The URL associated with the updated `Response`. - */ - url: string; - - /** - * The `BroadcastChannel` to use. If no channel is set or the browser doesn't support the BroadcastChannel - * api, then an attempt will be made to `postMessage` each window client. - */ - channel?: BroadcastChannel; -} - -declare class BroadcastUpdateNamespace { - /** - * Uses the [Broadcast Channel API]{@link https://developers.google.com/web/updates/2016/09/broadcastchannel} - * to notify interested parties when a cached response has been updated. - * In browsers that do not support the Broadcast Channel API, the instance - * falls back to sending the update via `postMessage()` to all window clients. - * - * For efficiency's sake, the underlying response bodies are not compared; - * only specific response headers are checked. - */ - static readonly BroadcastCacheUpdate: BroadcastCacheUpdateConstructor; - - /** - * Construct a BroadcastCacheUpdate instance with the passed options and - * calls its `notifyIfUpdated()` method whenever the plugin's - * `cacheDidUpdate` callback is invoked. - */ - static readonly Plugin: BroadcastUpdatePluginConstructor; - - /** - * You would not normally call this method directly; it's called automatically - * by an instance of the {@link BroadcastCacheUpdate} class. It's exposed here - * for the benefit of developers who would rather not use the full - * `BroadcastCacheUpdate` implementation. - * - * Calling this will dispatch a message on the provided - * {@link https://developers.google.com/web/updates/2016/09/broadcastchannel|Broadcast Channel} - * to notify interested subscribers about a change to a cached resource. - * - * The message that's posted has a formation inspired by the - * [Flux standard action](https://github.com/acdlite/flux-standard-action#introduction) - * format like so: - * - * ``` - * { - * type: 'CACHE_UPDATED', - * meta: 'workbox-broadcast-update', - * payload: { - * cacheName: 'the-cache-name', - * updatedURL: 'https://example.com/' - * } - * } - * ``` - * - * (Usage of [Flux](https://facebook.github.io/flux/) itself is not at - * all required.) - * @param {BroadcastUpdateOptions} options - * @returns {Promise} - */ - static broadCastUpdate (options: BroadcastUpdateOptions): Promise; - - /** - * Given two `Response's`, compares several header values to see if they are - * the same or not. - * @param {Response} firstResponse - * @param {Response} secondResponse - * @param {string[]} headersToCheck - * @return {boolean} - */ - static responsesAreSame (firstResponse: Response, secondResponse: Response, headersToCheck: string[]): boolean; -} - -/** - * ===== RangeRequestsNamespace ===== - */ - -declare class RangeRequestsNamespace { - /** - * Given a `Request` and `Response` objects as input, this will return a - * promise for a new `Response`. - * - * If the original `Response` already contains partial content (i.e. it has - * a status of 206), then this assumes it already fulfills the `Range:` - * requirements, and will return it as-is. - * - * @param {Request} request A request, which should contain a Range: - * header. - * @param {Response} originalResponse A response. - * @return {Promise} Either a `206 Partial Content` response, with - * the response body set to the slice of content specified by the request's - * `Range:` header, or a `416 Range Not Satisfiable` response if the - * conditions of the `Range:` header can't be met. - * - * @param {Request} request - A request, which should contain a Range: header. - * @param {Response} originalResponse - A response. - * @returns {Promise} Either a `206 Partial Content` response, with the response body - * set to the slice of content specified by the request's `Range:` header, - * or a `416 Range Not Satisfiable` response if the conditions of the `Range:` - * header can't be met. - */ - static createPartialResponse (request: Request, originalResponse: Response): Promise; - - /** - * The range request plugin makes it easy for a request with a 'Range' header to - * be fulfilled by a cached response. - * - * It does this by intercepting the `cachedResponseWillBeUsed` plugin callback - * and returning the appropriate subset of the cached response body. - */ - static readonly Plugin: RangeRequestsPluginConstructor; -} - -/** - * ===== Workbox Plugin ===== - */ -interface WorkboxPlugin { - /** - * Called before a Response is used to update a cache. You can alter the Response before it’s added to the cache or return null to avoid updating the cache at all. - * @param {CacheWillUpdatePluginContext} context - * @returns {Promise|Response|null} - */ - readonly cacheWillUpdate?: (context: CacheWillUpdatePluginContext) => Promise|Response|null; - - /** - * This allows developers to override the default cache key for reads or writes (or both). - * @param {CacheKeyWillBeUsedPluginContext} context - * @returns {Promise|string|Request} - */ - readonly cacheKeyWillBeUsed?: (context: CacheKeyWillBeUsedPluginContext) => Promise|string|Request; - - /** - * Called when a new entry is added to a cache or it’s updated. Useful if you wish to perform an action after a cache update. - * @param {CacheDidUpdatePluginContext} context - * @returns {void} - */ - readonly cacheDidUpdate?: (context: CacheDidUpdatePluginContext) => void; - - /** - * Before a cached Response is used to respond to a fetch event, this callback can be used to allow or block the Response from being used. - * @param {CacheResponseWillBeUsedPluginContext} context - * @returns {Promise|Response|null} - */ - readonly cachedResponseWillBeUsed?: (context: CacheResponseWillBeUsedPluginContext) => Promise|Response|null; - - /** - * This is called whenever a fetch event is about to be made. You can alter the Request in this callback. - * @param {RequestWillFetchPluginContext} context - * @returns {Request} - */ - readonly requestWillFetch?: (context: RequestWillFetchPluginContext) => Request; - - /** - * Called when a fetch event fails (note this is when the network request can’t be made at all and not when a request is a non-200 request). - * @param {FetchDidFailPluginContext} - * @returns {void} - */ - readonly fetchDidFail?: (context: FetchDidFailPluginContext) => void; - - /** - * Called when a network request is successful, regardless of what the HTTP status is of the response. - * @param {FetchDidSucceedPluginContext} - * @returns {Promise|Response} - */ - readonly fetchDidSucceed?: (context: FetchDidSucceedPluginContext) => Promise|Response; -} - -interface CacheWillUpdatePluginContext { - readonly request: Request; - readonly response: Response; -} - -interface CacheKeyWillBeUsedPluginContext { - readonly request: Request; - readonly mode: string; -} - -interface CacheDidUpdatePluginContext { - readonly event: Event; - readonly cacheName: string; - readonly request: Request; - readonly oldResponse: Response; - readonly newResponse: Response; -} - -interface CacheResponseWillBeUsedPluginContext { - readonly cacheName: string; - readonly request: Request; - readonly matchOptions: any; - readonly cachedResponse: Response; -} - -interface RequestWillFetchPluginContext { - readonly request: Request; -} - -interface FetchDidFailPluginContext { - readonly originalRequest: Request; - readonly request: Request; - readonly error: Error; -} - -interface FetchDidSucceedPluginContext { - readonly request: Request; - readonly response: Response; -} - -/** - * ===== WorkboxNamespace ===== - */ - -/** - * A ModulePathCallback function can be used to modify the modify the where Workbox modules are loaded. - * @param {string} moduleName - The name of the module to load (i.e. 'workbox-core', 'workbox-precaching' etc.). - * @param {boolean} debug - When true, dev builds should be loaded, otherwise load prod builds. - * @returns {string} This callback should return a path of module. This will be passed to importScripts(). - */ -type ModulePathCallback = (moduleName: string, debug: boolean) => string; - -interface ConfigOptions { - /** - * If true, `dev` builds are used, otherwise `prod` builds are used. - * By default, `prod` is used unless on localhost. - */ - debug: boolean; - - /** - * To avoid using the CDN with `workbox-sw` - * set the path prefix of where modules should be loaded from. - * For example `modulePathPrefix: '/third_party/workbox/v3.0.0/'`. - */ - modulePathPrefix: string; - - /** - * If defined, - * this callback will be responsible for determining the path of each - * workbox module. - */ - modulePathCb: ModulePathCallback; -} - -declare class WorkboxNamespace { - static readonly backgroundSync: typeof BackgroundSyncNamespace; - static readonly broadcastUpdate: typeof BroadcastUpdateNamespace; - static readonly cacheableResponse: typeof CacheableResponseNamespace; - static readonly core: typeof CoreNamespace; - static readonly expiration: typeof ExpirationNamespace; - static readonly googleAnalytics: typeof GoogleAnalyticsNamespace; - static readonly navigationPreload: typeof NavigationPreloadNamespace; - static readonly precaching: typeof PrecachingNamespace; - static readonly rangeRequests: typeof RangeRequestsNamespace; - static readonly routing: typeof RoutingNamespace; - static readonly strategies: typeof StrategiesNamespace; - static readonly streams: typeof StreamsNamespace; - - /** - * Load a Workbox module by passing in the appropriate module name. - * - * This is not generally needed unless you know there are modules that are - * dynamically used and you want to safe guard use of the module while the - * user may be offline. - * @param {string} moduleName - */ - static loadModule (moduleName: string): void; - - /** - * Updates the configuration options. You can specify whether to treat as a - * debug build and whether to use a CDN or a specific path when importing - * other workbox-modules - * @param {Partial} config - */ - static setConfig (config?: Partial): void; -} - -export = WorkboxNamespace; diff --git a/types/workbox-sw/tsconfig.json b/types/workbox-sw/tsconfig.json index 28446158f9..d18ac3295b 100644 --- a/types/workbox-sw/tsconfig.json +++ b/types/workbox-sw/tsconfig.json @@ -1,11 +1,6 @@ { - "files": [ - "index.d.ts", - "workbox-sw-tests.ts" - ], "compilerOptions": { "module": "commonjs", - "target": "es2017", "lib": [ "es2015", "webworker" @@ -21,5 +16,9 @@ "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } + }, + "files": [ + "index.d.ts", + "workbox-sw-tests.ts" + ] } diff --git a/types/workbox-sw/tslint.json b/types/workbox-sw/tslint.json index 453ff1da24..3650ee6aed 100644 --- a/types/workbox-sw/tslint.json +++ b/types/workbox-sw/tslint.json @@ -1,12 +1,12 @@ { "extends": "dtslint/dt.json", "rules": { - // TODO + "array-type": false, + "comment-format": false, + "interface-name": false, "no-redundant-jsdoc-2": false, "no-unnecessary-class": false, "no-empty-interface": false, - "array-type": false, - "interface-name": false, "space-before-function-paren": false } } diff --git a/types/workbox-sw/workbox-sw-tests.ts b/types/workbox-sw/workbox-sw-tests.ts index 11716d62f8..bebdf932ef 100644 --- a/types/workbox-sw/workbox-sw-tests.ts +++ b/types/workbox-sw/workbox-sw-tests.ts @@ -1,16 +1,27 @@ -import WorkboxSW = require("workbox-sw"); +/* tslint:disable:comment-format no-namespace */ -WorkboxSW.routing.registerRoute("/", new WorkboxSW.strategies.NetworkFirst()); // $ExpectType Route +"use strict"; -WorkboxSW.routing.registerRoute("/", WorkboxSW.strategies.networkFirst()); // $ExpectType Route +//============================================================================== +// workbox.loadModule +//============================================================================== -// $ExpectError -WorkboxSW.precaching.precacheAndRoute(/foo/); +export namespace LoadModuleTest { + declare const name: string; -WorkboxSW.precaching.precacheAndRoute(["some-resource.js"], {directoryIndex: "/"}); // $ExpectType void + // $ExpectType void + workbox.loadModule(name); +} -new WorkboxSW.backgroundSync.Queue('queue-name', { - onSync: ({ queue }) => { - queue; // $ExpectType Queue - }, -}); +//============================================================================== +// workbox.setConfig +//============================================================================== + +export namespace SetConfigTest { + declare const options: workbox.WorkboxOptions; + + // $ExpectType void + workbox.setConfig(); + // $ExpectType void + workbox.setConfig(options); +} diff --git a/types/workbox-window/Workbox.d.ts b/types/workbox-window/Workbox.d.ts index f51093e8a5..cd2ebf6e65 100644 --- a/types/workbox-window/Workbox.d.ts +++ b/types/workbox-window/Workbox.d.ts @@ -1,115 +1,20 @@ -import { EventTargetShim } from './utils/EventTargetShim'; -import { WorkboxEvent } from './utils/WorkboxEvent'; +import { WorkboxEventMap } from "./types/WorkboxEventMap"; -interface WorkboxMessageEvent extends WorkboxEvent { - /** - * The `data` property from the original `message` event. - */ - readonly data: any; -} +import { EventTargetShim } from "./utils/EventTargetShim"; -interface WorkboxExtendableEvent extends WorkboxEvent { - /** - * The service worker instance. - */ - readonly sw: ServiceWorker; -} - -interface WorkboxUpdatableEvent extends WorkboxExtendableEvent { - /** - * True if a service worker was already - * controlling when this `Workbox` instance called `register()`. - */ - readonly isUpdate?: boolean; -} - -interface WorkboxWaitingEvent extends WorkboxUpdatableEvent { - /** - * True if a service worker with - * a matching `scriptURL` was already waiting when this `Workbox` - * instance called `register()`. - */ - readonly wasWaitingBeforeRegister?: boolean; -} - -interface WokerboxEventMap { - message: WorkboxMessageEvent; - installed: WorkboxUpdatableEvent; - waiting: WorkboxWaitingEvent; - controlling: WorkboxEvent; - activated: WorkboxUpdatableEvent; - redundant: WorkboxEvent; - externalinstalled: WorkboxExtendableEvent; - externalwaiting: WorkboxExtendableEvent; - externalactivated: WorkboxExtendableEvent; -} - -declare class Workbox extends EventTargetShim { - /** - * Creates a new Workbox instance with a script URL and service worker - * options. The script URL and options are the same as those used when - * calling `navigator.serviceWorker.register(scriptURL, options)`. See: - * https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register - */ - constructor(scriptURL: string, registerOptions?: RegistrationOptions); - - /** - * Registers a service worker for this instances script URL and service - * worker options. By default this method delays registration until after - * the window has loaded. - */ - register(): Promise; - - /** - * Resolves to the service worker registered by this instance as soon as it - * is active. If a service worker was already controlling at registration - * time then it will resolve to that if the script URLs (and optionally - * script versions) match, otherwise it will wait until an update is found - * and activates. - */ +export class Workbox extends EventTargetShim { readonly active: Promise; - - /** - * Resolves to the service worker registered by this instance as soon as it - * is controlling the page. If a service worker was already controlling at - * registration time then it will resolve to that if the script URLs (and - * optionally script versions) match, otherwise it will wait until an update - * is found and starts controlling the page. - * Note: the first time a service worker is installed it will active but - * not start controlling the page unless `clients.claim()` is called in the - * service worker. - */ readonly controlling: Promise; - - /** - * Resolves with a reference to a service worker that matches the script URL - * of this instance, as soon as it's available. - * - * If, at registration time, there's already an active or waiting service - * worker with a matching script URL, it will be used (with the waiting - * service worker taking precedence over the active service worker if both - * match, since the waiting service worker would have been registered more - * recently). - * If there's no matching active or waiting service worker at registration - * time then the promise will not resolve until an update is found and starts - * installing, at which point the installing service worker is used. - */ + constructor(scriptURL: string, registerOptions?: RegistrationOptions); + addEventListener(type: K, listener: (this: Workbox, ev: WorkboxEventMap[K]) => void): void; + removeEventListener(type: K, listener: (this: Workbox, ev: WorkboxEventMap[K]) => void): void; getSW(): Promise; - - /** - * Sends the passed data object to the service worker registered by this - * instance (via [`getSW()`]{@link module:workbox-window.Workbox#getSW}) and resolves - * with a response (if any). - * - * A response can be set in a message handler in the service worker by - * calling `event.ports[0].postMessage(...)`, which will resolve the promise - * returned by `messageSW()`. If no response is set, the promise will never - * resolve. - */ - messageSW(data: any): Promise; - - addEventListener(type: K, listener: (this: Workbox, ev: WokerboxEventMap[K]) => void): void; - removeEventListener(type: K, listener: (this: Workbox, ev: WokerboxEventMap[K]) => void): void; + messageSW(data: any): Promise; + register(options?: Workbox.RegisterOptions): Promise; } -export { Workbox }; +export namespace Workbox { + interface RegisterOptions { + immediate?: boolean; + } +} diff --git a/types/workbox-window/index.d.ts b/types/workbox-window/index.d.ts index 77b540c9b4..34243a87a2 100644 --- a/types/workbox-window/index.d.ts +++ b/types/workbox-window/index.d.ts @@ -1,8 +1,12 @@ // Type definitions for workbox-window 4.3 // Project: https://github.com/GoogleChrome/workbox/tree/master/packages/workbox-window, https://github.com/GoogleChrome/workbox // Definitions by: Yamagishi Kazutoshi +// Jason Kwok // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 -export { Workbox } from './Workbox'; -export { messageSW } from './messageSW'; +export * from './Workbox'; +export * from './messageSW'; + +export * from "./types/WorkboxEvent"; +export * from "./types/WorkboxEventMap"; diff --git a/types/workbox-window/messageSW.d.ts b/types/workbox-window/messageSW.d.ts index 2fa4fcb176..528f3d8380 100644 --- a/types/workbox-window/messageSW.d.ts +++ b/types/workbox-window/messageSW.d.ts @@ -1,12 +1 @@ -/** - * Sends a data object to a service worker via `postMessage` and resolves with - * a response (if any). - * - * A response can be set in a message handler in the service worker by - * calling `event.ports[0].postMessage(...)`, which will resolve the promise - * returned by `messageSW()`. If no response is set, the promise will not - * resolve. - */ -declare function messageSW(sw: ServiceWorker, data: object): Promise; - -export { messageSW }; +export function messageSW(sw: ServiceWorker, data: any): Promise; diff --git a/types/workbox-window/tsconfig.json b/types/workbox-window/tsconfig.json index 8c47214a8b..342b69bb5f 100644 --- a/types/workbox-window/tsconfig.json +++ b/types/workbox-window/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", + "es2015", "webworker" ], "noImplicitAny": true, @@ -21,8 +21,9 @@ "index.d.ts", "Workbox.d.ts", "messageSW.d.ts", + "types/WorkboxEvent.d.ts", + "types/WorkboxEventMap.d.ts", "utils/EventTargetShim.d.ts", - "utils/WorkboxEvent.d.ts", "workbox-window-tests.ts" ] } diff --git a/types/workbox-window/types/WorkboxEvent.d.ts b/types/workbox-window/types/WorkboxEvent.d.ts new file mode 100644 index 0000000000..d5a614966f --- /dev/null +++ b/types/workbox-window/types/WorkboxEvent.d.ts @@ -0,0 +1,7 @@ +import { Workbox } from '../Workbox'; + +export interface WorkboxEvent { + readonly originalEvent: Event; + readonly type: string; + readonly target: Workbox; +} diff --git a/types/workbox-window/types/WorkboxEventMap.d.ts b/types/workbox-window/types/WorkboxEventMap.d.ts new file mode 100644 index 0000000000..024f342894 --- /dev/null +++ b/types/workbox-window/types/WorkboxEventMap.d.ts @@ -0,0 +1,29 @@ +import { WorkboxEvent } from "../types/WorkboxEvent"; + +export interface WorkboxEventMap { + message: WorkboxMessageEvent; + installed: WorkboxUpdatableEvent; + waiting: WorkboxWaitingEvent; + controlling: WorkboxEvent; + activated: WorkboxUpdatableEvent; + redundant: WorkboxEvent; + externalinstalled: WorkboxExtendableEvent; + externalwaiting: WorkboxExtendableEvent; + externalactivated: WorkboxExtendableEvent; +} + +export interface WorkboxMessageEvent extends WorkboxEvent { + readonly data: any; +} + +export interface WorkboxExtendableEvent extends WorkboxEvent { + readonly sw: ServiceWorker; +} + +export interface WorkboxUpdatableEvent extends WorkboxExtendableEvent { + readonly isUpdate?: boolean; +} + +export interface WorkboxWaitingEvent extends WorkboxUpdatableEvent { + readonly wasWaitingBeforeRegister?: boolean; +} diff --git a/types/workbox-window/utils/EventTargetShim.d.ts b/types/workbox-window/utils/EventTargetShim.d.ts index ea83cf8a26..fc810cff65 100644 --- a/types/workbox-window/utils/EventTargetShim.d.ts +++ b/types/workbox-window/utils/EventTargetShim.d.ts @@ -1,18 +1,13 @@ -import { WorkboxEvent } from './WorkboxEvent'; +import { WorkboxEvent } from "../types/WorkboxEvent"; -interface EventListenerShim { - (evt: WorkboxEvent): void; -} - -/** - * A minimal `EventTarget` shim. - * This is necessary because not all browsers support constructable - * `EventTarget`, so using a real `EventTarget` will error. - */ -declare class EventTargetShim { +export class EventTargetShim { addEventListener(type: string, listener: EventListenerShim): void; removeEventListener(type: string, listener: EventListenerShim): void; dispatchEvent(evt: WorkboxEvent): void; } -export { EventTargetShim }; +export {}; + +interface EventListenerShim { + (evt: WorkboxEvent): void; +} diff --git a/types/workbox-window/utils/WorkboxEvent.d.ts b/types/workbox-window/utils/WorkboxEvent.d.ts deleted file mode 100644 index c533635b0a..0000000000 --- a/types/workbox-window/utils/WorkboxEvent.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { Workbox } from '../Workbox'; - -/** - * A minimal `Event` subclass shim. - * This doesn't *actually* subclass `Event` because not all browsers support - * constructable `EventTarget`, and using a real `Event` will error. - */ -interface WorkboxEvent { - /** - * The original event. - */ - readonly originalEvent: Event; - - /** - * The event type. - */ - readonly type: string; - - /** - * The `Workbox` instance. - */ - readonly target: Workbox; -} - -export { WorkboxEvent }; diff --git a/types/workbox-window/workbox-window-tests.ts b/types/workbox-window/workbox-window-tests.ts index 0e5735a01b..e0eade8be7 100644 --- a/types/workbox-window/workbox-window-tests.ts +++ b/types/workbox-window/workbox-window-tests.ts @@ -1,16 +1,69 @@ -import { Workbox } from 'workbox-window'; +/* tslint:disable:comment-format no-namespace */ -{ - const wb = new Workbox('/sw.js'); +"use strict"; - wb.addEventListener('message', (event) => { - event.target; // $ExpectType Workbox - event.data; // $ExpectType any - }); +import { + Workbox, + WorkboxEvent, + WorkboxEventMap, + messageSW, +} from "workbox-window"; - wb.addEventListener('waiting', (event) => { - event.isUpdate; // $ExpectType boolean | undefined - }); +//============================================================================== +// WorkboxWindow.Workbox +//============================================================================== - wb.register(); // $ExpectType Promise +export namespace WorkboxTest { + declare const url: string; + declare const options: RegistrationOptions; + + // $ExpectType Workbox + new Workbox(url); + // $ExpectType Workbox + new Workbox(url, options); + + declare const workbox: Workbox; + declare const event: WorkboxEvent; + declare const eventListener: () => void; + declare const eventType: keyof WorkboxEventMap; + declare const messageData: any; + declare const registerOptions: Workbox.RegisterOptions; + + // $ExpectType Promise + workbox.active; + + // $ExpectType Promise + workbox.controlling; + + // $ExpectType void + workbox.addEventListener(eventType, eventListener); + + // $ExpectType void + workbox.dispatchEvent(event); + + // $ExpectType Promise + workbox.getSW(); + + // $ExpectType Promise + workbox.messageSW(messageData); + + // $ExpectType Promise + workbox.register(); + // $ExpectType Promise + workbox.register(registerOptions); + + // $ExpectType void + workbox.removeEventListener(eventType, eventListener); +} + +//============================================================================== +// WorkboxWindow.messageSW +//============================================================================== + +export namespace MessageSWTest { + declare const data: any; + declare const worker: ServiceWorker; + + // $ExpectType Promise + messageSW(worker, data); }