workbox-broadcast-update.dev.js.map 18.1 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: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","Response","WorkboxError","atLeastOneHeaderAvailable","some","header","headers","has","logger","warn","debug","every","headerStateComparison","headerValueComparison","get","CACHE_UPDATED_MESSAGE_TYPE","CACHE_UPDATED_MESSAGE_META","NOTIFY_ALL_CLIENTS","DEFAULT_HEADERS_TO_CHECK","isSafari","test","navigator","userAgent","defaultPayloadGenerator","data","cacheName","updatedURL","request","url","BroadcastCacheUpdate","constructor","generatePayload","notifyAllClients","_headersToCheck","_generatePayload","_notifyAllClients","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","client","clientId","BroadcastUpdatePlugin","cacheDidUpdate","dontWaitFor","_broadcastUpdate"],"mappings":";;;;IAEA,IAAI;IACAA,EAAAA,IAAI,CAAC,gCAAD,CAAJ,IAA0CC,CAAC,EAA3C;IACH,CAFD,CAGA,OAAOC,CAAP,EAAU;;ICLV;IACA;AACA;IACA;IACA;IACA;IACA;IAIA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;UACMC,gBAAgB,GAAG,CAACC,aAAD,EAAgBC,cAAhB,EAAgCC,cAAhC,KAAmD;IACxE,EAA2C;IACvC,QAAI,EAAEF,aAAa,YAAYG,QAAzB,IAAqCF,cAAc,YAAYE,QAAjE,CAAJ,EAAgF;IAC5E,YAAM,IAAIC,4BAAJ,CAAiB,iCAAjB,CAAN;IACH;IACJ;;IACD,QAAMC,yBAAyB,GAAGH,cAAc,CAACI,IAAf,CAAqBC,MAAD,IAAY;IAC9D,WAAQP,aAAa,CAACQ,OAAd,CAAsBC,GAAtB,CAA0BF,MAA1B,KAAqCN,cAAc,CAACO,OAAf,CAAuBC,GAAvB,CAA2BF,MAA3B,CAA7C;IACH,GAFiC,CAAlC;;IAGA,MAAI,CAACF,yBAAL,EAAgC;IAC5B,IAA2C;IACvCK,MAAAA,gBAAM,CAACC,IAAP,CAAa,0DAAD,GACP,gEADL;IAEAD,MAAAA,gBAAM,CAACE,KAAP,CAAc,uCAAd,EAAsDZ,aAAtD,EAAqEC,cAArE,EAAqFC,cAArF;IACH,KAL2B;IAO5B;;;IACA,WAAO,IAAP;IACH;;IACD,SAAOA,cAAc,CAACW,KAAf,CAAsBN,MAAD,IAAY;IACpC,UAAMO,qBAAqB,GAAGd,aAA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