diff --git a/.github/workflows/scorecards-analysis.yml b/.github/workflows/scorecards-analysis.yml new file mode 100644 index 0000000000..68a9025b2e --- /dev/null +++ b/.github/workflows/scorecards-analysis.yml @@ -0,0 +1,55 @@ +name: Scorecards supply-chain security +on: + # Only the default branch is supported. + branch_protection_rule: + schedule: + - cron: '33 8 * * 4' + push: + branches: [ v6 ] + +# Declare default permissions as read only. +permissions: read-all + +jobs: + analysis: + name: Scorecards analysis + runs-on: ubuntu-latest + permissions: + # Needed to upload the results to code-scanning dashboard. + security-events: write + actions: read + contents: read + + steps: + - name: "Checkout code" + uses: actions/checkout@ec3a7ce113134d7a93b817d10a8272cb61118579 # v2.4.0 + with: + persist-credentials: false + + - name: "Run analysis" + uses: ossf/scorecard-action@c8416b0b2bf627c349ca92fc8e3de51a64b005cf # v1.0.2 + with: + results_file: results.sarif + results_format: sarif + # Read-only PAT token. To create it, + # follow the steps in https://github.com/ossf/scorecard-action#pat-token-creation. + repo_token: ${{ secrets.SCORECARD_READ_TOKEN }} + # Publish the results to enable scorecard badges. For more details, see + # https://github.com/ossf/scorecard-action#publishing-results. + # For private repositories, `publish_results` will automatically be set to `false`, + # regardless of the value entered here. + publish_results: true + + # Upload the results as artifacts (optional). + - name: "Upload artifact" + uses: actions/upload-artifact@82c141cc518b40d92cc801eee768e7aafc9c2fa2 # v2.3.1 + with: + name: SARIF file + path: results.sarif + retention-days: 5 + + # Upload the results to GitHub's code scanning dashboard. + - name: "Upload to code-scanning" + uses: github/codeql-action/upload-sarif@5f532563584d71fdef14ee64d17bafb34f751ce5 # v1.0.26 + with: + sarif_file: results.sarif diff --git a/packages/workbox-background-sync/src/Queue.ts b/packages/workbox-background-sync/src/Queue.ts index d98aff23ae..4e05183964 100644 --- a/packages/workbox-background-sync/src/Queue.ts +++ b/packages/workbox-background-sync/src/Queue.ts @@ -11,7 +11,7 @@ import {logger} from 'workbox-core/_private/logger.js'; import {assert} from 'workbox-core/_private/assert.js'; import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; import {QueueStore} from './lib/QueueStore.js'; -import {UnidentifiedQueueStoreEntry} from './lib/QueueDb.js'; +import {QueueStoreEntry, UnidentifiedQueueStoreEntry} from './lib/QueueDb.js'; import {StorableRequest} from './lib/StorableRequest.js'; import './_version.js'; @@ -27,8 +27,9 @@ interface OnSyncCallback { } export interface QueueOptions { - onSync?: OnSyncCallback; + forceSyncFallback?: boolean; maxRetentionTime?: number; + onSync?: OnSyncCallback; } interface QueueEntry { @@ -79,6 +80,7 @@ class Queue { private readonly _onSync: OnSyncCallback; private readonly _maxRetentionTime: number; private readonly _queueStore: QueueStore; + private readonly _forceSyncFallback: boolean; private _syncInProgress = false; private _requestsAddedDuringSync = false; @@ -100,8 +102,17 @@ class Queue { * @param {number} [options.maxRetentionTime=7 days] 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. + * @param {boolean} [options.forceSyncFallback=false] If `true`, instead + * of attempting to use background sync events, always attempt to replay + * queued request at service worker startup. Most folks will not need + * this, unless you explicitly target a runtime like Electron that + * exposes the interfaces for background sync, but does not have a working + * implementation. */ - constructor(name: string, {onSync, maxRetentionTime}: QueueOptions = {}) { + constructor( + name: string, + {forceSyncFallback, onSync, maxRetentionTime}: QueueOptions = {}, + ) { // Ensure the store name is not already being used if (queueNames.has(name)) { throw new WorkboxError('duplicate-queue-name', {name}); @@ -112,6 +123,7 @@ class Queue { this._name = name; this._onSync = onSync || this.replayRequests; this._maxRetentionTime = maxRetentionTime || MAX_RETENTION_TIME; + this._forceSyncFallback = Boolean(forceSyncFallback); this._queueStore = new QueueStore(this._name); this._addSyncListener(); @@ -276,7 +288,14 @@ class Queue { entry.metadata = metadata; } - await this._queueStore[`${operation}Entry`](entry); + switch (operation) { + case 'push': + await this._queueStore.pushEntry(entry); + break; + case 'unshift': + await this._queueStore.unshiftEntry(entry); + break; + } if (process.env.NODE_ENV !== 'production') { logger.log( @@ -307,7 +326,15 @@ class Queue { operation: 'pop' | 'shift', ): Promise { const now = Date.now(); - const entry = await this._queueStore[`${operation}Entry`](); + let entry: QueueStoreEntry | undefined; + switch (operation) { + case 'pop': + entry = await this._queueStore.popEntry(); + break; + case 'shift': + entry = await this._queueStore.shiftEntry(); + break; + } if (entry) { // Ignore requests older than maxRetentionTime. Call this function @@ -364,7 +391,8 @@ class Queue { * Registers a sync event with a tag unique to this instance. */ async registerSync(): Promise { - if ('sync' in self.registration) { + // See https://github.com/GoogleChrome/workbox/issues/2393 + if ('sync' in self.registration && !this._forceSyncFallback) { try { await self.registration.sync.register(`${TAG_PREFIX}:${this._name}`); } catch (err) { @@ -382,13 +410,14 @@ class Queue { /** * In sync-supporting browsers, this adds a listener for the sync event. - * In non-sync-supporting browsers, this will retry the queue on service - * worker startup. + * In non-sync-supporting browsers, or if _forceSyncFallback is true, this + * will retry the queue on service worker startup. * * @private */ private _addSyncListener() { - if ('sync' in self.registration) { + // See https://github.com/GoogleChrome/workbox/issues/2393 + if ('sync' in self.registration && !this._forceSyncFallback) { self.addEventListener('sync', (event: SyncEvent) => { if (event.tag === `${TAG_PREFIX}:${this._name}`) { if (process.env.NODE_ENV !== 'production') { @@ -435,8 +464,9 @@ class Queue { if (process.env.NODE_ENV !== 'production') { logger.log(`Background sync replaying without background sync event`); } - // If the browser doesn't support background sync, retry - // every time the service worker starts up as a fallback. + // If the browser doesn't support background sync, or the developer has + // opted-in to not using it, retry every time the service worker starts up + // as a fallback. void this._onSync({queue: this}); } } diff --git a/packages/workbox-build/src/schema/GenerateSWOptions.json b/packages/workbox-build/src/schema/GenerateSWOptions.json index b50f1a39e9..0743134e6b 100644 --- a/packages/workbox-build/src/schema/GenerateSWOptions.json +++ b/packages/workbox-build/src/schema/GenerateSWOptions.json @@ -3,6 +3,7 @@ "type": "object", "properties": { "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", "type": "array", "items": { "anyOf": [ @@ -16,27 +17,33 @@ } }, "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", "$ref": "#/definitions/RegExp" }, "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", "type": "array", "items": {} }, "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", "default": 2097152, "type": "number" }, "modifyURLPrefix": { + "description": "A mapping of prefixes that, if present in an entry in the precache\nmanifest, will be replaced with the corresponding value. This can be used\nto, for example, remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.", "type": "object", "additionalProperties": { "type": "string" } }, "globFollow": { + "description": "Determines whether or not symlinks are followed when generating the\nprecache manifest. For more information, see the definition of `follow` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", "default": true, "type": "boolean" }, "globIgnores": { + "description": "A set of patterns matching files to always exclude when generating the\nprecache manifest. For more information, see the definition of `ignore` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", "default": [ "**/node_modules/**/*" ], @@ -46,6 +53,7 @@ } }, "globPatterns": { + "description": "Files matching any of these patterns will be included in the precache\nmanifest. For more information, see the\n[`glob` primer](https://github.com/isaacs/node-glob#glob-primer).", "default": [ "**/*.{js,css,html}" ], @@ -55,10 +63,12 @@ } }, "globStrict": { + "description": "If true, an error reading a directory when generating a precache manifest\nwill cause the build to fail. If false, the problematic directory will be\nskipped. For more information, see the definition of `strict` in the `glob`\n[documentation](https://github.com/isaacs/node-glob#options).", "default": true, "type": "boolean" }, "templatedURLs": { + "description": "If a URL is rendered based on some server-side logic, its contents may\ndepend on multiple files or on some other unique string value. The keys in\nthis object are server-rendered URLs. If the values are an array of\nstrings, they will be interpreted as `glob` patterns, and the contents of\nany files matching the patterns will be used to uniquely version the URL.\nIf used with a single string, it will be interpreted as unique versioning\ninformation that you've generated for a given URL.", "type": "object", "additionalProperties": { "anyOf": [ @@ -75,6 +85,7 @@ } }, "babelPresetEnvTargets": { + "description": "The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass\nto `babel-preset-env` when transpiling the service worker bundle.", "default": [ "chrome >= 56" ], @@ -84,20 +95,24 @@ } }, "cacheId": { + "description": "An optional ID to be prepended to cache names. This is primarily useful for\nlocal development where multiple sites may be served from the same\n`http://localhost:port` origin.", "type": [ "null", "string" ] }, "cleanupOutdatedCaches": { + "description": "Whether or not Workbox should attempt to identify and delete any precaches\ncreated by older, incompatible versions.", "default": false, "type": "boolean" }, "clientsClaim": { + "description": "Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)\nany existing clients as soon as it activates.", "default": false, "type": "boolean" }, "directoryIndex": { + "description": "If a navigation request for a URL ending in `/` fails to match a precached\nURL, this value will be appended to the URL and that will be checked for a\nprecache match. This should be set to what your web server is using for its\ndirectory index.", "type": [ "null", "string" @@ -108,22 +123,26 @@ "type": "boolean" }, "ignoreURLParametersMatching": { + "description": "Any search parameter names that match against one of the RegExp in this\narray will be removed before looking for a precache match. This is useful\nif your users might request URLs that contain, for example, URL parameters\nused to track the source of the traffic. If not provided, the default value\nis `[/^utm_/, /^fbclid$/]`.", "type": "array", "items": { "$ref": "#/definitions/RegExp" } }, "importScripts": { + "description": "A list of JavaScript files that should be passed to\n[`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)\ninside the generated service worker file. This is useful when you want to\nlet Workbox create your top-level service worker file, but want to include\nsome additional code, such as a push event listener.", "type": "array", "items": { "type": "string" } }, "inlineWorkboxRuntime": { + "description": "Whether the runtime code for the Workbox library should be included in the\ntop-level service worker, or split into a separate file that needs to be\ndeployed alongside the service worker. Keeping the runtime separate means\nthat users will not have to re-download the Workbox code each time your\ntop-level service worker changes.", "default": false, "type": "boolean" }, "mode": { + "description": "If set to 'production', then an optimized service worker bundle that\nexcludes debugging info will be produced. If not explicitly configured\nhere, the `process.env.NODE_ENV` value will be used, and failing that, it\nwill fall back to `'production'`.", "default": "production", "type": [ "null", @@ -131,6 +150,7 @@ ] }, "navigateFallback": { + "description": "If specified, all\n[navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)\nfor URLs that aren't precached will be fulfilled with the HTML at the URL\nprovided. You must pass in the URL of an HTML document that is listed in\nyour precache manifest. This is meant to be used in a Single Page App\nscenario, in which you want all navigations to use common\n[App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).", "default": null, "type": [ "null", @@ -138,23 +158,26 @@ ] }, "navigateFallbackAllowlist": { + "description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedent.", "type": "array", "items": { "$ref": "#/definitions/RegExp" } }, "navigateFallbackDenylist": { + "description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedence.", "type": "array", "items": { "$ref": "#/definitions/RegExp" } }, "navigationPreload": { - "description": "navigationPreload is only valid when runtimeCaching is configured. However,\nthis can't be expressed via TypeScript, so it's enforced via runtime logic.", + "description": "Whether or not to enable\n[navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)\nin the generated service worker. When set to true, you must also use\n`runtimeCaching` to set up an appropriate response strategy that will match\nnavigation requests, and make use of the preloaded response.", "default": false, "type": "boolean" }, "offlineGoogleAnalytics": { + "description": "Controls whether or not to include support for\n[offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).\nWhen `true`, the call to `workbox-google-analytics`'s `initialize()` will\nbe added to your generated service worker. When set to an `Object`, that\nobject will be passed in to the `initialize()` call, allowing you to\ncustomize the behavior.", "default": false, "anyOf": [ { @@ -166,23 +189,28 @@ ] }, "runtimeCaching": { + "description": "When using Workbox's build tools to generate your service worker, you can\nspecify one or more runtime caching configurations. These are then\ntranslated to {@link workbox-routing.registerRoute} calls using the match\nand handler configuration you define.\n\nFor all of the options, see the {@link workbox-build.RuntimeCaching}\ndocumentation. The example below shows a typical configuration, with two\nruntime routes defined:", "type": "array", "items": { "$ref": "#/definitions/RuntimeCaching" } }, "skipWaiting": { + "description": "Whether to add an unconditional call to [`skipWaiting()`](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#skip_the_waiting_phase)\nto the generated service worker. If `false`, then a `message` listener will\nbe added instead, allowing client pages to trigger `skipWaiting()` by\ncalling `postMessage({type: 'SKIP_WAITING'})` on a waiting service worker.", "default": false, "type": "boolean" }, "sourcemap": { + "description": "Whether to create a sourcemap for the generated service worker files.", "default": true, "type": "boolean" }, "swDest": { + "description": "The path and filename of the service worker file that will be created by\nthe build process, relative to the current working directory. It must end\nin '.js'.", "type": "string" }, "globDirectory": { + "description": "The local directory you wish to match `globPatterns` against. The path is\nrelative to the current directory.", "type": "string" } }, @@ -279,6 +307,7 @@ "type": "object", "properties": { "handler": { + "description": "This determines how the runtime route will generate a response.\nTo use one of the built-in {@link workbox-strategies}, provide its name,\nlike `'NetworkFirst'`.\nAlternatively, this can be a {@link workbox-core.RouteHandler} callback\nfunction with custom response logic.", "anyOf": [ { "$ref": "#/definitions/RouteHandlerCallback" @@ -299,6 +328,8 @@ ] }, "method": { + "description": "The HTTP method to match against. The default value of `'GET'` is normally\nsufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or\nanother type of request.", + "default": "GET", "enum": [ "DELETE", "GET", @@ -313,6 +344,7 @@ "type": "object", "properties": { "backgroundSync": { + "description": "Configuring this will add a\n{@link workbox-background-sync.BackgroundSyncPlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "name": { @@ -328,6 +360,7 @@ ] }, "broadcastUpdate": { + "description": "Configuring this will add a\n{@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "channelName": { @@ -343,27 +376,33 @@ ] }, "cacheableResponse": { + "description": "Configuring this will add a\n{@link workbox-cacheable-response.CacheableResponsePlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/CacheableResponseOptions" }, "cacheName": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`.", "type": [ "null", "string" ] }, "expiration": { + "description": "Configuring this will add a\n{@link workbox-expiration.ExpirationPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/ExpirationPluginOptions" }, "networkTimeoutSeconds": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`. Note that only\n`'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.", "type": "number" }, "plugins": { + "description": "Configuring this allows the use of one or more Workbox plugins that\ndon't have \"shortcut\" options (like `expiration` for\n{@link workbox-expiration.ExpirationPlugin}). The plugins provided here\nwill be added to the {@link workbox-strategies} configured in `handler`.", "type": "array", "items": { "$ref": "#/definitions/WorkboxPlugin" } }, "precacheFallback": { + "description": "Configuring this will add a\n{@link workbox-precaching.PrecacheFallbackPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "fallbackURL": { @@ -376,18 +415,22 @@ ] }, "rangeRequests": { + "description": "Enabling this will add a\n{@link workbox-range-requests.RangeRequestsPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "type": "boolean" }, "fetchOptions": { + "description": "Configuring this will pass along the `fetchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/RequestInit" }, "matchOptions": { + "description": "Configuring this will pass along the `matchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/CacheQueryOptions" } }, "additionalProperties": false }, "urlPattern": { + "description": "This match criteria determines whether the configured handler will\ngenerate a response for any requests that don't match one of the precached\nURLs. If multiple `RuntimeCaching` routes are defined, then the first one\nwhose `urlPattern` matches will be the one that responds.\n\nThis value directly maps to the first parameter passed to\n{@link workbox-routing.registerRoute}. It's recommended to use a\n{@link workbox-core.RouteMatchCallback} function for greatest flexibility.", "anyOf": [ { "$ref": "#/definitions/RegExp" diff --git a/packages/workbox-build/src/schema/GetManifestOptions.json b/packages/workbox-build/src/schema/GetManifestOptions.json index 84c9a0a9ba..9fd2d9740e 100644 --- a/packages/workbox-build/src/schema/GetManifestOptions.json +++ b/packages/workbox-build/src/schema/GetManifestOptions.json @@ -3,6 +3,7 @@ "type": "object", "properties": { "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", "type": "array", "items": { "anyOf": [ @@ -16,27 +17,33 @@ } }, "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", "$ref": "#/definitions/RegExp" }, "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", "type": "array", "items": {} }, "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", "default": 2097152, "type": "number" }, "modifyURLPrefix": { + "description": "A mapping of prefixes that, if present in an entry in the precache\nmanifest, will be replaced with the corresponding value. This can be used\nto, for example, remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.", "type": "object", "additionalProperties": { "type": "string" } }, "globFollow": { + "description": "Determines whether or not symlinks are followed when generating the\nprecache manifest. For more information, see the definition of `follow` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", "default": true, "type": "boolean" }, "globIgnores": { + "description": "A set of patterns matching files to always exclude when generating the\nprecache manifest. For more information, see the definition of `ignore` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", "default": [ "**/node_modules/**/*" ], @@ -46,6 +53,7 @@ } }, "globPatterns": { + "description": "Files matching any of these patterns will be included in the precache\nmanifest. For more information, see the\n[`glob` primer](https://github.com/isaacs/node-glob#glob-primer).", "default": [ "**/*.{js,css,html}" ], @@ -55,10 +63,12 @@ } }, "globStrict": { + "description": "If true, an error reading a directory when generating a precache manifest\nwill cause the build to fail. If false, the problematic directory will be\nskipped. For more information, see the definition of `strict` in the `glob`\n[documentation](https://github.com/isaacs/node-glob#options).", "default": true, "type": "boolean" }, "templatedURLs": { + "description": "If a URL is rendered based on some server-side logic, its contents may\ndepend on multiple files or on some other unique string value. The keys in\nthis object are server-rendered URLs. If the values are an array of\nstrings, they will be interpreted as `glob` patterns, and the contents of\nany files matching the patterns will be used to uniquely version the URL.\nIf used with a single string, it will be interpreted as unique versioning\ninformation that you've generated for a given URL.", "type": "object", "additionalProperties": { "anyOf": [ @@ -75,6 +85,7 @@ } }, "globDirectory": { + "description": "The local directory you wish to match `globPatterns` against. The path is\nrelative to the current directory.", "type": "string" } }, @@ -171,6 +182,7 @@ "type": "object", "properties": { "handler": { + "description": "This determines how the runtime route will generate a response.\nTo use one of the built-in {@link workbox-strategies}, provide its name,\nlike `'NetworkFirst'`.\nAlternatively, this can be a {@link workbox-core.RouteHandler} callback\nfunction with custom response logic.", "anyOf": [ { "$ref": "#/definitions/RouteHandlerCallback" @@ -191,6 +203,8 @@ ] }, "method": { + "description": "The HTTP method to match against. The default value of `'GET'` is normally\nsufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or\nanother type of request.", + "default": "GET", "enum": [ "DELETE", "GET", @@ -205,6 +219,7 @@ "type": "object", "properties": { "backgroundSync": { + "description": "Configuring this will add a\n{@link workbox-background-sync.BackgroundSyncPlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "name": { @@ -220,6 +235,7 @@ ] }, "broadcastUpdate": { + "description": "Configuring this will add a\n{@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "channelName": { @@ -235,27 +251,33 @@ ] }, "cacheableResponse": { + "description": "Configuring this will add a\n{@link workbox-cacheable-response.CacheableResponsePlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/CacheableResponseOptions" }, "cacheName": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`.", "type": [ "null", "string" ] }, "expiration": { + "description": "Configuring this will add a\n{@link workbox-expiration.ExpirationPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/ExpirationPluginOptions" }, "networkTimeoutSeconds": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`. Note that only\n`'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.", "type": "number" }, "plugins": { + "description": "Configuring this allows the use of one or more Workbox plugins that\ndon't have \"shortcut\" options (like `expiration` for\n{@link workbox-expiration.ExpirationPlugin}). The plugins provided here\nwill be added to the {@link workbox-strategies} configured in `handler`.", "type": "array", "items": { "$ref": "#/definitions/WorkboxPlugin" } }, "precacheFallback": { + "description": "Configuring this will add a\n{@link workbox-precaching.PrecacheFallbackPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "fallbackURL": { @@ -268,18 +290,22 @@ ] }, "rangeRequests": { + "description": "Enabling this will add a\n{@link workbox-range-requests.RangeRequestsPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "type": "boolean" }, "fetchOptions": { + "description": "Configuring this will pass along the `fetchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/RequestInit" }, "matchOptions": { + "description": "Configuring this will pass along the `matchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/CacheQueryOptions" } }, "additionalProperties": false }, "urlPattern": { + "description": "This match criteria determines whether the configured handler will\ngenerate a response for any requests that don't match one of the precached\nURLs. If multiple `RuntimeCaching` routes are defined, then the first one\nwhose `urlPattern` matches will be the one that responds.\n\nThis value directly maps to the first parameter passed to\n{@link workbox-routing.registerRoute}. It's recommended to use a\n{@link workbox-core.RouteMatchCallback} function for greatest flexibility.", "anyOf": [ { "$ref": "#/definitions/RegExp" diff --git a/packages/workbox-build/src/schema/InjectManifestOptions.json b/packages/workbox-build/src/schema/InjectManifestOptions.json index 12b6ab0371..c12aa79225 100644 --- a/packages/workbox-build/src/schema/InjectManifestOptions.json +++ b/packages/workbox-build/src/schema/InjectManifestOptions.json @@ -3,6 +3,7 @@ "type": "object", "properties": { "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", "type": "array", "items": { "anyOf": [ @@ -16,27 +17,33 @@ } }, "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", "$ref": "#/definitions/RegExp" }, "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", "type": "array", "items": {} }, "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", "default": 2097152, "type": "number" }, "modifyURLPrefix": { + "description": "A mapping of prefixes that, if present in an entry in the precache\nmanifest, will be replaced with the corresponding value. This can be used\nto, for example, remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.", "type": "object", "additionalProperties": { "type": "string" } }, "globFollow": { + "description": "Determines whether or not symlinks are followed when generating the\nprecache manifest. For more information, see the definition of `follow` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", "default": true, "type": "boolean" }, "globIgnores": { + "description": "A set of patterns matching files to always exclude when generating the\nprecache manifest. For more information, see the definition of `ignore` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).", "default": [ "**/node_modules/**/*" ], @@ -46,6 +53,7 @@ } }, "globPatterns": { + "description": "Files matching any of these patterns will be included in the precache\nmanifest. For more information, see the\n[`glob` primer](https://github.com/isaacs/node-glob#glob-primer).", "default": [ "**/*.{js,css,html}" ], @@ -55,10 +63,12 @@ } }, "globStrict": { + "description": "If true, an error reading a directory when generating a precache manifest\nwill cause the build to fail. If false, the problematic directory will be\nskipped. For more information, see the definition of `strict` in the `glob`\n[documentation](https://github.com/isaacs/node-glob#options).", "default": true, "type": "boolean" }, "templatedURLs": { + "description": "If a URL is rendered based on some server-side logic, its contents may\ndepend on multiple files or on some other unique string value. The keys in\nthis object are server-rendered URLs. If the values are an array of\nstrings, they will be interpreted as `glob` patterns, and the contents of\nany files matching the patterns will be used to uniquely version the URL.\nIf used with a single string, it will be interpreted as unique versioning\ninformation that you've generated for a given URL.", "type": "object", "additionalProperties": { "anyOf": [ @@ -75,16 +85,20 @@ } }, "injectionPoint": { + "description": "The string to find inside of the `swSrc` file. Once found, it will be\nreplaced by the generated precache manifest.", "default": "self.__WB_MANIFEST", "type": "string" }, "swSrc": { + "description": "The path and filename of the service worker file that will be read during\nthe build process, relative to the current working directory.", "type": "string" }, "swDest": { + "description": "The path and filename of the service worker file that will be created by\nthe build process, relative to the current working directory. It must end\nin '.js'.", "type": "string" }, "globDirectory": { + "description": "The local directory you wish to match `globPatterns` against. The path is\nrelative to the current directory.", "type": "string" } }, @@ -183,6 +197,7 @@ "type": "object", "properties": { "handler": { + "description": "This determines how the runtime route will generate a response.\nTo use one of the built-in {@link workbox-strategies}, provide its name,\nlike `'NetworkFirst'`.\nAlternatively, this can be a {@link workbox-core.RouteHandler} callback\nfunction with custom response logic.", "anyOf": [ { "$ref": "#/definitions/RouteHandlerCallback" @@ -203,6 +218,8 @@ ] }, "method": { + "description": "The HTTP method to match against. The default value of `'GET'` is normally\nsufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or\nanother type of request.", + "default": "GET", "enum": [ "DELETE", "GET", @@ -217,6 +234,7 @@ "type": "object", "properties": { "backgroundSync": { + "description": "Configuring this will add a\n{@link workbox-background-sync.BackgroundSyncPlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "name": { @@ -232,6 +250,7 @@ ] }, "broadcastUpdate": { + "description": "Configuring this will add a\n{@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "channelName": { @@ -247,27 +266,33 @@ ] }, "cacheableResponse": { + "description": "Configuring this will add a\n{@link workbox-cacheable-response.CacheableResponsePlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/CacheableResponseOptions" }, "cacheName": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`.", "type": [ "null", "string" ] }, "expiration": { + "description": "Configuring this will add a\n{@link workbox-expiration.ExpirationPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/ExpirationPluginOptions" }, "networkTimeoutSeconds": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`. Note that only\n`'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.", "type": "number" }, "plugins": { + "description": "Configuring this allows the use of one or more Workbox plugins that\ndon't have \"shortcut\" options (like `expiration` for\n{@link workbox-expiration.ExpirationPlugin}). The plugins provided here\nwill be added to the {@link workbox-strategies} configured in `handler`.", "type": "array", "items": { "$ref": "#/definitions/WorkboxPlugin" } }, "precacheFallback": { + "description": "Configuring this will add a\n{@link workbox-precaching.PrecacheFallbackPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "fallbackURL": { @@ -280,18 +305,22 @@ ] }, "rangeRequests": { + "description": "Enabling this will add a\n{@link workbox-range-requests.RangeRequestsPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "type": "boolean" }, "fetchOptions": { + "description": "Configuring this will pass along the `fetchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/RequestInit" }, "matchOptions": { + "description": "Configuring this will pass along the `matchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/CacheQueryOptions" } }, "additionalProperties": false }, "urlPattern": { + "description": "This match criteria determines whether the configured handler will\ngenerate a response for any requests that don't match one of the precached\nURLs. If multiple `RuntimeCaching` routes are defined, then the first one\nwhose `urlPattern` matches will be the one that responds.\n\nThis value directly maps to the first parameter passed to\n{@link workbox-routing.registerRoute}. It's recommended to use a\n{@link workbox-core.RouteMatchCallback} function for greatest flexibility.", "anyOf": [ { "$ref": "#/definitions/RegExp" diff --git a/packages/workbox-build/src/schema/WebpackGenerateSWOptions.json b/packages/workbox-build/src/schema/WebpackGenerateSWOptions.json index d1826ec1e0..eb45d0d679 100644 --- a/packages/workbox-build/src/schema/WebpackGenerateSWOptions.json +++ b/packages/workbox-build/src/schema/WebpackGenerateSWOptions.json @@ -3,6 +3,7 @@ "type": "object", "properties": { "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", "type": "array", "items": { "anyOf": [ @@ -16,43 +17,52 @@ } }, "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", "$ref": "#/definitions/RegExp" }, "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", "type": "array", "items": {} }, "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", "default": 2097152, "type": "number" }, "modifyURLPrefix": { + "description": "A mapping of prefixes that, if present in an entry in the precache\nmanifest, will be replaced with the corresponding value. This can be used\nto, for example, remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.", "type": "object", "additionalProperties": { "type": "string" } }, "chunks": { + "description": "One or more chunk names whose corresponding output files should be included\nin the precache manifest.", "type": "array", "items": { "type": "string" } }, "exclude": { + "description": "One or more specifiers used to exclude assets from the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `exclude` option.\nIf not provided, the default value is `[/\\.map$/, /^manifest.*\\.js$]`.", "type": "array", "items": {} }, "excludeChunks": { + "description": "One or more chunk names whose corresponding output files should be excluded\nfrom the precache manifest.", "type": "array", "items": { "type": "string" } }, "include": { + "description": "One or more specifiers used to include assets in the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `include` option.", "type": "array", "items": {} }, "mode": { + "description": "If set to 'production', then an optimized service worker bundle that\nexcludes debugging info will be produced. If not explicitly configured\nhere, the `process.env.NODE_ENV` value will be used, and failing that, it\nwill fall back to `'production'`.", "default": "production", "type": [ "null", @@ -60,6 +70,7 @@ ] }, "babelPresetEnvTargets": { + "description": "The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass\nto `babel-preset-env` when transpiling the service worker bundle.", "default": [ "chrome >= 56" ], @@ -69,20 +80,24 @@ } }, "cacheId": { + "description": "An optional ID to be prepended to cache names. This is primarily useful for\nlocal development where multiple sites may be served from the same\n`http://localhost:port` origin.", "type": [ "null", "string" ] }, "cleanupOutdatedCaches": { + "description": "Whether or not Workbox should attempt to identify and delete any precaches\ncreated by older, incompatible versions.", "default": false, "type": "boolean" }, "clientsClaim": { + "description": "Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)\nany existing clients as soon as it activates.", "default": false, "type": "boolean" }, "directoryIndex": { + "description": "If a navigation request for a URL ending in `/` fails to match a precached\nURL, this value will be appended to the URL and that will be checked for a\nprecache match. This should be set to what your web server is using for its\ndirectory index.", "type": [ "null", "string" @@ -93,22 +108,26 @@ "type": "boolean" }, "ignoreURLParametersMatching": { + "description": "Any search parameter names that match against one of the RegExp in this\narray will be removed before looking for a precache match. This is useful\nif your users might request URLs that contain, for example, URL parameters\nused to track the source of the traffic. If not provided, the default value\nis `[/^utm_/, /^fbclid$/]`.", "type": "array", "items": { "$ref": "#/definitions/RegExp" } }, "importScripts": { + "description": "A list of JavaScript files that should be passed to\n[`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)\ninside the generated service worker file. This is useful when you want to\nlet Workbox create your top-level service worker file, but want to include\nsome additional code, such as a push event listener.", "type": "array", "items": { "type": "string" } }, "inlineWorkboxRuntime": { + "description": "Whether the runtime code for the Workbox library should be included in the\ntop-level service worker, or split into a separate file that needs to be\ndeployed alongside the service worker. Keeping the runtime separate means\nthat users will not have to re-download the Workbox code each time your\ntop-level service worker changes.", "default": false, "type": "boolean" }, "navigateFallback": { + "description": "If specified, all\n[navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)\nfor URLs that aren't precached will be fulfilled with the HTML at the URL\nprovided. You must pass in the URL of an HTML document that is listed in\nyour precache manifest. This is meant to be used in a Single Page App\nscenario, in which you want all navigations to use common\n[App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).", "default": null, "type": [ "null", @@ -116,23 +135,26 @@ ] }, "navigateFallbackAllowlist": { + "description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedent.", "type": "array", "items": { "$ref": "#/definitions/RegExp" } }, "navigateFallbackDenylist": { + "description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedence.", "type": "array", "items": { "$ref": "#/definitions/RegExp" } }, "navigationPreload": { - "description": "navigationPreload is only valid when runtimeCaching is configured. However,\nthis can't be expressed via TypeScript, so it's enforced via runtime logic.", + "description": "Whether or not to enable\n[navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)\nin the generated service worker. When set to true, you must also use\n`runtimeCaching` to set up an appropriate response strategy that will match\nnavigation requests, and make use of the preloaded response.", "default": false, "type": "boolean" }, "offlineGoogleAnalytics": { + "description": "Controls whether or not to include support for\n[offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).\nWhen `true`, the call to `workbox-google-analytics`'s `initialize()` will\nbe added to your generated service worker. When set to an `Object`, that\nobject will be passed in to the `initialize()` call, allowing you to\ncustomize the behavior.", "default": false, "anyOf": [ { @@ -144,26 +166,31 @@ ] }, "runtimeCaching": { + "description": "When using Workbox's build tools to generate your service worker, you can\nspecify one or more runtime caching configurations. These are then\ntranslated to {@link workbox-routing.registerRoute} calls using the match\nand handler configuration you define.\n\nFor all of the options, see the {@link workbox-build.RuntimeCaching}\ndocumentation. The example below shows a typical configuration, with two\nruntime routes defined:", "type": "array", "items": { "$ref": "#/definitions/RuntimeCaching" } }, "skipWaiting": { + "description": "Whether to add an unconditional call to [`skipWaiting()`](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#skip_the_waiting_phase)\nto the generated service worker. If `false`, then a `message` listener will\nbe added instead, allowing client pages to trigger `skipWaiting()` by\ncalling `postMessage({type: 'SKIP_WAITING'})` on a waiting service worker.", "default": false, "type": "boolean" }, "sourcemap": { + "description": "Whether to create a sourcemap for the generated service worker files.", "default": true, "type": "boolean" }, "importScriptsViaChunks": { + "description": "One or more names of webpack chunks. The content of those chunks will be\nincluded in the generated service worker, via a call to `importScripts()`.", "type": "array", "items": { "type": "string" } }, "swDest": { + "description": "The asset name of the service worker file created by this plugin.", "default": "service-worker.js", "type": "string" } @@ -258,6 +285,7 @@ "type": "object", "properties": { "handler": { + "description": "This determines how the runtime route will generate a response.\nTo use one of the built-in {@link workbox-strategies}, provide its name,\nlike `'NetworkFirst'`.\nAlternatively, this can be a {@link workbox-core.RouteHandler} callback\nfunction with custom response logic.", "anyOf": [ { "$ref": "#/definitions/RouteHandlerCallback" @@ -278,6 +306,8 @@ ] }, "method": { + "description": "The HTTP method to match against. The default value of `'GET'` is normally\nsufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or\nanother type of request.", + "default": "GET", "enum": [ "DELETE", "GET", @@ -292,6 +322,7 @@ "type": "object", "properties": { "backgroundSync": { + "description": "Configuring this will add a\n{@link workbox-background-sync.BackgroundSyncPlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "name": { @@ -307,6 +338,7 @@ ] }, "broadcastUpdate": { + "description": "Configuring this will add a\n{@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "channelName": { @@ -322,27 +354,33 @@ ] }, "cacheableResponse": { + "description": "Configuring this will add a\n{@link workbox-cacheable-response.CacheableResponsePlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/CacheableResponseOptions" }, "cacheName": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`.", "type": [ "null", "string" ] }, "expiration": { + "description": "Configuring this will add a\n{@link workbox-expiration.ExpirationPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/ExpirationPluginOptions" }, "networkTimeoutSeconds": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`. Note that only\n`'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.", "type": "number" }, "plugins": { + "description": "Configuring this allows the use of one or more Workbox plugins that\ndon't have \"shortcut\" options (like `expiration` for\n{@link workbox-expiration.ExpirationPlugin}). The plugins provided here\nwill be added to the {@link workbox-strategies} configured in `handler`.", "type": "array", "items": { "$ref": "#/definitions/WorkboxPlugin" } }, "precacheFallback": { + "description": "Configuring this will add a\n{@link workbox-precaching.PrecacheFallbackPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "fallbackURL": { @@ -355,18 +393,22 @@ ] }, "rangeRequests": { + "description": "Enabling this will add a\n{@link workbox-range-requests.RangeRequestsPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "type": "boolean" }, "fetchOptions": { + "description": "Configuring this will pass along the `fetchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/RequestInit" }, "matchOptions": { + "description": "Configuring this will pass along the `matchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/CacheQueryOptions" } }, "additionalProperties": false }, "urlPattern": { + "description": "This match criteria determines whether the configured handler will\ngenerate a response for any requests that don't match one of the precached\nURLs. If multiple `RuntimeCaching` routes are defined, then the first one\nwhose `urlPattern` matches will be the one that responds.\n\nThis value directly maps to the first parameter passed to\n{@link workbox-routing.registerRoute}. It's recommended to use a\n{@link workbox-core.RouteMatchCallback} function for greatest flexibility.", "anyOf": [ { "$ref": "#/definitions/RegExp" diff --git a/packages/workbox-build/src/schema/WebpackInjectManifestOptions.json b/packages/workbox-build/src/schema/WebpackInjectManifestOptions.json index b8e08d6a59..0695b9ecee 100644 --- a/packages/workbox-build/src/schema/WebpackInjectManifestOptions.json +++ b/packages/workbox-build/src/schema/WebpackInjectManifestOptions.json @@ -3,6 +3,7 @@ "type": "object", "properties": { "additionalManifestEntries": { + "description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.", "type": "array", "items": { "anyOf": [ @@ -16,63 +17,77 @@ } }, "dontCacheBustURLsMatching": { + "description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.", "$ref": "#/definitions/RegExp" }, "manifestTransforms": { + "description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.", "type": "array", "items": {} }, "maximumFileSizeToCacheInBytes": { + "description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.", "default": 2097152, "type": "number" }, "modifyURLPrefix": { + "description": "A mapping of prefixes that, if present in an entry in the precache\nmanifest, will be replaced with the corresponding value. This can be used\nto, for example, remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.", "type": "object", "additionalProperties": { "type": "string" } }, "chunks": { + "description": "One or more chunk names whose corresponding output files should be included\nin the precache manifest.", "type": "array", "items": { "type": "string" } }, "exclude": { + "description": "One or more specifiers used to exclude assets from the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `exclude` option.\nIf not provided, the default value is `[/\\.map$/, /^manifest.*\\.js$]`.", "type": "array", "items": {} }, "excludeChunks": { + "description": "One or more chunk names whose corresponding output files should be excluded\nfrom the precache manifest.", "type": "array", "items": { "type": "string" } }, "include": { + "description": "One or more specifiers used to include assets in the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `include` option.", "type": "array", "items": {} }, "mode": { + "description": "If set to 'production', then an optimized service worker bundle that\nexcludes debugging info will be produced. If not explicitly configured\nhere, the `mode` value configured in the current `webpack` compilation\nwill be used.", "type": [ "null", "string" ] }, "injectionPoint": { + "description": "The string to find inside of the `swSrc` file. Once found, it will be\nreplaced by the generated precache manifest.", "default": "self.__WB_MANIFEST", "type": "string" }, "swSrc": { + "description": "The path and filename of the service worker file that will be read during\nthe build process, relative to the current working directory.", "type": "string" }, "compileSrc": { + "description": "When `true` (the default), the `swSrc` file will be compiled by webpack.\nWhen `false`, compilation will not occur (and `webpackCompilationPlugins`\ncan't be used.) Set to `false` if you want to inject the manifest into,\ne.g., a JSON file.", "default": true, "type": "boolean" }, "swDest": { + "description": "The asset name of the service worker file that will be created by this\nplugin. If omitted, the name will be based on the `swSrc` name.", "type": "string" }, "webpackCompilationPlugins": { + "description": "Optional `webpack` plugins that will be used when compiling the `swSrc`\ninput file. Only valid if `compileSrc` is `true`.", "type": "array", "items": {} } @@ -170,6 +185,7 @@ "type": "object", "properties": { "handler": { + "description": "This determines how the runtime route will generate a response.\nTo use one of the built-in {@link workbox-strategies}, provide its name,\nlike `'NetworkFirst'`.\nAlternatively, this can be a {@link workbox-core.RouteHandler} callback\nfunction with custom response logic.", "anyOf": [ { "$ref": "#/definitions/RouteHandlerCallback" @@ -190,6 +206,8 @@ ] }, "method": { + "description": "The HTTP method to match against. The default value of `'GET'` is normally\nsufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or\nanother type of request.", + "default": "GET", "enum": [ "DELETE", "GET", @@ -204,6 +222,7 @@ "type": "object", "properties": { "backgroundSync": { + "description": "Configuring this will add a\n{@link workbox-background-sync.BackgroundSyncPlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "name": { @@ -219,6 +238,7 @@ ] }, "broadcastUpdate": { + "description": "Configuring this will add a\n{@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the\n{@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "channelName": { @@ -234,27 +254,33 @@ ] }, "cacheableResponse": { + "description": "Configuring this will add a\n{@link workbox-cacheable-response.CacheableResponsePlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/CacheableResponseOptions" }, "cacheName": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`.", "type": [ "null", "string" ] }, "expiration": { + "description": "Configuring this will add a\n{@link workbox-expiration.ExpirationPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/ExpirationPluginOptions" }, "networkTimeoutSeconds": { + "description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`. Note that only\n`'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.", "type": "number" }, "plugins": { + "description": "Configuring this allows the use of one or more Workbox plugins that\ndon't have \"shortcut\" options (like `expiration` for\n{@link workbox-expiration.ExpirationPlugin}). The plugins provided here\nwill be added to the {@link workbox-strategies} configured in `handler`.", "type": "array", "items": { "$ref": "#/definitions/WorkboxPlugin" } }, "precacheFallback": { + "description": "Configuring this will add a\n{@link workbox-precaching.PrecacheFallbackPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "type": "object", "properties": { "fallbackURL": { @@ -267,18 +293,22 @@ ] }, "rangeRequests": { + "description": "Enabling this will add a\n{@link workbox-range-requests.RangeRequestsPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.", "type": "boolean" }, "fetchOptions": { + "description": "Configuring this will pass along the `fetchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/RequestInit" }, "matchOptions": { + "description": "Configuring this will pass along the `matchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.", "$ref": "#/definitions/CacheQueryOptions" } }, "additionalProperties": false }, "urlPattern": { + "description": "This match criteria determines whether the configured handler will\ngenerate a response for any requests that don't match one of the precached\nURLs. If multiple `RuntimeCaching` routes are defined, then the first one\nwhose `urlPattern` matches will be the one that responds.\n\nThis value directly maps to the first parameter passed to\n{@link workbox-routing.registerRoute}. It's recommended to use a\n{@link workbox-core.RouteMatchCallback} function for greatest flexibility.", "anyOf": [ { "$ref": "#/definitions/RegExp" diff --git a/packages/workbox-build/src/types.ts b/packages/workbox-build/src/types.ts index ef4e0f4124..179e13b1e3 100644 --- a/packages/workbox-build/src/types.ts +++ b/packages/workbox-build/src/types.ts @@ -15,7 +15,7 @@ export interface ManifestEntry { url: string; } -type StrategyName = +export type StrategyName = | 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' @@ -23,31 +23,107 @@ type StrategyName = | 'StaleWhileRevalidate'; export interface RuntimeCaching { + /** + * This determines how the runtime route will generate a response. + * To use one of the built-in {@link workbox-strategies}, provide its name, + * like `'NetworkFirst'`. + * Alternatively, this can be a {@link workbox-core.RouteHandler} callback + * function with custom response logic. + */ handler: RouteHandler | StrategyName; + /** + * The HTTP method to match against. The default value of `'GET'` is normally + * sufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or + * another type of request. + * @default "GET" + */ method?: HTTPMethod; options?: { + /** + * Configuring this will add a + * {@link workbox-background-sync.BackgroundSyncPlugin} instance to the + * {@link workbox-strategies} configured in `handler`. + */ backgroundSync?: { name: string; options?: QueueOptions; }; + /** + * Configuring this will add a + * {@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the + * {@link workbox-strategies} configured in `handler`. + */ broadcastUpdate?: { // TODO: This option is ignored since we switched to using postMessage(). // Remove it in the next major release. channelName?: string; options: BroadcastCacheUpdateOptions; }; + /** + * Configuring this will add a + * {@link workbox-cacheable-response.CacheableResponsePlugin} instance to + * the {@link workbox-strategies} configured in `handler`. + */ cacheableResponse?: CacheableResponseOptions; + /** + * If provided, this will set the `cacheName` property of the + * {@link workbox-strategies} configured in `handler`. + */ cacheName?: string | null; + /** + * Configuring this will add a + * {@link workbox-expiration.ExpirationPlugin} instance to + * the {@link workbox-strategies} configured in `handler`. + */ expiration?: ExpirationPluginOptions; + /** + * If provided, this will set the `cacheName` property of the + * {@link workbox-strategies} configured in `handler`. Note that only + * `'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`. + */ networkTimeoutSeconds?: number; + /** + * Configuring this allows the use of one or more Workbox plugins that + * don't have "shortcut" options (like `expiration` for + * {@link workbox-expiration.ExpirationPlugin}). The plugins provided here + * will be added to the {@link workbox-strategies} configured in `handler`. + */ plugins?: Array; + /** + * Configuring this will add a + * {@link workbox-precaching.PrecacheFallbackPlugin} instance to + * the {@link workbox-strategies} configured in `handler`. + */ precacheFallback?: { fallbackURL: string; }; + /** + * Enabling this will add a + * {@link workbox-range-requests.RangeRequestsPlugin} instance to + * the {@link workbox-strategies} configured in `handler`. + */ rangeRequests?: boolean; + /** + * Configuring this will pass along the `fetchOptions` value to + * the {@link workbox-strategies} configured in `handler`. + */ fetchOptions?: RequestInit; + /** + * Configuring this will pass along the `matchOptions` value to + * the {@link workbox-strategies} configured in `handler`. + */ matchOptions?: CacheQueryOptions; }; + /** + * This match criteria determines whether the configured handler will + * generate a response for any requests that don't match one of the precached + * URLs. If multiple `RuntimeCaching` routes are defined, then the first one + * whose `urlPattern` matches will be the one that responds. + * + * This value directly maps to the first parameter passed to + * {@link workbox-routing.registerRoute}. It's recommended to use a + * {@link workbox-core.RouteMatchCallback} function for greatest flexibility. + */ urlPattern: RegExp | string | RouteMatchCallback; } @@ -62,13 +138,42 @@ export type ManifestTransform = ( ) => Promise | ManifestTransformResult; export interface BasePartial { + /** + * A list of entries to be precached, in addition to any entries that are + * generated as part of the build configuration. + */ additionalManifestEntries?: Array; + /** + * Assets that match this will be assumed to be uniquely versioned via their + * URL, and exempted from the normal HTTP cache-busting that's done when + * populating the precache. While not required, it's recommended that if your + * existing build process already inserts a `[hash]` value into each filename, + * you provide a RegExp that will detect that, as it will reduce the bandwidth + * consumed when precaching. + */ dontCacheBustURLsMatching?: RegExp; + /** + * One or more functions which will be applied sequentially against the + * generated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are + * also specified, their corresponding transformations will be applied first. + */ manifestTransforms?: Array; /** + * This value can be used to determine the maximum size of files that will be + * precached. This prevents you from inadvertently precaching very large files + * that might have accidentally matched one of your patterns. * @default 2097152 */ maximumFileSizeToCacheInBytes?: number; + /** + * A mapping of prefixes that, if present in an entry in the precache + * manifest, will be replaced with the corresponding value. This can be used + * to, for example, remove or add a path prefix from a manifest entry if your + * web hosting setup doesn't match your local filesystem setup. As an + * alternative with more flexibility, you can use the `manifestTransforms` + * option and provide a function that modifies the entries in the manifest + * using whatever logic you provide. + */ modifyURLPrefix?: { [key: string]: string; }; @@ -76,55 +181,163 @@ export interface BasePartial { export interface GeneratePartial { /** + * The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass + * to `babel-preset-env` when transpiling the service worker bundle. * @default ["chrome >= 56"] */ babelPresetEnvTargets?: Array; + /** + * An optional ID to be prepended to cache names. This is primarily useful for + * local development where multiple sites may be served from the same + * `http://localhost:port` origin. + */ cacheId?: string | null; /** + * Whether or not Workbox should attempt to identify and delete any precaches + * created by older, incompatible versions. * @default false */ cleanupOutdatedCaches?: boolean; /** + * Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim) + * any existing clients as soon as it activates. * @default false */ clientsClaim?: boolean; + /** + * If a navigation request for a URL ending in `/` fails to match a precached + * URL, this value will be appended to the URL and that will be checked for a + * precache match. This should be set to what your web server is using for its + * directory index. + */ directoryIndex?: string | null; /** * @default false */ disableDevLogs?: boolean; + // We can't use the @default annotation here to assign the value via AJV, as + // an Array can't be serialized into JSON. + /** + * Any search parameter names that match against one of the RegExp in this + * array will be removed before looking for a precache match. This is useful + * if your users might request URLs that contain, for example, URL parameters + * used to track the source of the traffic. If not provided, the default value + * is `[/^utm_/, /^fbclid$/]`. + * + */ ignoreURLParametersMatching?: Array; + /** + * A list of JavaScript files that should be passed to + * [`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts) + * inside the generated service worker file. This is useful when you want to + * let Workbox create your top-level service worker file, but want to include + * some additional code, such as a push event listener. + */ importScripts?: Array; /** + * Whether the runtime code for the Workbox library should be included in the + * top-level service worker, or split into a separate file that needs to be + * deployed alongside the service worker. Keeping the runtime separate means + * that users will not have to re-download the Workbox code each time your + * top-level service worker changes. * @default false */ inlineWorkboxRuntime?: boolean; /** + * If set to 'production', then an optimized service worker bundle that + * excludes debugging info will be produced. If not explicitly configured + * here, the `process.env.NODE_ENV` value will be used, and failing that, it + * will fall back to `'production'`. * @default "production" */ mode?: string | null; /** + * If specified, all + * [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests) + * for URLs that aren't precached will be fulfilled with the HTML at the URL + * provided. You must pass in the URL of an HTML document that is listed in + * your precache manifest. This is meant to be used in a Single Page App + * scenario, in which you want all navigations to use common + * [App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell). * @default null */ navigateFallback?: string | null; + /** + * An optional array of regular expressions that restricts which URLs the + * configured `navigateFallback` behavior applies to. This is useful if only a + * subset of your site's URLs should be treated as being part of a + * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). + * If both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are + * configured, the denylist takes precedent. + */ navigateFallbackAllowlist?: Array; + /** + * An optional array of regular expressions that restricts which URLs the + * configured `navigateFallback` behavior applies to. This is useful if only a + * subset of your site's URLs should be treated as being part of a + * [Single Page App](https://en.wikipedia.org/wiki/Single-page_application). + * If both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are + * configured, the denylist takes precedence. + */ navigateFallbackDenylist?: Array; /** - * navigationPreload is only valid when runtimeCaching is configured. However, - * this can't be expressed via TypeScript, so it's enforced via runtime logic. + * Whether or not to enable + * [navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload) + * in the generated service worker. When set to true, you must also use + * `runtimeCaching` to set up an appropriate response strategy that will match + * navigation requests, and make use of the preloaded response. * @default false */ navigationPreload?: boolean; /** + * Controls whether or not to include support for + * [offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics). + * When `true`, the call to `workbox-google-analytics`'s `initialize()` will + * be added to your generated service worker. When set to an `Object`, that + * object will be passed in to the `initialize()` call, allowing you to + * customize the behavior. * @default false */ offlineGoogleAnalytics?: boolean | GoogleAnalyticsInitializeOptions; + /** + * When using Workbox's build tools to generate your service worker, you can + * specify one or more runtime caching configurations. These are then + * translated to {@link workbox-routing.registerRoute} calls using the match + * and handler configuration you define. + * + * For all of the options, see the {@link workbox-build.RuntimeCaching} + * documentation. The example below shows a typical configuration, with two + * runtime routes defined: + * + * @example + * runtimeCaching: [{ + * urlPattern: ({url}) => url.origin === 'https://api.example.com', + * handler: 'NetworkFirst', + * options: { + * cacheName: 'api-cache', + * }, + * }, { + * urlPattern: ({request}) => request.destination === 'image', + * handler: 'StaleWhileRevalidate', + * options: { + * cacheName: 'images-cache', + * expiration: { + * maxEntries: 10, + * }, + * }, + * }] + */ runtimeCaching?: Array; /** + * Whether to add an unconditional call to [`skipWaiting()`](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#skip_the_waiting_phase) + * to the generated service worker. If `false`, then a `message` listener will + * be added instead, allowing client pages to trigger `skipWaiting()` by + * calling `postMessage({type: 'SKIP_WAITING'})` on a waiting service worker. * @default false */ skipWaiting?: boolean; /** + * Whether to create a sourcemap for the generated service worker files. * @default true */ sourcemap?: boolean; @@ -134,85 +347,163 @@ export interface GeneratePartial { // optional when using GenerateSW if runtimeCaching is also used. This is // enforced via runtime validation, and needs to be documented. export interface RequiredGlobDirectoryPartial { + /** + * The local directory you wish to match `globPatterns` against. The path is + * relative to the current directory. + */ globDirectory: string; } export interface OptionalGlobDirectoryPartial { + /** + * The local directory you wish to match `globPatterns` against. The path is + * relative to the current directory. + */ globDirectory?: string; } export interface GlobPartial { /** + * Determines whether or not symlinks are followed when generating the + * precache manifest. For more information, see the definition of `follow` in + * the `glob` [documentation](https://github.com/isaacs/node-glob#options). * @default true */ globFollow?: boolean; /** + * A set of patterns matching files to always exclude when generating the + * precache manifest. For more information, see the definition of `ignore` in + * the `glob` [documentation](https://github.com/isaacs/node-glob#options). * @default ["**\/node_modules\/**\/*"] */ globIgnores?: Array; /** + * Files matching any of these patterns will be included in the precache + * manifest. For more information, see the + * [`glob` primer](https://github.com/isaacs/node-glob#glob-primer). * @default ["**\/*.{js,css,html}"] */ globPatterns?: Array; /** + * If true, an error reading a directory when generating a precache manifest + * will cause the build to fail. If false, the problematic directory will be + * skipped. For more information, see the definition of `strict` in the `glob` + * [documentation](https://github.com/isaacs/node-glob#options). * @default true */ globStrict?: boolean; + /** + * If a URL is rendered based on some server-side logic, its contents may + * depend on multiple files or on some other unique string value. The keys in + * this object are server-rendered URLs. If the values are an array of + * strings, they will be interpreted as `glob` patterns, and the contents of + * any files matching the patterns will be used to uniquely version the URL. + * If used with a single string, it will be interpreted as unique versioning + * information that you've generated for a given URL. + */ templatedURLs?: { [key: string]: string | Array; }; } -interface InjectPartial { +export interface InjectPartial { /** + * The string to find inside of the `swSrc` file. Once found, it will be + * replaced by the generated precache manifest. * @default "self.__WB_MANIFEST" */ injectionPoint?: string; + /** + * The path and filename of the service worker file that will be read during + * the build process, relative to the current working directory. + */ swSrc: string; } -interface WebpackPartial { +export interface WebpackPartial { + /** + * One or more chunk names whose corresponding output files should be included + * in the precache manifest. + */ chunks?: Array; // We can't use the @default annotation here to assign the value via AJV, as // an Array can't be serialized into JSON. // The default value of [/\.map$/, /^manifest.*\.js$/] will be assigned by // the validation function, and we need to reflect that in the docs. - exclude?: Array< - //eslint-disable-next-line @typescript-eslint/ban-types - string | RegExp | ((arg0: any) => boolean) - >; + /** + * One or more specifiers used to exclude assets from the precache manifest. + * This is interpreted following + * [the same rules](https://webpack.js.org/configuration/module/#condition) + * as `webpack`'s standard `exclude` option. + * If not provided, the default value is `[/\.map$/, /^manifest.*\.js$]`. + */ + exclude?: Array boolean)>; + /** + * One or more chunk names whose corresponding output files should be excluded + * from the precache manifest. + */ excludeChunks?: Array; - - include?: Array< - //eslint-disable-next-line @typescript-eslint/ban-types - string | RegExp | ((arg0: any) => boolean) - >; + /** + * One or more specifiers used to include assets in the precache manifest. + * This is interpreted following + * [the same rules](https://webpack.js.org/configuration/module/#condition) + * as `webpack`'s standard `include` option. + */ + include?: Array boolean)>; + /** + * If set to 'production', then an optimized service worker bundle that + * excludes debugging info will be produced. If not explicitly configured + * here, the `mode` value configured in the current `webpack` compilation + * will be used. + */ mode?: string | null; } export interface RequiredSWDestPartial { + /** + * The path and filename of the service worker file that will be created by + * the build process, relative to the current working directory. It must end + * in '.js'. + */ swDest: string; } -interface WebpackGenerateSWPartial { +export interface WebpackGenerateSWPartial { + /** + * One or more names of webpack chunks. The content of those chunks will be + * included in the generated service worker, via a call to `importScripts()`. + */ importScriptsViaChunks?: Array; /** + * The asset name of the service worker file created by this plugin. * @default "service-worker.js" */ swDest?: string; } -interface WebpackInjectManifestPartial { +export interface WebpackInjectManifestPartial { /** + * When `true` (the default), the `swSrc` file will be compiled by webpack. + * When `false`, compilation will not occur (and `webpackCompilationPlugins` + * can't be used.) Set to `false` if you want to inject the manifest into, + * e.g., a JSON file. * @default true */ compileSrc?: boolean; // This doesn't have a hardcoded default value; instead, the default will be // set at runtime to the swSrc basename, with the hardcoded extension .js. + /** + * The asset name of the service worker file that will be created by this + * plugin. If omitted, the name will be based on the `swSrc` name. + */ swDest?: string; // This can only be set if compileSrc is true, but that restriction can't be // represented in TypeScript. It's enforced via custom runtime validation // logic and needs to be documented. + /** + * Optional `webpack` plugins that will be used when compiling the `swSrc` + * input file. Only valid if `compileSrc` is `true`. + */ webpackCompilationPlugins?: Array; } @@ -253,14 +544,23 @@ export type BuildResult = Omit & { filePaths: Array; }; +/** + * @private + */ export interface FileDetails { file: string; hash: string; size: number; } +/** + * @private + */ export type BuildType = 'dev' | 'prod'; +/** + * @private + */ export interface WorkboxPackageJSON extends PackageJson { workbox?: { browserNamespace?: string; diff --git a/packages/workbox-strategies/src/StaleWhileRevalidate.ts b/packages/workbox-strategies/src/StaleWhileRevalidate.ts index 80ac1619a3..1e8d37f8bd 100644 --- a/packages/workbox-strategies/src/StaleWhileRevalidate.ts +++ b/packages/workbox-strategies/src/StaleWhileRevalidate.ts @@ -84,6 +84,7 @@ class StaleWhileRevalidate extends Strategy { // Swallow this error because a 'no-response' error will be thrown in // main handler return flow. This will be in the `waitUntil()` flow. }); + void handler.waitUntil(fetchAndCachePromise); let response = await handler.cacheMatch(request); diff --git a/test/workbox-background-sync/sw/test-Queue.mjs b/test/workbox-background-sync/sw/test-Queue.mjs index efa46d0669..08ac4ce353 100644 --- a/test/workbox-background-sync/sw/test-Queue.mjs +++ b/test/workbox-background-sync/sw/test-Queue.mjs @@ -205,6 +205,13 @@ describe(`Queue`, function () { expect(onSync.calledOnce).to.be.true; } }); + + it(`should run 'onSync' on instantiation when forceSyncFallback is set`, async function () { + const onSync = sandbox.spy(); + new Queue('foo', {onSync, forceSyncFallback: true}); + + expect(onSync.calledOnce).to.be.true; + }); }); describe(`pushRequest`, function () {