diff --git a/infra/testing/validator/service-worker-runtime.js b/infra/testing/validator/service-worker-runtime.js index 7ee885a5f..c0780dab7 100644 --- a/infra/testing/validator/service-worker-runtime.js +++ b/infra/testing/validator/service-worker-runtime.js @@ -135,7 +135,7 @@ function setupSpiesAndContextForGenerateSW() { return {addEventListener, context, methodsToSpies: workboxContext}; } -function validateMethodCalls({methodsToSpies, expectedMethodCalls}) { +function validateMethodCalls({methodsToSpies, expectedMethodCalls, context}) { for (const [method, spy] of Object.entries(methodsToSpies)) { if (spy.called) { // Special-case handling for importScripts(), as the first call may be @@ -157,6 +157,13 @@ function validateMethodCalls({methodsToSpies, expectedMethodCalls}) { `while testing method calls for ${method}`).to.be.undefined; } } + + // Special validation for __WB_DISABLE_DEV_LOGS, which is a boolean + // assignment, so we can't stub it out. + if ('__WB_DISABLE_DEV_LOGS' in expectedMethodCalls) { + expect(context.self.__WB_DISABLE_DEV_LOGS).to.eql( + expectedMethodCalls.__WB_DISABLE_DEV_LOGS, `__WB_DISABLE_DEV_LOGS`); + } } /** @@ -194,7 +201,7 @@ module.exports = async ({ vm.runInNewContext(swString, context); - validateMethodCalls({methodsToSpies, expectedMethodCalls}); + validateMethodCalls({methodsToSpies, expectedMethodCalls, context}); // Optionally check the usage of addEventListener(). if (addEventListenerValidation) { diff --git a/packages/workbox-build/src/lib/populate-sw-template.js b/packages/workbox-build/src/lib/populate-sw-template.js index 906649b6c..ac1a3fb94 100644 --- a/packages/workbox-build/src/lib/populate-sw-template.js +++ b/packages/workbox-build/src/lib/populate-sw-template.js @@ -19,6 +19,7 @@ module.exports = ({ cleanupOutdatedCaches, clientsClaim, directoryIndex, + disableDevLogs, ignoreURLParametersMatching, importScripts, manifestEntries = [], @@ -73,6 +74,7 @@ module.exports = ({ cacheId, cleanupOutdatedCaches, clientsClaim, + disableDevLogs, importScripts, manifestEntries, navigateFallback, diff --git a/packages/workbox-build/src/lib/write-sw-using-default-template.js b/packages/workbox-build/src/lib/write-sw-using-default-template.js index 185fb1d45..cb7c20044 100644 --- a/packages/workbox-build/src/lib/write-sw-using-default-template.js +++ b/packages/workbox-build/src/lib/write-sw-using-default-template.js @@ -19,6 +19,7 @@ module.exports = async ({ cleanupOutdatedCaches, clientsClaim, directoryIndex, + disableDevLogs, ignoreURLParametersMatching, importScripts, inlineWorkboxRuntime, @@ -47,6 +48,7 @@ module.exports = async ({ cleanupOutdatedCaches, clientsClaim, directoryIndex, + disableDevLogs, ignoreURLParametersMatching, importScripts, manifestEntries, diff --git a/packages/workbox-build/src/options/defaults.js b/packages/workbox-build/src/options/defaults.js index 6aab4c78b..550c87fc2 100644 --- a/packages/workbox-build/src/options/defaults.js +++ b/packages/workbox-build/src/options/defaults.js @@ -10,6 +10,7 @@ module.exports = { babelPresetEnvTargets: ['chrome >= 56'], cleanupOutdatedCaches: false, clientsClaim: false, + disableDevLogs: false, exclude: [ /\.map$/, /^manifest.*\.js$/, diff --git a/packages/workbox-build/src/options/partials/generate.js b/packages/workbox-build/src/options/partials/generate.js index 527aae17a..910725919 100644 --- a/packages/workbox-build/src/options/partials/generate.js +++ b/packages/workbox-build/src/options/partials/generate.js @@ -18,6 +18,7 @@ module.exports = { cleanupOutdatedCaches: joi.boolean().default(defaults.cleanupOutdatedCaches), clientsClaim: joi.boolean().default(defaults.clientsClaim), directoryIndex: joi.string(), + disableDevLogs: joi.boolean().default(defaults.disableDevLogs), ignoreURLParametersMatching: joi.array().items(regExpObject), importScripts: joi.array().items(joi.string()), inlineWorkboxRuntime: joi.boolean().default(defaults.inlineWorkboxRuntime), diff --git a/packages/workbox-build/src/templates/sw-template.js b/packages/workbox-build/src/templates/sw-template.js index 13bf4209c..3fbf0060f 100644 --- a/packages/workbox-build/src/templates/sw-template.js +++ b/packages/workbox-build/src/templates/sw-template.js @@ -55,4 +55,6 @@ self.addEventListener('message', (event) => { <% if (runtimeCaching) { runtimeCaching.forEach(runtimeCachingString => {%><%= runtimeCachingString %><% });} %> -<% if (offlineAnalyticsConfigString) { %><%= use('workbox-google-analytics', 'initialize') %>(<%= offlineAnalyticsConfigString %>);<% } %>`; +<% if (offlineAnalyticsConfigString) { %><%= use('workbox-google-analytics', 'initialize') %>(<%= offlineAnalyticsConfigString %>);<% } %> + +<% if (disableDevLogs) { %>self.__WB_DISABLE_DEV_LOGS = true;<% } %>`; diff --git a/packages/workbox-core/src/_private/logger.ts b/packages/workbox-core/src/_private/logger.ts index 0775dc540..ecc00fd23 100644 --- a/packages/workbox-core/src/_private/logger.ts +++ b/packages/workbox-core/src/_private/logger.ts @@ -7,11 +7,17 @@ import '../_version.js'; +declare global { + interface WorkerGlobalScope { + __WB_DISABLE_DEV_LOGS: boolean; + } +} type LoggerMethods = 'debug'|'log'|'warn'|'error'|'groupCollapsed'|'groupEnd'; - const logger = (process.env.NODE_ENV === 'production' ? null : (() => { + self.__WB_DISABLE_DEV_LOGS = false; + let inGroup = false; const methodToColorMap: {[methodName: string]: string|null} = { @@ -24,6 +30,10 @@ const logger = (process.env.NODE_ENV === 'production' ? null : (() => }; const print = function(method: LoggerMethods, args: any[]) { + if (self.__WB_DISABLE_DEV_LOGS) { + return; + } + if (method === 'groupCollapsed') { // Safari doesn't print all console.groupCollapsed() arguments: // https://bugs.webkit.org/show_bug.cgi?id=182754 diff --git a/test/workbox-build/node/generate-sw.js b/test/workbox-build/node/generate-sw.js index 583631cd2..1f40330b1 100644 --- a/test/workbox-build/node/generate-sw.js +++ b/test/workbox-build/node/generate-sw.js @@ -33,6 +33,7 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { 'cacheId', 'clientsClaim', 'directoryIndex', + 'disableDevLogs', 'dontCacheBustURLsMatching', 'globDirectory', 'globFollow', @@ -138,6 +139,47 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { confirmDirectoryContains(outputDir, filePaths); await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { + __WB_DISABLE_DEV_LOGS: undefined, + importScripts: [], + precacheAndRoute: [[[{ + url: 'index.html', + revision: '3883c45b119c9d7e9ad75a1b4a4672ac', + }, { + url: 'page-1.html', + revision: '544658ab25ee8762dc241e8b1c5ed96d', + }, { + url: 'page-2.html', + revision: 'a3a71ce0b9b43c459cf58bd37e911b74', + }, { + url: 'styles/stylesheet-1.css', + revision: '934823cbc67ccf0d67aa2a2eeb798f12', + }, { + url: 'styles/stylesheet-2.css', + revision: '884f6853a4fc655e4c2dc0c0f27a227c', + }, { + url: 'webpackEntry.js', + revision: '5b652181a25e96f255d0490203d3c47e', + }], {}]], + }}); + }); + + it(`should disable logging when disableDevLogs is set to true`, async function() { + const outputDir = tempy.directory(); + const swDest = upath.join(outputDir, 'sw.js'); + const options = Object.assign({}, BASE_OPTIONS, { + disableDevLogs: true, + swDest, + }); + + const {count, filePaths, size, warnings} = await generateSW(options); + expect(warnings).to.be.empty; + expect(count).to.eql(6); + expect(size).to.eql(2604); + + confirmDirectoryContains(outputDir, filePaths); + + await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { + __WB_DISABLE_DEV_LOGS: true, importScripts: [], precacheAndRoute: [[[{ url: 'index.html', diff --git a/test/workbox-build/node/lib/populate-sw-template.js b/test/workbox-build/node/lib/populate-sw-template.js index 6e141b324..55e238573 100644 --- a/test/workbox-build/node/lib/populate-sw-template.js +++ b/test/workbox-build/node/lib/populate-sw-template.js @@ -72,6 +72,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() { cacheId: undefined, cleanupOutdatedCaches: undefined, clientsClaim: undefined, + disableDevLogs: undefined, importScripts: undefined, navigateFallback: undefined, navigateFallbackBlacklist: undefined, @@ -89,6 +90,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() { const cleanupOutdatedCaches = true; const clientsClaim = true; const directoryIndex = 'index.html'; + const disableDevLogs = true; const handleFetch = true; const ignoreURLParametersMatching = [/a/, /b/]; const importScripts = ['test.js']; @@ -122,6 +124,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() { cleanupOutdatedCaches, clientsClaim, directoryIndex, + disableDevLogs, handleFetch, ignoreURLParametersMatching, importScripts, @@ -145,6 +148,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() { cacheId, cleanupOutdatedCaches, clientsClaim, + disableDevLogs, importScripts, manifestEntries, navigateFallback, @@ -195,6 +199,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() { cacheId: undefined, cleanupOutdatedCaches: undefined, clientsClaim: undefined, + disableDevLogs: undefined, importScripts: undefined, navigateFallback: undefined, navigateFallbackBlacklist: undefined, diff --git a/test/workbox-core/sw/_private/test-logger.mjs b/test/workbox-core/sw/_private/test-logger.mjs index b98fac9e5..c0c9a7dfb 100644 --- a/test/workbox-core/sw/_private/test-logger.mjs +++ b/test/workbox-core/sw/_private/test-logger.mjs @@ -26,6 +26,8 @@ describe(`logger`, function() { } }); } + + self.__WB_DISABLE_DEV_LOGS = false; }); after(function() { @@ -59,6 +61,20 @@ describe(`logger`, function() { expect(logger).to.equal(null); }); + it(`should toggle logging based on the value of __WB_DISABLE_DEV_LOGS`, function() { + if (process.env.NODE_ENV === 'production') this.skip(); + + const logStub = sandbox.stub(console, 'log'); + + self.__WB_DISABLE_DEV_LOGS = true; + logger.log(''); + expect(logStub.callCount).to.eql(0); + + self.__WB_DISABLE_DEV_LOGS = false; + logger.log(''); + expect(logStub.callCount).to.eql(1); + }); + consoleLevels.forEach((consoleLevel) => { describe(`.${consoleLevel}()`, function() { it(`should work without input`, function() {