UNPKG

2.75 kBJavaScriptView Raw
1/*
2 Copyright 2018 Google LLC
3
4 Use of this source code is governed by an MIT-style
5 license that can be found in the LICENSE file or at
6 https://opensource.org/licenses/MIT.
7*/
8
9const template = require('lodash.template');
10const swTemplate = require('../templates/sw-template');
11
12const errors = require('./errors');
13const runtimeCachingConverter = require('./runtime-caching-converter');
14const stringifyWithoutComments = require('./stringify-without-comments');
15
16module.exports = ({
17 cacheId,
18 cleanupOutdatedCaches,
19 clientsClaim,
20 directoryIndex,
21 ignoreURLParametersMatching,
22 importScripts,
23 manifestEntries,
24 modulePathPrefix,
25 navigateFallback,
26 navigateFallbackBlacklist,
27 navigateFallbackWhitelist,
28 offlineGoogleAnalytics,
29 runtimeCaching,
30 skipWaiting,
31 workboxSWImport,
32}) => {
33 // These are all options that can be passed to the precacheAndRoute() method.
34 const precacheOptions = {
35 directoryIndex,
36 // An array of RegExp objects can't be serialized by JSON.stringify()'s
37 // default behavior, so if it's given, convert it manually.
38 ignoreURLParametersMatching: ignoreURLParametersMatching ?
39 [] :
40 undefined,
41 };
42
43 let precacheOptionsString = JSON.stringify(precacheOptions, null, 2);
44 if (ignoreURLParametersMatching) {
45 precacheOptionsString = precacheOptionsString.replace(
46 `"ignoreURLParametersMatching": []`,
47 `"ignoreURLParametersMatching": [` +
48 `${ignoreURLParametersMatching.join(', ')}]`
49 );
50 }
51
52 let offlineAnalyticsConfigString;
53 if (offlineGoogleAnalytics) {
54 // If offlineGoogleAnalytics is a truthy value, we need to convert it to the
55 // format expected by the template.
56 offlineAnalyticsConfigString = offlineGoogleAnalytics === true ?
57 // If it's the literal value true, then use an empty config string.
58 '{}' :
59 // Otherwise, convert the config object into a more complex string, taking
60 // into account the fact that functions might need to be stringified.
61 stringifyWithoutComments(offlineGoogleAnalytics);
62 }
63
64 try {
65 const populatedTemplate = template(swTemplate)({
66 cacheId,
67 cleanupOutdatedCaches,
68 clientsClaim,
69 importScripts,
70 manifestEntries,
71 modulePathPrefix,
72 navigateFallback,
73 navigateFallbackBlacklist,
74 navigateFallbackWhitelist,
75 offlineAnalyticsConfigString,
76 precacheOptionsString,
77 skipWaiting,
78 runtimeCaching: runtimeCachingConverter(runtimeCaching),
79 workboxSWImport,
80 });
81
82 // Clean up multiple blank lines.
83 return populatedTemplate.replace(/\n{3,}/g, '\n\n').trim() + '\n';
84 } catch (error) {
85 throw new Error(
86 `${errors['populating-sw-tmpl-failed']} '${error.message}'`);
87 }
88};