workbox-broadcast-update.dev.js.map 16.3 KB
{"version":3,"file":"workbox-broadcast-update.dev.js","sources":["../_version.js","../responsesAreSame.js","../utils/constants.js","../BroadcastCacheUpdate.js","../BroadcastUpdatePlugin.js"],"sourcesContent":["\"use strict\";\n// @ts-ignore\ntry {\n    self['workbox:broadcast-update:5.1.4'] && _();\n}\ncatch (e) { }\n","/*\n  Copyright 2018 Google LLC\n\n  Use of this source code is governed by an MIT-style\n  license that can be found in the LICENSE file or at\n  https://opensource.org/licenses/MIT.\n*/\nimport { WorkboxError } from 'workbox-core/_private/WorkboxError.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport './_version.js';\n/**\n * Given two `Response's`, compares several header values to see if they are\n * the same or not.\n *\n * @param {Response} firstResponse\n * @param {Response} secondResponse\n * @param {Array<string>} headersToCheck\n * @return {boolean}\n *\n * @memberof module:workbox-broadcast-update\n */\nconst responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {\n    if (process.env.NODE_ENV !== 'production') {\n        if (!(firstResponse instanceof Response &&\n            secondResponse instanceof Response)) {\n            throw new WorkboxError('invalid-responses-are-same-args');\n        }\n    }\n    const atLeastOneHeaderAvailable = headersToCheck.some((header) => {\n        return firstResponse.headers.has(header) &&\n            secondResponse.headers.has(header);\n    });\n    if (!atLeastOneHeaderAvailable) {\n        if (process.env.NODE_ENV !== 'production') {\n            logger.warn(`Unable to determine where the response has been updated ` +\n                `because none of the headers that would be checked are present.`);\n            logger.debug(`Attempting to compare the following: `, firstResponse, secondResponse, headersToCheck);\n        }\n        // Just return true, indicating the that responses are the same, since we\n        // can't determine otherwise.\n        return true;\n    }\n    return headersToCheck.every((header) => {\n        const headerStateComparison = firstResponse.headers.has(header) ===\n            secondResponse.headers.has(header);\n        const headerValueComparison = firstResponse.headers.get(header) ===\n            secondResponse.headers.get(header);\n        return headerStateComparison && headerValueComparison;\n    });\n};\nexport { responsesAreSame };\n","/*\n  Copyright 2018 Google LLC\n\n  Use of this source code is governed by an MIT-style\n  license that can be found in the LICENSE file or at\n  https://opensource.org/licenses/MIT.\n*/\nimport '../_version.js';\nexport const CACHE_UPDATED_MESSAGE_TYPE = 'CACHE_UPDATED';\nexport const CACHE_UPDATED_MESSAGE_META = 'workbox-broadcast-update';\nexport const DEFAULT_HEADERS_TO_CHECK = [\n    'content-length',\n    'etag',\n    'last-modified',\n];\n","/*\n  Copyright 2018 Google LLC\n\n  Use of this source code is governed by an MIT-style\n  license that can be found in the LICENSE file or at\n  https://opensource.org/licenses/MIT.\n*/\nimport { assert } from 'workbox-core/_private/assert.js';\nimport { timeout } from 'workbox-core/_private/timeout.js';\nimport { resultingClientExists } from 'workbox-core/_private/resultingClientExists.js';\nimport { logger } from 'workbox-core/_private/logger.js';\nimport { responsesAreSame } from './responsesAreSame.js';\nimport { CACHE_UPDATED_MESSAGE_TYPE, CACHE_UPDATED_MESSAGE_META, DEFAULT_HEADERS_TO_CHECK } from './utils/constants.js';\nimport './_version.js';\n// UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser\n// TODO(philipwalton): remove once this Safari bug fix has been released.\n// https://bugs.webkit.org/show_bug.cgi?id=201169\nconst isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n/**\n * Generates the default payload used in update messages. By default the\n * payload includes the `cacheName` and `updatedURL` fields.\n *\n * @return Object\n * @private\n */\nfunction defaultPayloadGenerator(data) {\n    return {\n        cacheName: data.cacheName,\n        updatedURL: data.request.url,\n    };\n}\n/**\n * Uses the `postMessage()` API to inform any open windows/tabs when a cached\n * response has been updated.\n *\n * For efficiency's sake, the underlying response bodies are not compared;\n * only specific response headers are checked.\n *\n * @memberof module:workbox-broadcast-update\n */\nclass BroadcastCacheUpdate {\n    /**\n     * Construct a BroadcastCacheUpdate instance with a specific `channelName` to\n     * broadcast messages on\n     *\n     * @param {Object} options\n     * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n     *     A list of headers that will be used to determine whether the responses\n     *     differ.\n     * @param {string} [options.generatePayload] A function whose return value\n     *     will be used as the `payload` field in any cache update messages sent\n     *     to the window clients.\n     */\n    constructor({ headersToCheck, generatePayload, } = {}) {\n        this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;\n        this._generatePayload = generatePayload || defaultPayloadGenerator;\n    }\n    /**\n     * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)\n     * and sends a message (via `postMessage()`) to all window clients if the\n     * responses differ (note: neither of the Responses can be\n     * {@link http://stackoverflow.com/questions/39109789|opaque}).\n     *\n     * The message that's posted has the following format (where `payload` can\n     * be customized via the `generatePayload` option the instance is created\n     * with):\n     *\n     * ```\n     * {\n     *   type: 'CACHE_UPDATED',\n     *   meta: 'workbox-broadcast-update',\n     *   payload: {\n     *     cacheName: 'the-cache-name',\n     *     updatedURL: 'https://example.com/'\n     *   }\n     * }\n     * ```\n     *\n     * @param {Object} options\n     * @param {Response} [options.oldResponse] Cached response to compare.\n     * @param {Response} options.newResponse Possibly updated response to compare.\n     * @param {Request} options.request The request.\n     * @param {string} options.cacheName Name of the cache the responses belong\n     *     to. This is included in the broadcast message.\n     * @param {Event} [options.event] event An optional event that triggered\n     *     this possible cache update.\n     * @return {Promise} Resolves once the update is sent.\n     */\n    async notifyIfUpdated(options) {\n        if (process.env.NODE_ENV !== 'production') {\n            assert.isType(options.cacheName, 'string', {\n                moduleName: 'workbox-broadcast-update',\n                className: 'BroadcastCacheUpdate',\n                funcName: 'notifyIfUpdated',\n                paramName: 'cacheName',\n            });\n            assert.isInstance(options.newResponse, Response, {\n                moduleName: 'workbox-broadcast-update',\n                className: 'BroadcastCacheUpdate',\n                funcName: 'notifyIfUpdated',\n                paramName: 'newResponse',\n            });\n            assert.isInstance(options.request, Request, {\n                moduleName: 'workbox-broadcast-update',\n                className: 'BroadcastCacheUpdate',\n                funcName: 'notifyIfUpdated',\n                paramName: 'request',\n            });\n        }\n        // Without two responses there is nothing to compare.\n        if (!options.oldResponse) {\n            return;\n        }\n        if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {\n            if (process.env.NODE_ENV !== 'production') {\n                logger.log(`Newer response found (and cached) for:`, options.request.url);\n            }\n            const messageData = {\n                type: CACHE_UPDATED_MESSAGE_TYPE,\n                meta: CACHE_UPDATED_MESSAGE_META,\n                payload: this._generatePayload(options),\n            };\n            // For navigation requests, wait until the new window client exists\n            // before sending the message\n            if (options.request.mode === 'navigate') {\n                let resultingClientId;\n                if (options.event instanceof FetchEvent) {\n                    resultingClientId = options.event.resultingClientId;\n                }\n                const resultingWin = await resultingClientExists(resultingClientId);\n                // Safari does not currently implement postMessage buffering and\n                // there's no good way to feature detect that, so to increase the\n                // chances of the message being delivered in Safari, we add a timeout.\n                // We also do this if `resultingClientExists()` didn't return a client,\n                // which means it timed out, so it's worth waiting a bit longer.\n                if (!resultingWin || isSafari) {\n                    // 3500 is chosen because (according to CrUX data) 80% of mobile\n                    // websites hit the DOMContentLoaded event in less than 3.5 seconds.\n                    // And presumably sites implementing service worker are on the\n                    // higher end of the performance spectrum.\n                    await timeout(3500);\n                }\n            }\n            const windows = await self.clients.matchAll({ type: 'window' });\n            for (const win of windows) {\n                win.postMessage(messageData);\n            }\n        }\n    }\n}\nexport { BroadcastCacheUpdate };\n","/*\n  Copyright 2018 Google LLC\n\n  Use of this source code is governed by an MIT-style\n  license that can be found in the LICENSE file or at\n  https://opensource.org/licenses/MIT.\n*/\nimport { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';\nimport { BroadcastCacheUpdate } from './BroadcastCacheUpdate.js';\nimport './_version.js';\n/**\n * This plugin will automatically broadcast a message whenever a cached response\n * is updated.\n *\n * @memberof module:workbox-broadcast-update\n */\nclass BroadcastUpdatePlugin {\n    /**\n     * Construct a BroadcastCacheUpdate instance with the passed options and\n     * calls its [`notifyIfUpdated()`]{@link module:workbox-broadcast-update.BroadcastCacheUpdate~notifyIfUpdated}\n     * method whenever the plugin's `cacheDidUpdate` callback is invoked.\n     *\n     * @param {Object} options\n     * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]\n     *     A list of headers that will be used to determine whether the responses\n     *     differ.\n     * @param {string} [options.generatePayload] A function whose return value\n     *     will be used as the `payload` field in any cache update messages sent\n     *     to the window clients.\n     */\n    constructor(options) {\n        /**\n         * A \"lifecycle\" callback that will be triggered automatically by the\n         * `workbox-sw` and `workbox-runtime-caching` handlers when an entry is\n         * added to a cache.\n         *\n         * @private\n         * @param {Object} options The input object to this function.\n         * @param {string} options.cacheName Name of the cache being updated.\n         * @param {Response} [options.oldResponse] The previous cached value, if any.\n         * @param {Response} options.newResponse The new value in the cache.\n         * @param {Request} options.request The request that triggered the update.\n         * @param {Request} [options.event] The event that triggered the update.\n         */\n        this.cacheDidUpdate = async (options) => {\n            dontWaitFor(this._broadcastUpdate.notifyIfUpdated(options));\n        };\n        this._broadcastUpdate = new BroadcastCacheUpdate(options);\n    }\n}\nexport { BroadcastUpdatePlugin };\n"],"names":["self","_","e","responsesAreSame","firstResponse","secondResponse","headersToCheck","Response","WorkboxError","atLeastOneHeaderAvailable","some","header","headers","has","logger","warn","debug","every","headerStateComparison","headerValueComparison","get","CACHE_UPDATED_MESSAGE_TYPE","CACHE_UPDATED_MESSAGE_META","DEFAULT_HEADERS_TO_CHECK","isSafari","test","navigator","userAgent","defaultPayloadGenerator","data","cacheName","updatedURL","request","url","BroadcastCacheUpdate","constructor","generatePayload","_headersToCheck","_generatePayload","notifyIfUpdated","options","assert","isType","moduleName","className","funcName","paramName","isInstance","newResponse","Request","oldResponse","log","messageData","type","meta","payload","mode","resultingClientId","event","FetchEvent","resultingWin","resultingClientExists","timeout","windows","clients","matchAll","win","postMessage","BroadcastUpdatePlugin","cacheDidUpdate","dontWaitFor","_broadcastUpdate"],"mappings":";;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,gCAAD,CAAJ,IAA0CC,CAAC,EAA3C;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;;;;;;;AAOA,IAGA;;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