write-sw-using-default-template.ts
2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import fse from 'fs-extra';
import upath from 'upath';
import {bundle} from './bundle';
import {errors} from './errors';
import {GenerateSWOptions, ManifestEntry} from '../types';
import {populateSWTemplate} from './populate-sw-template';
export async function writeSWUsingDefaultTemplate({
babelPresetEnvTargets,
cacheId,
cleanupOutdatedCaches,
clientsClaim,
directoryIndex,
disableDevLogs,
ignoreURLParametersMatching,
importScripts,
inlineWorkboxRuntime,
manifestEntries,
mode,
navigateFallback,
navigateFallbackDenylist,
navigateFallbackAllowlist,
navigationPreload,
offlineGoogleAnalytics,
runtimeCaching,
skipWaiting,
sourcemap,
swDest,
}: GenerateSWOptions & {manifestEntries: Array<ManifestEntry>}): Promise<
Array<string>
> {
const outputDir = upath.dirname(swDest);
try {
await fse.mkdirp(outputDir);
} catch (error) {
throw new Error(
`${errors['unable-to-make-sw-directory']}. ` +
`'${error instanceof Error && error.message ? error.message : ''}'`,
);
}
const unbundledCode = populateSWTemplate({
cacheId,
cleanupOutdatedCaches,
clientsClaim,
directoryIndex,
disableDevLogs,
ignoreURLParametersMatching,
importScripts,
manifestEntries,
navigateFallback,
navigateFallbackDenylist,
navigateFallbackAllowlist,
navigationPreload,
offlineGoogleAnalytics,
runtimeCaching,
skipWaiting,
});
try {
const files = await bundle({
babelPresetEnvTargets,
inlineWorkboxRuntime,
mode,
sourcemap,
swDest,
unbundledCode,
});
const filePaths: Array<string> = [];
for (const file of files) {
const filePath = upath.resolve(file.name);
filePaths.push(filePath);
await fse.writeFile(filePath, file.contents);
}
return filePaths;
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code === 'EISDIR') {
// See https://github.com/GoogleChrome/workbox/issues/612
throw new Error(errors['sw-write-failure-directory']);
}
throw new Error(`${errors['sw-write-failure']} '${err.message}'`);
}
}