Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose the event object to plugin methods #1640

Merged
merged 4 commits into from
Sep 18, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 4 additions & 4 deletions packages/workbox-broadcast-cache-update/Plugin.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ class Plugin {
* added to a cache.
*
* @private
* @param {Object} input The input object to this function.
* @param {string} input.cacheName Name of the cache the responses belong to.
* @param {Response} [input.oldResponse] The previous cached value, if any.
* @param {Response} input.newResponse The new value in the cache.
* @param {Object} options The input object to this function.
* @param {string} options.cacheName Name of the cache being updated.
* @param {Response} [options.oldResponse] The previous cached value, if any.
* @param {Response} options.newResponse The new value in the cache.
*/
cacheDidUpdate({cacheName, oldResponse, newResponse, request}) {
if (process.env.NODE_ENV !== 'production') {
Expand Down
16 changes: 8 additions & 8 deletions packages/workbox-cache-expiration/Plugin.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,12 @@ class Plugin {
* prevents it from being used if the `Response`'s `Date` header value is
* older than the configured `maxAgeSeconds`.
*
* @param {Object} input
* @param {string} input.cacheName Name of the cache the responses belong to.
* @param {Response} input.cachedResponse The `Response` object that's been
* read from a cache and whose freshness should be checked.
* @param {Object} options
* @param {string} options.cacheName Name of the cache the response is in.
* @param {Response} options.cachedResponse The `Response` object that's been
* read from a cache and whose freshness should be checked.
* @return {Response} Either the `cachedResponse`, if it's
* fresh, or `null` if the `Response` is older than `maxAgeSeconds`.
* fresh, or `null` if the `Response` is older than `maxAgeSeconds`.
*
* @private
*/
Expand Down Expand Up @@ -197,9 +197,9 @@ class Plugin {
* A "lifecycle" callback that will be triggered automatically by the
* `workbox.runtimeCaching` handlers when an entry is added to a cache.
*
* @param {Object} input
* @param {string} input.cacheName Name of the cache the responses belong to.
* @param {string} input.request The Request for the cached entry.
* @param {Object} options
* @param {string} options.cacheName Name of the cache that was updated.
* @param {string} options.request The Request for the cached entry.
*
* @private
*/
Expand Down
56 changes: 38 additions & 18 deletions packages/workbox-core/_private/cacheWrapper.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,23 @@ import '../_version.mjs';
*
* Will call `cacheDidUpdate` on plugins if the cache was updated.
*
* @param {string} cacheName
* @param {Request} request
* @param {Response} response
* @param {Array<Object>} [plugins]
* @param {Object} options
* @param {string} options.cacheName
* @param {Request} options.request
* @param {Response} options.response
* @param {Event} [options.event]
* @param {Array<Object>} [options.plugins=[]]
*
* @private
* @memberof module:workbox-core
*/
const putWrapper = async (cacheName, request, response, plugins = []) => {
const putWrapper = async ({
cacheName,
request,
response,
event,
plugins = [],
} = {}) => {
if (!response) {
if (process.env.NODE_ENV !== 'production') {
logger.error(`Cannot cache non-existent response for ` +
Expand All @@ -49,8 +57,8 @@ const putWrapper = async (cacheName, request, response, plugins = []) => {
});
}

let responseToCache = await _isResponseSafeToCache(
request, response, plugins);
let responseToCache =
await _isResponseSafeToCache({request, response, event, plugins});

if (!responseToCache) {
if (process.env.NODE_ENV !== 'production') {
Expand All @@ -75,7 +83,7 @@ const putWrapper = async (cacheName, request, response, plugins = []) => {
plugins, pluginEvents.CACHE_DID_UPDATE);

let oldResponse = updatePlugins.length > 0 ?
await matchWrapper(cacheName, request) : null;
await matchWrapper({cacheName, request}) : null;

if (process.env.NODE_ENV !== 'production') {
logger.debug(`Updating the '${cacheName}' cache with a new Response for ` +
Expand All @@ -96,6 +104,7 @@ const putWrapper = async (cacheName, request, response, plugins = []) => {
await plugin[pluginEvents.CACHE_DID_UPDATE].call(plugin, {
cacheName,
request,
event,
oldResponse,
newResponse: responseToCache,
});
Expand All @@ -105,17 +114,24 @@ const putWrapper = async (cacheName, request, response, plugins = []) => {
/**
* This is a wrapper around cache.match().
*
* @param {string} cacheName Name of the cache to match against.
* @param {Request} request The Request that will be used to look up cache
* entries.
* @param {Object} matchOptions Options passed to cache.match().
* @param {Array<Object>} [plugins] Array of plugins.
* @param {Object} options
* @param {string} options.cacheName Name of the cache to match against.
* @param {Request} options.request The Request that will be used to look up
*. cache entries.
* @param {Event} [options.event] The event that propted the action.
* @param {Object} [options.matchOptions] Options passed to cache.match().
* @param {Array<Object>} [options.plugins=[]] Array of plugins.
* @return {Response} A cached response if available.
*
* @private
* @memberof module:workbox-core
*/
const matchWrapper = async (cacheName, request, matchOptions, plugins = []) => {
const matchWrapper = async ({
cacheName,
request,
event,
matchOptions,
plugins = []}) => {
const cache = await caches.open(cacheName);
let cachedResponse = await cache.match(request, matchOptions);
if (process.env.NODE_ENV !== 'production') {
Expand All @@ -131,6 +147,7 @@ const matchWrapper = async (cacheName, request, matchOptions, plugins = []) => {
.call(plugin, {
cacheName,
request,
event,
matchOptions,
cachedResponse,
});
Expand All @@ -152,15 +169,17 @@ const matchWrapper = async (cacheName, request, matchOptions, plugins = []) => {
* This method will call cacheWillUpdate on the available plugins (or use
* response.ok) to determine if the Response is safe and valid to cache.
*
* @param {Request} request
* @param {Response} response
* @param {Array<Object>} plugins
* @param {Object} options
* @param {Request} options.request
* @param {Response} options.response
* @param {Event} [options.event]
* @param {Array<Object>} [options.plugins=[]]
* @return {Promise<Response>}
*
* @private
* @memberof module:workbox-core
*/
const _isResponseSafeToCache = async (request, response, plugins) => {
const _isResponseSafeToCache = async ({request, response, event, plugins}) => {
let responseToCache = response;
let pluginsUsed = false;
for (let plugin of plugins) {
Expand All @@ -170,6 +189,7 @@ const _isResponseSafeToCache = async (request, response, plugins) => {
.call(plugin, {
request,
response: responseToCache,
event,
});

if (process.env.NODE_ENV !== 'production') {
Expand Down
30 changes: 17 additions & 13 deletions packages/workbox-core/_private/fetchWrapper.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,26 @@ import '../_version.mjs';
*
* Will call requestWillFetch on available plugins.
*
* @param {Request|string} request
* @param {Object} fetchOptions
* @param {Array<Object>} [plugins]
* @param {Promise<Response>} [preloadResponse]
* @param {Object} options
* @param {Request|string} options.request
* @param {Object} [options.fetchOptions]
* @param {Event} [options.event]
* @param {Array<Object>} [options.plugins=[]]
* @return {Promise<Response>}
*
* @private
* @memberof module:workbox-core
*/
const wrappedFetch = async (request,
fetchOptions,
plugins = [],
preloadResponse) => {
// We *should* be able to call `await preloadResponse` even if it's undefined,
// but for some reason, doing so leads to errors in our Node unit tests.
// To work around that, explicitly check preloadResponse's value first.
if (preloadResponse) {
const possiblePreloadResponse = await preloadResponse;
const wrappedFetch = async ({
request,
fetchOptions,
event,
plugins = []}) => {
// We *should* be able to call `await event.preloadResponse` even if it's
// undefined, but for some reason, doing so leads to errors in our Node unit
// tests. To work around that, explicitly check preloadResponse's value first.
if (event && event.preloadResponse) {
const possiblePreloadResponse = await event.preloadResponse;
if (possiblePreloadResponse) {
if (process.env.NODE_ENV !== 'production') {
logger.log(`Using a preloaded navigation response for ` +
Expand Down Expand Up @@ -82,6 +84,7 @@ const wrappedFetch = async (request,
if (pluginEvents.REQUEST_WILL_FETCH in plugin) {
request = await plugin[pluginEvents.REQUEST_WILL_FETCH].call(plugin, {
request: request.clone(),
event,
});

if (process.env.NODE_ENV !== 'production') {
Expand Down Expand Up @@ -123,6 +126,7 @@ const wrappedFetch = async (request,
for (let plugin of failedFetchPlugins) {
await plugin[pluginEvents.FETCH_DID_FAIL].call(plugin, {
error,
event,
originalRequest: originalRequest.clone(),
request: pluginFilteredRequest.clone(),
});
Expand Down
4 changes: 3 additions & 1 deletion packages/workbox-precaching/_default.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -160,12 +160,14 @@ moduleExports.precache = (entries) => {
installActivateListenersAdded = true;
self.addEventListener('install', (event) => {
event.waitUntil(precacheController.install({
suppressWarnings,
event,
plugins,
suppressWarnings,
}));
});
self.addEventListener('activate', (event) => {
event.waitUntil(precacheController.activate({
event,
plugins,
}));
});
Expand Down
62 changes: 37 additions & 25 deletions packages/workbox-precaching/controllers/PrecacheController.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -142,20 +142,20 @@ class PrecacheController {
* precaching assets.
*
* @param {Object} options
* @param {boolean} options.suppressWarnings Suppress warning messages.
* @param {Array<Object>} options.plugins Plugins to be used for fetching
* and caching during install.
* @return {
* Promise<workbox.precaching.InstallResult>}
* @param {boolean} [options.suppressWarnings] Suppress warning messages.
* @param {Event} [options.event] The install event (if needed).
* @param {Array<Object>} [options.plugins] Plugins to be used for fetching
* and caching during install.
* @return {Promise<workbox.precaching.InstallResult>}
*/
async install(options = {}) {
async install({suppressWarnings = false, event, plugins} = {}) {
if (process.env.NODE_ENV !== 'production') {
if (options.suppressWarnings !== true) {
if (suppressWarnings !== true) {
showWarningsIfNeeded(this._entriesToCacheMap);
}

if (options.plugins) {
assert.isArray(options.plugins, {
if (plugins) {
assert.isArray(plugins, {
moduleName: 'workbox-precaching',
className: 'PrecacheController',
funcName: 'install',
Expand Down Expand Up @@ -190,7 +190,7 @@ class PrecacheController {

// Wait for all requests to be cached.
await Promise.all(entriesToPrecache.map((precacheEntry) => {
return this._cacheEntryInTemp(precacheEntry, options.plugins);
return this._cacheEntryInTemp({event, plugins, precacheEntry});
}));

if (process.env.NODE_ENV !== 'production') {
Expand Down Expand Up @@ -223,8 +223,12 @@ class PrecacheController {
// when done, to help avoid triggering quota errors.
for (const request of requests) {
const response = await tempCache.match(request);
await cacheWrapper.put(this._cacheName, request,
response, options.plugins);
await cacheWrapper.put({
cacheName: this._cacheName,
request,
response,
plugins: options.plugins,
});
await tempCache.delete(request);
}

Expand All @@ -247,27 +251,35 @@ class PrecacheController {
* is valid.
*
* @private
* @param {BaseCacheEntry} precacheEntry The entry to fetch and cache.
* @param {Array<Object>} plugins Array of plugins to apply to fetch and
* caching.
* @param {Object} options
* @param {BaseCacheEntry} options.precacheEntry The entry to fetch and cache.
* @param {Event} [options.event] The install event (if passed).
* @param {Array<Object>} [options.plugins] An array of plugins to apply to
* fetch and caching.
* @return {Promise<boolean>} Returns a promise that resolves once the entry
* has been fetched and cached or skipped if no update is needed. The
* promise resolves with true if the entry was cached / updated and
* false if the entry is already cached and up-to-date.
* has been fetched and cached or skipped if no update is needed. The
* promise resolves with true if the entry was cached / updated and
* false if the entry is already cached and up-to-date.
*/
async _cacheEntryInTemp(precacheEntry, plugins) {
let response = await fetchWrapper.fetch(
precacheEntry._networkRequest,
null,
async _cacheEntryInTemp({precacheEntry, event, plugins}) {
let response = await fetchWrapper.fetch({
request: precacheEntry._networkRequest,
event,
fetchOptions: null,
plugins,
);
});

if (response.redirected) {
response = await cleanRedirect(response);
}

await cacheWrapper.put(this._getTempCacheName(),
precacheEntry._cacheRequest, response, plugins);
await cacheWrapper.put({
cacheName: this._getTempCacheName(),
request: precacheEntry._cacheRequest,
response,
event,
plugins,
});

await this._precacheDetailsModel._addEntry(precacheEntry);

Expand Down
6 changes: 3 additions & 3 deletions packages/workbox-routing/NavigationRoute.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ class NavigationRoute extends Route {
/**
* Routes match handler.
*
* @param {Object} input
* @param {FetchEvent} input.event
* @param {URL} input.url
* @param {Object} options
* @param {FetchEvent} options.event
* @param {URL} options.url
* @return {boolean}
*
* @private
Expand Down