workbox-broadcast-update.prod.js.map 14.4 KB
{"version":3,"file":"workbox-broadcast-update.prod.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:6.5.3'] && _();\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 workbox-broadcast-update\n */\nconst responsesAreSame = (firstResponse, secondResponse, headersToCheck) => {\n    if (process.env.NODE_ENV !== 'production') {\n        if (!(firstResponse instanceof Response && 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) && 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) === secondResponse.headers.has(header);\n        const headerValueComparison = firstResponse.headers.get(header) === 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 NOTIFY_ALL_CLIENTS = true;\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_META, CACHE_UPDATED_MESSAGE_TYPE, DEFAULT_HEADERS_TO_CHECK, NOTIFY_ALL_CLIENTS, } 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 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     * @param {boolean} [options.notifyAllClients=true] If true (the default) then\n     *     all open clients will receive a message. If false, then only the client\n     *     that make the original request will be notified of the update.\n     */\n    constructor({ generatePayload, headersToCheck, notifyAllClients, } = {}) {\n        this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;\n        this._generatePayload = generatePayload || defaultPayloadGenerator;\n        this._notifyAllClients = notifyAllClients !== null && notifyAllClients !== void 0 ? notifyAllClients : NOTIFY_ALL_CLIENTS;\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. Neither of the Responses can be\n     * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).\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 The 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            if (this._notifyAllClients) {\n                const windows = await self.clients.matchAll({ type: 'window' });\n                for (const win of windows) {\n                    win.postMessage(messageData);\n                }\n            }\n            else {\n                // See https://github.com/GoogleChrome/workbox/issues/2895\n                if (options.event instanceof FetchEvent) {\n                    const client = await self.clients.get(options.event.clientId);\n                    client === null || client === void 0 ? void 0 : client.postMessage(messageData);\n                }\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 workbox-broadcast-update\n */\nclass BroadcastUpdatePlugin {\n    /**\n     * Construct a {@link workbox-broadcast-update.BroadcastUpdate} instance with\n     * the passed options and calls its `notifyIfUpdated` method whenever the\n     * 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","some","header","headers","has","every","headerStateComparison","headerValueComparison","get","DEFAULT_HEADERS_TO_CHECK","isSafari","test","navigator","userAgent","defaultPayloadGenerator","data","cacheName","updatedURL","request","url","BroadcastCacheUpdate","constructor","generatePayload","notifyAllClients","_headersToCheck","_generatePayload","_notifyAllClients","options","oldResponse","newResponse","this","messageData","type","meta","payload","mode","resultingClientId","event","FetchEvent","resultingClientExists","timeout","windows","clients","matchAll","win","postMessage","client","clientId","cacheDidUpdate","async","dontWaitFor","_broadcastUpdate","notifyIfUpdated"],"mappings":"0FAEA,IACIA,KAAK,mCAAqCC,IAE9C,MAAOC,UCgBDC,EAAmB,CAACC,EAAeC,EAAgBC,KAMnBA,EAAeC,MAAMC,GAC3CJ,EAAcK,QAAQC,IAAIF,IAAWH,EAAeI,QAAQC,IAAIF,MAYrEF,EAAeK,OAAOH,UACnBI,EAAwBR,EAAcK,QAAQC,IAAIF,KAAYH,EAAeI,QAAQC,IAAIF,GACzFK,EAAwBT,EAAcK,QAAQK,IAAIN,KAAYH,EAAeI,QAAQK,IAAIN,UACxFI,GAAyBC,KChC3BE,EAA2B,CACpC,iBACA,OACA,iBCGEC,EAAW,iCAAiCC,KAAKC,UAAUC,WAQjE,SAASC,EAAwBC,SACtB,CACHC,UAAWD,EAAKC,UAChBC,WAAYF,EAAKG,QAAQC,KAYjC,MAAMC,EAgBFC,aAAYC,gBAAEA,EAAFtB,eAAmBA,EAAnBuB,iBAAmCA,GAAsB,SAC5DC,EAAkBxB,GAAkBS,OACpCgB,EAAmBH,GAAmBR,OACtCY,EAAoBH,MAAAA,GAA2DA,wBAiClEI,MAsBbA,EAAQC,cAGR/B,EAAiB8B,EAAQC,YAAaD,EAAQE,YAAaC,KAAKN,GAAkB,OAI7EO,EAAc,CAChBC,KDlH0B,gBCmH1BC,KDlH0B,2BCmH1BC,QAASJ,KAAKL,EAAiBE,OAIN,aAAzBA,EAAQT,QAAQiB,KAAqB,KACjCC,EACAT,EAAQU,iBAAiBC,aACzBF,EAAoBT,EAAQU,MAAMD,yBAEXG,wBAAsBH,KAM5B1B,SAKX8B,UAAQ,SAGlBV,KAAKJ,EAAmB,OAClBe,QAAgB/C,KAAKgD,QAAQC,SAAS,CAAEX,KAAM,eAC/C,MAAMY,KAAOH,EACdG,EAAIC,YAAYd,WAKhBJ,EAAQU,iBAAiBC,WAAY,OAC/BQ,QAAepD,KAAKgD,QAAQlC,IAAImB,EAAQU,MAAMU,UACpDD,MAAAA,GAAgDA,EAAOD,YAAYd,8DC7IvF,MAcIV,YAAYM,QAcHqB,eAAiBC,MAAAA,IAClBC,cAAYpB,KAAKqB,EAAiBC,gBAAgBzB,UAEjDwB,EAAmB,IAAI/B,EAAqBO"}