This commit is contained in:
Iliyan Angelov
2025-09-14 23:24:25 +03:00
commit c67067a2a4
71311 changed files with 6800714 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
import { ManifestEntry } from '../types';
type AdditionalManifestEntriesTransform = {
(manifest: Array<ManifestEntry & {
size: number;
}>): {
manifest: Array<ManifestEntry & {
size: number;
}>;
warnings: string[];
};
};
export declare function additionalManifestEntriesTransform(additionalManifestEntries: Array<ManifestEntry | string>): AdditionalManifestEntriesTransform;
export {};

View File

@@ -0,0 +1,47 @@
"use strict";
/*
Copyright 2019 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.additionalManifestEntriesTransform = void 0;
const errors_1 = require("./errors");
function additionalManifestEntriesTransform(additionalManifestEntries) {
return (manifest) => {
const warnings = [];
const stringEntries = new Set();
for (const additionalEntry of additionalManifestEntries) {
// Warn about either a string or an object that lacks a revision property.
// (An object with a revision property set to null is okay.)
if (typeof additionalEntry === 'string') {
stringEntries.add(additionalEntry);
manifest.push({
revision: null,
size: 0,
url: additionalEntry,
});
}
else {
if (additionalEntry && additionalEntry.revision === undefined) {
stringEntries.add(additionalEntry.url);
}
manifest.push(Object.assign({ size: 0 }, additionalEntry));
}
}
if (stringEntries.size > 0) {
let urls = '\n';
for (const stringEntry of stringEntries) {
urls += ` - ${stringEntry}\n`;
}
warnings.push(errors_1.errors['string-entry-warning'] + urls);
}
return {
manifest,
warnings,
};
};
}
exports.additionalManifestEntriesTransform = additionalManifestEntriesTransform;

View File

@@ -0,0 +1,9 @@
import { GeneratePartial, RequiredSWDestPartial } from '../types';
interface NameAndContents {
contents: string | Uint8Array;
name: string;
}
export declare function bundle({ babelPresetEnvTargets, inlineWorkboxRuntime, mode, sourcemap, swDest, unbundledCode, }: Omit<GeneratePartial, 'runtimeCaching'> & RequiredSWDestPartial & {
unbundledCode: string;
}): Promise<Array<NameAndContents>>;
export {};

123
frontend/node_modules/workbox-build/build/lib/bundle.js generated vendored Normal file
View File

@@ -0,0 +1,123 @@
"use strict";
/*
Copyright 2019 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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.bundle = void 0;
const plugin_babel_1 = require("@rollup/plugin-babel");
const plugin_node_resolve_1 = require("@rollup/plugin-node-resolve");
const rollup_1 = require("rollup");
const rollup_plugin_terser_1 = require("rollup-plugin-terser");
const fs_extra_1 = require("fs-extra");
const rollup_plugin_off_main_thread_1 = __importDefault(require("@surma/rollup-plugin-off-main-thread"));
const preset_env_1 = __importDefault(require("@babel/preset-env"));
const plugin_replace_1 = __importDefault(require("@rollup/plugin-replace"));
const tempy_1 = __importDefault(require("tempy"));
const upath_1 = __importDefault(require("upath"));
async function bundle({ babelPresetEnvTargets, inlineWorkboxRuntime, mode, sourcemap, swDest, unbundledCode, }) {
// We need to write this to the "real" file system, as Rollup won't read from
// a custom file system.
const { dir, base } = upath_1.default.parse(swDest);
const temporaryFile = tempy_1.default.file({ name: base });
await (0, fs_extra_1.writeFile)(temporaryFile, unbundledCode);
const plugins = [
(0, plugin_node_resolve_1.nodeResolve)(),
(0, plugin_replace_1.default)({
// See https://github.com/GoogleChrome/workbox/issues/2769
'preventAssignment': true,
'process.env.NODE_ENV': JSON.stringify(mode),
}),
(0, plugin_babel_1.babel)({
babelHelpers: 'bundled',
// Disable the logic that checks for local Babel config files:
// https://github.com/GoogleChrome/workbox/issues/2111
babelrc: false,
configFile: false,
presets: [
[
preset_env_1.default,
{
targets: {
browsers: babelPresetEnvTargets,
},
loose: true,
},
],
],
}),
];
if (mode === 'production') {
plugins.push((0, rollup_plugin_terser_1.terser)({
mangle: {
toplevel: true,
properties: {
regex: /(^_|_$)/,
},
},
}));
}
const rollupConfig = {
plugins,
input: temporaryFile,
};
// Rollup will inline the runtime by default. If we don't want that, we need
// to add in some additional config.
if (!inlineWorkboxRuntime) {
// No lint for omt(), library has no types.
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
rollupConfig.plugins.unshift((0, rollup_plugin_off_main_thread_1.default)());
rollupConfig.manualChunks = (id) => {
return id.includes('workbox') ? 'workbox' : undefined;
};
}
const bundle = await (0, rollup_1.rollup)(rollupConfig);
const { output } = await bundle.generate({
sourcemap,
// Using an external Workbox runtime requires 'amd'.
format: inlineWorkboxRuntime ? 'es' : 'amd',
});
const files = [];
for (const chunkOrAsset of output) {
if (chunkOrAsset.type === 'asset') {
files.push({
name: chunkOrAsset.fileName,
contents: chunkOrAsset.source,
});
}
else {
let code = chunkOrAsset.code;
if (chunkOrAsset.map) {
const sourceMapFile = chunkOrAsset.fileName + '.map';
code += `//# sourceMappingURL=${sourceMapFile}\n`;
files.push({
name: sourceMapFile,
contents: chunkOrAsset.map.toString(),
});
}
files.push({
name: chunkOrAsset.fileName,
contents: code,
});
}
}
// Make sure that if there was a directory portion included in swDest, it's
// preprended to all of the generated files.
return files.map((file) => {
file.name = upath_1.default.format({
dir,
base: file.name,
ext: '',
name: '',
root: '',
});
return file;
});
}
exports.bundle = bundle;

View File

@@ -0,0 +1,2 @@
import { BuildType } from '../types';
export declare function getModuleURL(moduleName: string, buildType: BuildType): string;

View File

@@ -0,0 +1,57 @@
"use strict";
/*
Copyright 2021 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.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getModuleURL = void 0;
const assert_1 = require("assert");
const errors_1 = require("./errors");
const cdn = __importStar(require("../cdn-details.json"));
function getVersionedURL() {
return `${getCDNPrefix()}/${cdn.latestVersion}`;
}
function getCDNPrefix() {
return `${cdn.origin}/${cdn.bucketName}/${cdn.releasesDir}`;
}
function getModuleURL(moduleName, buildType) {
(0, assert_1.ok)(moduleName, errors_1.errors['no-module-name']);
if (buildType) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const pkgJson = require(`${moduleName}/package.json`);
if (buildType === 'dev' && pkgJson.workbox && pkgJson.workbox.prodOnly) {
// This is not due to a public-facing exception, so just throw an Error(),
// without creating an entry in errors.js.
throw Error(`The 'dev' build of ${moduleName} is not available.`);
}
return `${getVersionedURL()}/${moduleName}.${buildType.slice(0, 4)}.js`;
}
return `${getVersionedURL()}/${moduleName}.js`;
}
exports.getModuleURL = getModuleURL;

View File

@@ -0,0 +1,20 @@
/**
* This copies over a set of runtime libraries used by Workbox into a
* local directory, which should be deployed alongside your service worker file.
*
* As an alternative to deploying these local copies, you could instead use
* Workbox from its official CDN URL.
*
* This method is exposed for the benefit of developers using
* {@link workbox-build.injectManifest} who would
* prefer not to use the CDN copies of Workbox. Developers using
* {@link workbox-build.generateSW} don't need to
* explicitly call this method.
*
* @param {string} destDirectory The path to the parent directory under which
* the new directory of libraries will be created.
* @return {Promise<string>} The name of the newly created directory.
*
* @alias workbox-build.copyWorkboxLibraries
*/
export declare function copyWorkboxLibraries(destDirectory: string): Promise<string>;

View File

@@ -0,0 +1,69 @@
"use strict";
/*
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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.copyWorkboxLibraries = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const upath_1 = __importDefault(require("upath"));
const errors_1 = require("./errors");
// Used to filter the libraries to copy based on our package.json dependencies.
const WORKBOX_PREFIX = 'workbox-';
// The directory within each package containing the final bundles.
const BUILD_DIR = 'build';
/**
* This copies over a set of runtime libraries used by Workbox into a
* local directory, which should be deployed alongside your service worker file.
*
* As an alternative to deploying these local copies, you could instead use
* Workbox from its official CDN URL.
*
* This method is exposed for the benefit of developers using
* {@link workbox-build.injectManifest} who would
* prefer not to use the CDN copies of Workbox. Developers using
* {@link workbox-build.generateSW} don't need to
* explicitly call this method.
*
* @param {string} destDirectory The path to the parent directory under which
* the new directory of libraries will be created.
* @return {Promise<string>} The name of the newly created directory.
*
* @alias workbox-build.copyWorkboxLibraries
*/
async function copyWorkboxLibraries(destDirectory) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const thisPkg = require('../../package.json');
// Use the version string from workbox-build in the name of the parent
// directory. This should be safe, because lerna will bump workbox-build's
// pkg.version whenever one of the dependent libraries gets bumped, and we
// care about versioning the dependent libraries.
const workboxDirectoryName = `workbox-v${thisPkg.version ? thisPkg.version : ''}`;
const workboxDirectoryPath = upath_1.default.join(destDirectory, workboxDirectoryName);
await fs_extra_1.default.ensureDir(workboxDirectoryPath);
const copyPromises = [];
const librariesToCopy = Object.keys(thisPkg.dependencies || {}).filter((dependency) => dependency.startsWith(WORKBOX_PREFIX));
for (const library of librariesToCopy) {
// Get the path to the package on the user's filesystem by require-ing
// the package's `package.json` file via the node resolution algorithm.
const libraryPath = upath_1.default.dirname(require.resolve(`${library}/package.json`));
const buildPath = upath_1.default.join(libraryPath, BUILD_DIR);
// fse.copy() copies all the files in a directory, not the directory itself.
// See https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy.md#copysrc-dest-options-callback
copyPromises.push(fs_extra_1.default.copy(buildPath, workboxDirectoryPath));
}
try {
await Promise.all(copyPromises);
return workboxDirectoryName;
}
catch (error) {
throw Error(`${errors_1.errors['unable-to-copy-workbox-libraries']} ${error instanceof Error ? error.toString() : ''}`);
}
}
exports.copyWorkboxLibraries = copyWorkboxLibraries;

View File

@@ -0,0 +1,61 @@
export declare const errors: {
'unable-to-get-rootdir': string;
'no-extension': string;
'invalid-file-manifest-name': string;
'unable-to-get-file-manifest-name': string;
'invalid-sw-dest': string;
'unable-to-get-sw-name': string;
'unable-to-get-save-config': string;
'unable-to-get-file-hash': string;
'unable-to-get-file-size': string;
'unable-to-glob-files': string;
'unable-to-make-manifest-directory': string;
'read-manifest-template-failure': string;
'populating-manifest-tmpl-failed': string;
'manifest-file-write-failure': string;
'unable-to-make-sw-directory': string;
'read-sw-template-failure': string;
'sw-write-failure': string;
'sw-write-failure-directory': string;
'unable-to-copy-workbox-libraries': string;
'invalid-generate-sw-input': string;
'invalid-glob-directory': string;
'invalid-dont-cache-bust': string;
'invalid-exclude-files': string;
'invalid-get-manifest-entries-input': string;
'invalid-manifest-path': string;
'invalid-manifest-entries': string;
'invalid-manifest-format': string;
'invalid-static-file-globs': string;
'invalid-templated-urls': string;
'templated-url-matches-glob': string;
'invalid-glob-ignores': string;
'manifest-entry-bad-url': string;
'modify-url-prefix-bad-prefixes': string;
'invalid-inject-manifest-arg': string;
'injection-point-not-found': string;
'multiple-injection-points': string;
'populating-sw-tmpl-failed': string;
'useless-glob-pattern': string;
'bad-template-urls-asset': string;
'invalid-runtime-caching': string;
'static-file-globs-deprecated': string;
'dynamic-url-deprecated': string;
'urlPattern-is-required': string;
'handler-is-required': string;
'invalid-generate-file-manifest-arg': string;
'invalid-sw-src': string;
'same-src-and-dest': string;
'only-regexp-routes-supported': string;
'bad-runtime-caching-config': string;
'invalid-network-timeout-seconds': string;
'no-module-name': string;
'bad-manifest-transforms-return-value': string;
'string-entry-warning': string;
'no-manifest-entries-or-runtime-caching': string;
'cant-find-sourcemap': string;
'nav-preload-runtime-caching': string;
'cache-name-required': string;
'manifest-transforms': string;
'invalid-handler-string': string;
};

125
frontend/node_modules/workbox-build/build/lib/errors.js generated vendored Normal file
View File

@@ -0,0 +1,125 @@
"use strict";
/*
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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.errors = void 0;
const common_tags_1 = require("common-tags");
exports.errors = {
'unable-to-get-rootdir': `Unable to get the root directory of your web app.`,
'no-extension': (0, common_tags_1.oneLine) `Unable to detect a usable extension for a file in your web
app directory.`,
'invalid-file-manifest-name': (0, common_tags_1.oneLine) `The File Manifest Name must have at least one
character.`,
'unable-to-get-file-manifest-name': 'Unable to get a file manifest name.',
'invalid-sw-dest': `The 'swDest' value must be a valid path.`,
'unable-to-get-sw-name': 'Unable to get a service worker file name.',
'unable-to-get-save-config': (0, common_tags_1.oneLine) `An error occurred when asking to save details
in a config file.`,
'unable-to-get-file-hash': (0, common_tags_1.oneLine) `An error occurred when attempting to create a
file hash.`,
'unable-to-get-file-size': (0, common_tags_1.oneLine) `An error occurred when attempting to get a file
size.`,
'unable-to-glob-files': 'An error occurred when globbing for files.',
'unable-to-make-manifest-directory': (0, common_tags_1.oneLine) `Unable to make output directory for
file manifest.`,
'read-manifest-template-failure': 'Unable to read template for file manifest',
'populating-manifest-tmpl-failed': (0, common_tags_1.oneLine) `An error occurred when populating the
file manifest template.`,
'manifest-file-write-failure': 'Unable to write the file manifest.',
'unable-to-make-sw-directory': (0, common_tags_1.oneLine) `Unable to make the directories to output
the service worker path.`,
'read-sw-template-failure': (0, common_tags_1.oneLine) `Unable to read the service worker template
file.`,
'sw-write-failure': 'Unable to write the service worker file.',
'sw-write-failure-directory': (0, common_tags_1.oneLine) `Unable to write the service worker file;
'swDest' should be a full path to the file, not a path to a directory.`,
'unable-to-copy-workbox-libraries': (0, common_tags_1.oneLine) `One or more of the Workbox libraries
could not be copied over to the destination directory: `,
'invalid-generate-sw-input': (0, common_tags_1.oneLine) `The input to generateSW() must be an object.`,
'invalid-glob-directory': (0, common_tags_1.oneLine) `The supplied globDirectory must be a path as a
string.`,
'invalid-dont-cache-bust': (0, common_tags_1.oneLine) `The supplied 'dontCacheBustURLsMatching'
parameter must be a RegExp.`,
'invalid-exclude-files': 'The excluded files should be an array of strings.',
'invalid-get-manifest-entries-input': (0, common_tags_1.oneLine) `The input to
'getFileManifestEntries()' must be an object.`,
'invalid-manifest-path': (0, common_tags_1.oneLine) `The supplied manifest path is not a string with
at least one character.`,
'invalid-manifest-entries': (0, common_tags_1.oneLine) `The manifest entries must be an array of
strings or JavaScript objects containing a url parameter.`,
'invalid-manifest-format': (0, common_tags_1.oneLine) `The value of the 'format' option passed to
generateFileManifest() must be either 'iife' (the default) or 'es'.`,
'invalid-static-file-globs': (0, common_tags_1.oneLine) `The 'globPatterns' value must be an array
of strings.`,
'invalid-templated-urls': (0, common_tags_1.oneLine) `The 'templatedURLs' value should be an object
that maps URLs to either a string, or to an array of glob patterns.`,
'templated-url-matches-glob': (0, common_tags_1.oneLine) `One of the 'templatedURLs' URLs is already
being tracked via 'globPatterns': `,
'invalid-glob-ignores': (0, common_tags_1.oneLine) `The 'globIgnores' parameter must be an array of
glob pattern strings.`,
'manifest-entry-bad-url': (0, common_tags_1.oneLine) `The generated manifest contains an entry without
a URL string. This is likely an error with workbox-build.`,
'modify-url-prefix-bad-prefixes': (0, common_tags_1.oneLine) `The 'modifyURLPrefix' parameter must be
an object with string key value pairs.`,
'invalid-inject-manifest-arg': (0, common_tags_1.oneLine) `The input to 'injectManifest()' must be an
object.`,
'injection-point-not-found': (0, common_tags_1.oneLine) `Unable to find a place to inject the manifest.
Please ensure that your service worker file contains the following: `,
'multiple-injection-points': (0, common_tags_1.oneLine) `Please ensure that your 'swSrc' file contains
only one match for the following: `,
'populating-sw-tmpl-failed': (0, common_tags_1.oneLine) `Unable to generate service worker from
template.`,
'useless-glob-pattern': (0, common_tags_1.oneLine) `One of the glob patterns doesn't match any files.
Please remove or fix the following: `,
'bad-template-urls-asset': (0, common_tags_1.oneLine) `There was an issue using one of the provided
'templatedURLs'.`,
'invalid-runtime-caching': (0, common_tags_1.oneLine) `The 'runtimeCaching' parameter must an an
array of objects with at least a 'urlPattern' and 'handler'.`,
'static-file-globs-deprecated': (0, common_tags_1.oneLine) `'staticFileGlobs' is deprecated.
Please use 'globPatterns' instead.`,
'dynamic-url-deprecated': (0, common_tags_1.oneLine) `'dynamicURLToDependencies' is deprecated.
Please use 'templatedURLs' instead.`,
'urlPattern-is-required': (0, common_tags_1.oneLine) `The 'urlPattern' option is required when using
'runtimeCaching'.`,
'handler-is-required': (0, common_tags_1.oneLine) `The 'handler' option is required when using
runtimeCaching.`,
'invalid-generate-file-manifest-arg': (0, common_tags_1.oneLine) `The input to generateFileManifest()
must be an Object.`,
'invalid-sw-src': `The 'swSrc' file can't be read.`,
'same-src-and-dest': (0, common_tags_1.oneLine) `Unable to find a place to inject the manifest. This is
likely because swSrc and swDest are configured to the same file.
Please ensure that your swSrc file contains the following:`,
'only-regexp-routes-supported': (0, common_tags_1.oneLine) `Please use a regular expression object as
the urlPattern parameter. (Express-style routes are not currently
supported.)`,
'bad-runtime-caching-config': (0, common_tags_1.oneLine) `An unknown configuration option was used
with runtimeCaching: `,
'invalid-network-timeout-seconds': (0, common_tags_1.oneLine) `When using networkTimeoutSeconds, you
must set the handler to 'NetworkFirst'.`,
'no-module-name': (0, common_tags_1.oneLine) `You must provide a moduleName parameter when calling
getModuleURL().`,
'bad-manifest-transforms-return-value': (0, common_tags_1.oneLine) `The return value from a
manifestTransform should be an object with 'manifest' and optionally
'warnings' properties.`,
'string-entry-warning': (0, common_tags_1.oneLine) `Some items were passed to additionalManifestEntries
without revisioning info. This is generally NOT safe. Learn more at
https://bit.ly/wb-precache.`,
'no-manifest-entries-or-runtime-caching': (0, common_tags_1.oneLine) `Couldn't find configuration for
either precaching or runtime caching. Please ensure that the various glob
options are set to match one or more files, and/or configure the
runtimeCaching option.`,
'cant-find-sourcemap': (0, common_tags_1.oneLine) `The swSrc file refers to a sourcemap that can't be
opened:`,
'nav-preload-runtime-caching': (0, common_tags_1.oneLine) `When using navigationPreload, you must also
configure a runtimeCaching route that will use the preloaded response.`,
'cache-name-required': (0, common_tags_1.oneLine) `When using cache expiration, you must also
configure a custom cacheName.`,
'manifest-transforms': (0, common_tags_1.oneLine) `When using manifestTransforms, you must provide
an array of functions.`,
'invalid-handler-string': (0, common_tags_1.oneLine) `The handler name provided is not valid: `,
};

View File

@@ -0,0 +1 @@
export declare function escapeRegExp(str: string): string;

View File

@@ -0,0 +1,15 @@
"use strict";
/*
Copyright 2019 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.escapeRegExp = void 0;
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
exports.escapeRegExp = escapeRegExp;

View File

@@ -0,0 +1,2 @@
import { FileDetails } from '../types';
export declare function getCompositeDetails(compositeURL: string, dependencyDetails: Array<FileDetails>): FileDetails;

View File

@@ -0,0 +1,31 @@
"use strict";
/*
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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCompositeDetails = void 0;
const crypto_1 = __importDefault(require("crypto"));
function getCompositeDetails(compositeURL, dependencyDetails) {
let totalSize = 0;
let compositeHash = '';
for (const fileDetails of dependencyDetails) {
totalSize += fileDetails.size;
compositeHash += fileDetails.hash;
}
const md5 = crypto_1.default.createHash('md5');
md5.update(compositeHash);
const hashOfHashes = md5.digest('hex');
return {
file: compositeURL,
hash: hashOfHashes,
size: totalSize,
};
}
exports.getCompositeDetails = getCompositeDetails;

View File

@@ -0,0 +1,14 @@
import { GlobPartial } from '../types';
interface FileDetails {
file: string;
hash: string;
size: number;
}
export declare function getFileDetails({ globDirectory, globFollow, globIgnores, globPattern, globStrict, }: Omit<GlobPartial, 'globDirectory' | 'globPatterns' | 'templatedURLs'> & {
globDirectory: string;
globPattern: string;
}): {
globbedFileDetails: Array<FileDetails>;
warning: string;
};
export {};

View File

@@ -0,0 +1,55 @@
"use strict";
/*
Copyright 2021 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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFileDetails = void 0;
const glob_1 = __importDefault(require("glob"));
const upath_1 = __importDefault(require("upath"));
const errors_1 = require("./errors");
const get_file_size_1 = require("./get-file-size");
const get_file_hash_1 = require("./get-file-hash");
function getFileDetails({ globDirectory, globFollow, globIgnores, globPattern, globStrict, }) {
let globbedFiles;
let warning = '';
try {
globbedFiles = glob_1.default.sync(globPattern, {
cwd: globDirectory,
follow: globFollow,
ignore: globIgnores,
strict: globStrict,
});
}
catch (err) {
throw new Error(errors_1.errors['unable-to-glob-files'] +
` '${err instanceof Error && err.message ? err.message : ''}'`);
}
if (globbedFiles.length === 0) {
warning =
errors_1.errors['useless-glob-pattern'] +
' ' +
JSON.stringify({ globDirectory, globPattern, globIgnores }, null, 2);
}
const globbedFileDetails = [];
for (const file of globbedFiles) {
const fullPath = upath_1.default.join(globDirectory, file);
const fileSize = (0, get_file_size_1.getFileSize)(fullPath);
if (fileSize !== null) {
const fileHash = (0, get_file_hash_1.getFileHash)(fullPath);
globbedFileDetails.push({
file: `${upath_1.default.relative(globDirectory, fullPath)}`,
hash: fileHash,
size: fileSize,
});
}
}
return { globbedFileDetails, warning };
}
exports.getFileDetails = getFileDetails;

View File

@@ -0,0 +1 @@
export declare function getFileHash(file: string): string;

View File

@@ -0,0 +1,27 @@
"use strict";
/*
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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFileHash = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const get_string_hash_1 = require("./get-string-hash");
const errors_1 = require("./errors");
function getFileHash(file) {
try {
const buffer = fs_extra_1.default.readFileSync(file);
return (0, get_string_hash_1.getStringHash)(buffer);
}
catch (err) {
throw new Error(errors_1.errors['unable-to-get-file-hash'] +
` '${err instanceof Error && err.message ? err.message : ''}'`);
}
}
exports.getFileHash = getFileHash;

View File

@@ -0,0 +1,2 @@
import { GetManifestResult, GetManifestOptions } from '../types';
export declare function getFileManifestEntries({ additionalManifestEntries, dontCacheBustURLsMatching, globDirectory, globFollow, globIgnores, globPatterns, globStrict, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, templatedURLs, }: GetManifestOptions): Promise<GetManifestResult>;

View File

@@ -0,0 +1,98 @@
"use strict";
/*
Copyright 2021 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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFileManifestEntries = void 0;
const assert_1 = __importDefault(require("assert"));
const errors_1 = require("./errors");
const get_composite_details_1 = require("./get-composite-details");
const get_file_details_1 = require("./get-file-details");
const get_string_details_1 = require("./get-string-details");
const transform_manifest_1 = require("./transform-manifest");
async function getFileManifestEntries({ additionalManifestEntries, dontCacheBustURLsMatching, globDirectory, globFollow, globIgnores, globPatterns = [], globStrict, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, templatedURLs, }) {
const warnings = [];
const allFileDetails = new Map();
try {
for (const globPattern of globPatterns) {
const { globbedFileDetails, warning } = (0, get_file_details_1.getFileDetails)({
globDirectory,
globFollow,
globIgnores,
globPattern,
globStrict,
});
if (warning) {
warnings.push(warning);
}
for (const details of globbedFileDetails) {
if (details && !allFileDetails.has(details.file)) {
allFileDetails.set(details.file, details);
}
}
}
}
catch (error) {
// If there's an exception thrown while globbing, then report
// it back as a warning, and don't consider it fatal.
if (error instanceof Error && error.message) {
warnings.push(error.message);
}
}
if (templatedURLs) {
for (const url of Object.keys(templatedURLs)) {
(0, assert_1.default)(!allFileDetails.has(url), errors_1.errors['templated-url-matches-glob']);
const dependencies = templatedURLs[url];
if (Array.isArray(dependencies)) {
const details = dependencies.reduce((previous, globPattern) => {
try {
const { globbedFileDetails, warning } = (0, get_file_details_1.getFileDetails)({
globDirectory,
globFollow,
globIgnores,
globPattern,
globStrict,
});
if (warning) {
warnings.push(warning);
}
return previous.concat(globbedFileDetails);
}
catch (error) {
const debugObj = {};
debugObj[url] = dependencies;
throw new Error(`${errors_1.errors['bad-template-urls-asset']} ` +
`'${globPattern}' from '${JSON.stringify(debugObj)}':\n` +
`${error instanceof Error ? error.toString() : ''}`);
}
}, []);
if (details.length === 0) {
throw new Error(`${errors_1.errors['bad-template-urls-asset']} The glob ` +
`pattern '${dependencies.toString()}' did not match anything.`);
}
allFileDetails.set(url, (0, get_composite_details_1.getCompositeDetails)(url, details));
}
else if (typeof dependencies === 'string') {
allFileDetails.set(url, (0, get_string_details_1.getStringDetails)(url, dependencies));
}
}
}
const transformedManifest = await (0, transform_manifest_1.transformManifest)({
additionalManifestEntries,
dontCacheBustURLsMatching,
manifestTransforms,
maximumFileSizeToCacheInBytes,
modifyURLPrefix,
fileDetails: Array.from(allFileDetails.values()),
});
transformedManifest.warnings.push(...warnings);
return transformedManifest;
}
exports.getFileManifestEntries = getFileManifestEntries;

View File

@@ -0,0 +1 @@
export declare function getFileSize(file: string): number | null;

View File

@@ -0,0 +1,29 @@
"use strict";
/*
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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFileSize = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const errors_1 = require("./errors");
function getFileSize(file) {
try {
const stat = fs_extra_1.default.statSync(file);
if (!stat.isFile()) {
return null;
}
return stat.size;
}
catch (err) {
throw new Error(errors_1.errors['unable-to-get-file-size'] +
` '${err instanceof Error && err.message ? err.message : ''}'`);
}
}
exports.getFileSize = getFileSize;

View File

@@ -0,0 +1 @@
export declare function getSourceMapURL(srcContents: string): string | null;

View File

@@ -0,0 +1,32 @@
"use strict";
/*
Copyright 2022 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSourceMapURL = void 0;
// Adapted from https://github.com/lydell/source-map-url/blob/master/source-map-url.js
// See https://github.com/GoogleChrome/workbox/issues/3019
const innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/;
const regex = RegExp('(?:' +
'/\\*' +
'(?:\\s*\r?\n(?://)?)?' +
'(?:' +
innerRegex.source +
')' +
'\\s*' +
'\\*/' +
'|' +
'//(?:' +
innerRegex.source +
')' +
')' +
'\\s*');
function getSourceMapURL(srcContents) {
const match = srcContents.match(regex);
return match ? match[1] || match[2] || '' : null;
}
exports.getSourceMapURL = getSourceMapURL;

View File

@@ -0,0 +1,2 @@
import { FileDetails } from '../types';
export declare function getStringDetails(url: string, str: string): FileDetails;

View File

@@ -0,0 +1,19 @@
"use strict";
/*
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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getStringDetails = void 0;
const get_string_hash_1 = require("./get-string-hash");
function getStringDetails(url, str) {
return {
file: url,
hash: (0, get_string_hash_1.getStringHash)(str),
size: str.length,
};
}
exports.getStringDetails = getStringDetails;

View File

@@ -0,0 +1,3 @@
/// <reference types="node" />
import crypto from 'crypto';
export declare function getStringHash(input: crypto.BinaryLike): string;

View File

@@ -0,0 +1,20 @@
"use strict";
/*
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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getStringHash = void 0;
const crypto_1 = __importDefault(require("crypto"));
function getStringHash(input) {
const md5 = crypto_1.default.createHash('md5');
md5.update(input);
return md5.digest('hex');
}
exports.getStringHash = getStringHash;

View File

@@ -0,0 +1,2 @@
import { ManifestTransform } from '../types';
export declare function maximumSizeTransform(maximumFileSizeToCacheInBytes: number): ManifestTransform;

View File

@@ -0,0 +1,30 @@
"use strict";
/*
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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.maximumSizeTransform = void 0;
const pretty_bytes_1 = __importDefault(require("pretty-bytes"));
function maximumSizeTransform(maximumFileSizeToCacheInBytes) {
return (originalManifest) => {
const warnings = [];
const manifest = originalManifest.filter((entry) => {
if (entry.size <= maximumFileSizeToCacheInBytes) {
return true;
}
warnings.push(`${entry.url} is ${(0, pretty_bytes_1.default)(entry.size)}, and won't ` +
`be precached. Configure maximumFileSizeToCacheInBytes to change ` +
`this limit.`);
return false;
});
return { manifest, warnings };
};
}
exports.maximumSizeTransform = maximumSizeTransform;

View File

@@ -0,0 +1,4 @@
import { ManifestTransform } from '../types';
export declare function modifyURLPrefixTransform(modifyURLPrefix: {
[key: string]: string;
}): ManifestTransform;

View File

@@ -0,0 +1,51 @@
"use strict";
/*
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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.modifyURLPrefixTransform = void 0;
const errors_1 = require("./errors");
const escape_regexp_1 = require("./escape-regexp");
function modifyURLPrefixTransform(modifyURLPrefix) {
if (!modifyURLPrefix ||
typeof modifyURLPrefix !== 'object' ||
Array.isArray(modifyURLPrefix)) {
throw new Error(errors_1.errors['modify-url-prefix-bad-prefixes']);
}
// If there are no entries in modifyURLPrefix, just return an identity
// function as a shortcut.
if (Object.keys(modifyURLPrefix).length === 0) {
return (manifest) => {
return { manifest };
};
}
for (const key of Object.keys(modifyURLPrefix)) {
if (typeof modifyURLPrefix[key] !== 'string') {
throw new Error(errors_1.errors['modify-url-prefix-bad-prefixes']);
}
}
// Escape the user input so it's safe to use in a regex.
const safeModifyURLPrefixes = Object.keys(modifyURLPrefix).map(escape_regexp_1.escapeRegExp);
// Join all the `modifyURLPrefix` keys so a single regex can be used.
const prefixMatchesStrings = safeModifyURLPrefixes.join('|');
// Add `^` to the front the prefix matches so it only matches the start of
// a string.
const modifyRegex = new RegExp(`^(${prefixMatchesStrings})`);
return (originalManifest) => {
const manifest = originalManifest.map((entry) => {
if (typeof entry.url !== 'string') {
throw new Error(errors_1.errors['manifest-entry-bad-url']);
}
entry.url = entry.url.replace(modifyRegex, (match) => {
return modifyURLPrefix[match];
});
return entry;
});
return { manifest };
};
}
exports.modifyURLPrefixTransform = modifyURLPrefixTransform;

View File

@@ -0,0 +1,33 @@
/**
* Class for keeping track of which Workbox modules are used by the generated
* service worker script.
*
* @private
*/
export declare class ModuleRegistry {
private readonly _modulesUsed;
/**
* @private
*/
constructor();
/**
* @return {Array<string>} A list of all of the import statements that are
* needed for the modules being used.
* @private
*/
getImportStatements(): Array<string>;
/**
* @param {string} pkg The workbox package that the module belongs to.
* @param {string} moduleName The name of the module to import.
* @return {string} The local variable name that corresponds to that module.
* @private
*/
getLocalName(pkg: string, moduleName: string): string;
/**
* @param {string} pkg The workbox package that the module belongs to.
* @param {string} moduleName The name of the module to import.
* @return {string} The local variable name that corresponds to that module.
* @private
*/
use(pkg: string, moduleName: string): string;
}

View File

@@ -0,0 +1,70 @@
"use strict";
/*
Copyright 2019 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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModuleRegistry = void 0;
const common_tags_1 = require("common-tags");
const upath_1 = __importDefault(require("upath"));
/**
* Class for keeping track of which Workbox modules are used by the generated
* service worker script.
*
* @private
*/
class ModuleRegistry {
/**
* @private
*/
constructor() {
this._modulesUsed = new Map();
}
/**
* @return {Array<string>} A list of all of the import statements that are
* needed for the modules being used.
* @private
*/
getImportStatements() {
const workboxModuleImports = [];
for (const [localName, { moduleName, pkg }] of this._modulesUsed) {
// By default require.resolve returns the resolved path of the 'main'
// field, which might be deeper than the package root. To work around
// this, we can find the package's root by resolving its package.json and
// strip the '/package.json' from the resolved path.
const pkgJsonPath = require.resolve(`${pkg}/package.json`);
const pkgRoot = upath_1.default.dirname(pkgJsonPath);
const importStatement = (0, common_tags_1.oneLine) `import {${moduleName} as ${localName}} from
'${pkgRoot}/${moduleName}.mjs';`;
workboxModuleImports.push(importStatement);
}
return workboxModuleImports;
}
/**
* @param {string} pkg The workbox package that the module belongs to.
* @param {string} moduleName The name of the module to import.
* @return {string} The local variable name that corresponds to that module.
* @private
*/
getLocalName(pkg, moduleName) {
return `${pkg.replace(/-/g, '_')}_${moduleName}`;
}
/**
* @param {string} pkg The workbox package that the module belongs to.
* @param {string} moduleName The name of the module to import.
* @return {string} The local variable name that corresponds to that module.
* @private
*/
use(pkg, moduleName) {
const localName = this.getLocalName(pkg, moduleName);
this._modulesUsed.set(localName, { moduleName, pkg });
return localName;
}
}
exports.ModuleRegistry = ModuleRegistry;

View File

@@ -0,0 +1,2 @@
import { ManifestTransform } from '../types';
export declare function noRevisionForURLsMatchingTransform(regexp: RegExp): ManifestTransform;

View File

@@ -0,0 +1,29 @@
"use strict";
/*
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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.noRevisionForURLsMatchingTransform = void 0;
const errors_1 = require("./errors");
function noRevisionForURLsMatchingTransform(regexp) {
if (!(regexp instanceof RegExp)) {
throw new Error(errors_1.errors['invalid-dont-cache-bust']);
}
return (originalManifest) => {
const manifest = originalManifest.map((entry) => {
if (typeof entry.url !== 'string') {
throw new Error(errors_1.errors['manifest-entry-bad-url']);
}
if (entry.url.match(regexp)) {
entry.revision = null;
}
return entry;
});
return { manifest };
};
}
exports.noRevisionForURLsMatchingTransform = noRevisionForURLsMatchingTransform;

View File

@@ -0,0 +1,4 @@
import { GeneratePartial, ManifestEntry } from '../types';
export declare function populateSWTemplate({ cacheId, cleanupOutdatedCaches, clientsClaim, directoryIndex, disableDevLogs, ignoreURLParametersMatching, importScripts, manifestEntries, navigateFallback, navigateFallbackDenylist, navigateFallbackAllowlist, navigationPreload, offlineGoogleAnalytics, runtimeCaching, skipWaiting, }: GeneratePartial & {
manifestEntries?: Array<ManifestEntry>;
}): string;

View File

@@ -0,0 +1,79 @@
"use strict";
/*
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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.populateSWTemplate = void 0;
const template_1 = __importDefault(require("lodash/template"));
const errors_1 = require("./errors");
const module_registry_1 = require("./module-registry");
const runtime_caching_converter_1 = require("./runtime-caching-converter");
const stringify_without_comments_1 = require("./stringify-without-comments");
const sw_template_1 = require("../templates/sw-template");
function populateSWTemplate({ cacheId, cleanupOutdatedCaches, clientsClaim, directoryIndex, disableDevLogs, ignoreURLParametersMatching, importScripts, manifestEntries = [], navigateFallback, navigateFallbackDenylist, navigateFallbackAllowlist, navigationPreload, offlineGoogleAnalytics, runtimeCaching = [], skipWaiting, }) {
// There needs to be at least something to precache, or else runtime caching.
if (!((manifestEntries === null || manifestEntries === void 0 ? void 0 : manifestEntries.length) > 0 || runtimeCaching.length > 0)) {
throw new Error(errors_1.errors['no-manifest-entries-or-runtime-caching']);
}
// These are all options that can be passed to the precacheAndRoute() method.
const precacheOptions = {
directoryIndex,
// An array of RegExp objects can't be serialized by JSON.stringify()'s
// default behavior, so if it's given, convert it manually.
ignoreURLParametersMatching: ignoreURLParametersMatching
? []
: undefined,
};
let precacheOptionsString = JSON.stringify(precacheOptions, null, 2);
if (ignoreURLParametersMatching) {
precacheOptionsString = precacheOptionsString.replace(`"ignoreURLParametersMatching": []`, `"ignoreURLParametersMatching": [` +
`${ignoreURLParametersMatching.join(', ')}]`);
}
let offlineAnalyticsConfigString = undefined;
if (offlineGoogleAnalytics) {
// If offlineGoogleAnalytics is a truthy value, we need to convert it to the
// format expected by the template.
offlineAnalyticsConfigString =
offlineGoogleAnalytics === true
? // If it's the literal value true, then use an empty config string.
'{}'
: // Otherwise, convert the config object into a more complex string, taking
// into account the fact that functions might need to be stringified.
(0, stringify_without_comments_1.stringifyWithoutComments)(offlineGoogleAnalytics);
}
const moduleRegistry = new module_registry_1.ModuleRegistry();
try {
const populatedTemplate = (0, template_1.default)(sw_template_1.swTemplate)({
cacheId,
cleanupOutdatedCaches,
clientsClaim,
disableDevLogs,
importScripts,
manifestEntries,
navigateFallback,
navigateFallbackDenylist,
navigateFallbackAllowlist,
navigationPreload,
offlineAnalyticsConfigString,
precacheOptionsString,
runtimeCaching: (0, runtime_caching_converter_1.runtimeCachingConverter)(moduleRegistry, runtimeCaching),
skipWaiting,
use: moduleRegistry.use.bind(moduleRegistry),
});
const workboxImportStatements = moduleRegistry.getImportStatements();
// We need the import statements for all of the Workbox runtime modules
// prepended, so that the correct bundle can be created.
return workboxImportStatements.join('\n') + populatedTemplate;
}
catch (error) {
throw new Error(`${errors_1.errors['populating-sw-tmpl-failed']} '${error instanceof Error && error.message ? error.message : ''}'`);
}
}
exports.populateSWTemplate = populateSWTemplate;

View File

@@ -0,0 +1,4 @@
export declare function rebasePath({ baseDirectory, file, }: {
baseDirectory: string;
file: string;
}): string;

View File

@@ -0,0 +1,24 @@
"use strict";
/*
Copyright 2019 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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.rebasePath = void 0;
const upath_1 = __importDefault(require("upath"));
function rebasePath({ baseDirectory, file, }) {
// The initial path is relative to the current directory, so make it absolute.
const absolutePath = upath_1.default.resolve(file);
// Convert the absolute path so that it's relative to the baseDirectory.
const relativePath = upath_1.default.relative(baseDirectory, absolutePath);
// Remove any leading ./ as it won't work in a glob pattern.
const normalizedPath = upath_1.default.normalize(relativePath);
return normalizedPath;
}
exports.rebasePath = rebasePath;

View File

@@ -0,0 +1,30 @@
import { RawSourceMap } from 'source-map';
/**
* Adapted from https://github.com/nsams/sourcemap-aware-replace, with modern
* JavaScript updates, along with additional properties copied from originalMap.
*
* @param {Object} options
* @param {string} options.jsFilename The name for the file whose contents
* correspond to originalSource.
* @param {Object} options.originalMap The sourcemap for originalSource,
* prior to any replacements.
* @param {string} options.originalSource The source code, prior to any
* replacements.
* @param {string} options.replaceString A string to swap in for searchString.
* @param {string} options.searchString A string in originalSource to replace.
* Only the first occurrence will be replaced.
* @return {{source: string, map: string}} An object containing both
* originalSource with the replacement applied, and the modified originalMap.
*
* @private
*/
export declare function replaceAndUpdateSourceMap({ jsFilename, originalMap, originalSource, replaceString, searchString, }: {
jsFilename: string;
originalMap: RawSourceMap;
originalSource: string;
replaceString: string;
searchString: string;
}): Promise<{
map: string;
source: string;
}>;

View File

@@ -0,0 +1,98 @@
"use strict";
/*
Copyright 2019 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.replaceAndUpdateSourceMap = void 0;
const source_map_1 = require("source-map");
/**
* Adapted from https://github.com/nsams/sourcemap-aware-replace, with modern
* JavaScript updates, along with additional properties copied from originalMap.
*
* @param {Object} options
* @param {string} options.jsFilename The name for the file whose contents
* correspond to originalSource.
* @param {Object} options.originalMap The sourcemap for originalSource,
* prior to any replacements.
* @param {string} options.originalSource The source code, prior to any
* replacements.
* @param {string} options.replaceString A string to swap in for searchString.
* @param {string} options.searchString A string in originalSource to replace.
* Only the first occurrence will be replaced.
* @return {{source: string, map: string}} An object containing both
* originalSource with the replacement applied, and the modified originalMap.
*
* @private
*/
async function replaceAndUpdateSourceMap({ jsFilename, originalMap, originalSource, replaceString, searchString, }) {
const generator = new source_map_1.SourceMapGenerator({
file: jsFilename,
});
const consumer = await new source_map_1.SourceMapConsumer(originalMap);
let pos;
let src = originalSource;
const replacements = [];
let lineNum = 0;
let filePos = 0;
const lines = src.split('\n');
for (let line of lines) {
lineNum++;
let searchPos = 0;
while ((pos = line.indexOf(searchString, searchPos)) !== -1) {
src =
src.substring(0, filePos + pos) +
replaceString +
src.substring(filePos + pos + searchString.length);
line =
line.substring(0, pos) +
replaceString +
line.substring(pos + searchString.length);
replacements.push({ line: lineNum, column: pos });
searchPos = pos + replaceString.length;
}
filePos += line.length + 1;
}
replacements.reverse();
consumer.eachMapping((mapping) => {
for (const replacement of replacements) {
if (replacement.line === mapping.generatedLine &&
mapping.generatedColumn > replacement.column) {
const offset = searchString.length - replaceString.length;
mapping.generatedColumn -= offset;
}
}
if (mapping.source) {
const newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn,
},
original: {
line: mapping.originalLine,
column: mapping.originalColumn,
},
source: mapping.source,
};
return generator.addMapping(newMapping);
}
return mapping;
});
consumer.destroy();
// JSON.parse returns any.
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const updatedSourceMap = Object.assign(JSON.parse(generator.toString()), {
names: originalMap.names,
sourceRoot: originalMap.sourceRoot,
sources: originalMap.sources,
sourcesContent: originalMap.sourcesContent,
});
return {
map: JSON.stringify(updatedSourceMap),
source: src,
};
}
exports.replaceAndUpdateSourceMap = replaceAndUpdateSourceMap;

View File

@@ -0,0 +1,3 @@
import { ModuleRegistry } from './module-registry';
import { RuntimeCaching } from '../types';
export declare function runtimeCachingConverter(moduleRegistry: ModuleRegistry, runtimeCaching: Array<RuntimeCaching>): Array<string>;

View File

@@ -0,0 +1,142 @@
"use strict";
/*
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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.runtimeCachingConverter = void 0;
const common_tags_1 = require("common-tags");
const errors_1 = require("./errors");
const stringify_without_comments_1 = require("./stringify-without-comments");
/**
* Given a set of options that configures runtime caching behavior, convert it
* to the equivalent Workbox method calls.
*
* @param {ModuleRegistry} moduleRegistry
* @param {Object} options See
* https://developers.google.com/web/tools/workbox/modules/workbox-build#generateSW-runtimeCaching
* @return {string} A JSON string representing the equivalent options.
*
* @private
*/
function getOptionsString(moduleRegistry, options = {}) {
const plugins = [];
const handlerOptions = {};
for (const optionName of Object.keys(options)) {
if (options[optionName] === undefined) {
continue;
}
switch (optionName) {
// Using a library here because JSON.stringify won't handle functions.
case 'plugins': {
plugins.push(...options.plugins.map(stringify_without_comments_1.stringifyWithoutComments));
break;
}
// These are the option properties that we want to pull out, so that
// they're passed to the handler constructor.
case 'cacheName':
case 'networkTimeoutSeconds':
case 'fetchOptions':
case 'matchOptions': {
handlerOptions[optionName] = options[optionName];
break;
}
// The following cases are all shorthands for creating a plugin with a
// given configuration.
case 'backgroundSync': {
const name = options.backgroundSync.name;
const plugin = moduleRegistry.use('workbox-background-sync', 'BackgroundSyncPlugin');
let pluginCode = `new ${plugin}(${JSON.stringify(name)}`;
if (options.backgroundSync.options) {
pluginCode += `, ${(0, stringify_without_comments_1.stringifyWithoutComments)(options.backgroundSync.options)}`;
}
pluginCode += `)`;
plugins.push(pluginCode);
break;
}
case 'broadcastUpdate': {
const channelName = options.broadcastUpdate.channelName;
const opts = Object.assign({ channelName }, options.broadcastUpdate.options);
const plugin = moduleRegistry.use('workbox-broadcast-update', 'BroadcastUpdatePlugin');
plugins.push(`new ${plugin}(${(0, stringify_without_comments_1.stringifyWithoutComments)(opts)})`);
break;
}
case 'cacheableResponse': {
const plugin = moduleRegistry.use('workbox-cacheable-response', 'CacheableResponsePlugin');
plugins.push(`new ${plugin}(${(0, stringify_without_comments_1.stringifyWithoutComments)(options.cacheableResponse)})`);
break;
}
case 'expiration': {
const plugin = moduleRegistry.use('workbox-expiration', 'ExpirationPlugin');
plugins.push(`new ${plugin}(${(0, stringify_without_comments_1.stringifyWithoutComments)(options.expiration)})`);
break;
}
case 'precacheFallback': {
const plugin = moduleRegistry.use('workbox-precaching', 'PrecacheFallbackPlugin');
plugins.push(`new ${plugin}(${(0, stringify_without_comments_1.stringifyWithoutComments)(options.precacheFallback)})`);
break;
}
case 'rangeRequests': {
const plugin = moduleRegistry.use('workbox-range-requests', 'RangeRequestsPlugin');
// There are no configuration options for the constructor.
plugins.push(`new ${plugin}()`);
break;
}
default: {
throw new Error(
// In the default case optionName is typed as 'never'.
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`${errors_1.errors['bad-runtime-caching-config']} ${optionName}`);
}
}
}
if (Object.keys(handlerOptions).length > 0 || plugins.length > 0) {
const optionsString = JSON.stringify(handlerOptions).slice(1, -1);
return (0, common_tags_1.oneLine) `{
${optionsString ? optionsString + ',' : ''}
plugins: [${plugins.join(', ')}]
}`;
}
else {
return '';
}
}
function runtimeCachingConverter(moduleRegistry, runtimeCaching) {
return runtimeCaching
.map((entry) => {
const method = entry.method || 'GET';
if (!entry.urlPattern) {
throw new Error(errors_1.errors['urlPattern-is-required']);
}
if (!entry.handler) {
throw new Error(errors_1.errors['handler-is-required']);
}
if (entry.options &&
entry.options.networkTimeoutSeconds &&
entry.handler !== 'NetworkFirst') {
throw new Error(errors_1.errors['invalid-network-timeout-seconds']);
}
// urlPattern might be a string, a RegExp object, or a function.
// If it's a string, it needs to be quoted.
const matcher = typeof entry.urlPattern === 'string'
? JSON.stringify(entry.urlPattern)
: entry.urlPattern;
const registerRoute = moduleRegistry.use('workbox-routing', 'registerRoute');
if (typeof entry.handler === 'string') {
const optionsString = getOptionsString(moduleRegistry, entry.options);
const handler = moduleRegistry.use('workbox-strategies', entry.handler);
const strategyString = `new ${handler}(${optionsString})`;
return `${registerRoute}(${matcher.toString()}, ${strategyString}, '${method}');\n`;
}
else if (typeof entry.handler === 'function') {
return `${registerRoute}(${matcher.toString()}, ${entry.handler.toString()}, '${method}');\n`;
}
// '' will be filtered out.
return '';
})
.filter((entry) => Boolean(entry));
}
exports.runtimeCachingConverter = runtimeCachingConverter;

View File

@@ -0,0 +1,3 @@
export declare function stringifyWithoutComments(obj: {
[key: string]: any;
}): string;

View File

@@ -0,0 +1,28 @@
"use strict";
/*
Copyright 2021 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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.stringifyWithoutComments = void 0;
const stringify_object_1 = __importDefault(require("stringify-object"));
const strip_comments_1 = __importDefault(require("strip-comments"));
function stringifyWithoutComments(obj) {
return (0, stringify_object_1.default)(obj, {
// See https://github.com/yeoman/stringify-object#transformobject-property-originalresult
transform: (_obj, _prop, str) => {
if (typeof _prop !== 'symbol' && typeof _obj[_prop] === 'function') {
// Can't typify correctly stripComments
return (0, strip_comments_1.default)(str); // eslint-disable-line
}
return str;
},
});
}
exports.stringifyWithoutComments = stringifyWithoutComments;

View File

@@ -0,0 +1,63 @@
import { BasePartial, FileDetails, ManifestEntry } from '../types';
/**
* A `ManifestTransform` function can be used to modify the modify the `url` or
* `revision` properties of some or all of the
* {@link workbox-build.ManifestEntry} in the manifest.
*
* Deleting the `revision` property of an entry will cause
* the corresponding `url` to be precached without cache-busting parameters
* applied, which is to say, it implies that the URL itself contains
* proper versioning info. If the `revision` property is present, it must be
* set to a string.
*
* @example A transformation that prepended the origin of a CDN for any
* URL starting with '/assets/' could be implemented as:
*
* const cdnTransform = async (manifestEntries) => {
* const manifest = manifestEntries.map(entry => {
* const cdnOrigin = 'https://example.com';
* if (entry.url.startsWith('/assets/')) {
* entry.url = cdnOrigin + entry.url;
* }
* return entry;
* });
* return {manifest, warnings: []};
* };
*
* @example A transformation that nulls the revision field when the
* URL contains an 8-character hash surrounded by '.', indicating that it
* already contains revision information:
*
* const removeRevisionTransform = async (manifestEntries) => {
* const manifest = manifestEntries.map(entry => {
* const hashRegExp = /\.\w{8}\./;
* if (entry.url.match(hashRegExp)) {
* entry.revision = null;
* }
* return entry;
* });
* return {manifest, warnings: []};
* };
*
* @callback ManifestTransform
* @param {Array<workbox-build.ManifestEntry>} manifestEntries The full
* array of entries, prior to the current transformation.
* @param {Object} [compilation] When used in the webpack plugins, this param
* will be set to the current `compilation`.
* @return {Promise<workbox-build.ManifestTransformResult>}
* The array of entries with the transformation applied, and optionally, any
* warnings that should be reported back to the build tool.
*
* @memberof workbox-build
*/
interface ManifestTransformResultWithWarnings {
count: number;
size: number;
manifestEntries: ManifestEntry[];
warnings: string[];
}
export declare function transformManifest({ additionalManifestEntries, dontCacheBustURLsMatching, fileDetails, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, transformParam, }: BasePartial & {
fileDetails: Array<FileDetails>;
transformParam?: unknown;
}): Promise<ManifestTransformResultWithWarnings>;
export {};

View File

@@ -0,0 +1,69 @@
"use strict";
/*
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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.transformManifest = void 0;
const additional_manifest_entries_transform_1 = require("./additional-manifest-entries-transform");
const errors_1 = require("./errors");
const maximum_size_transform_1 = require("./maximum-size-transform");
const modify_url_prefix_transform_1 = require("./modify-url-prefix-transform");
const no_revision_for_urls_matching_transform_1 = require("./no-revision-for-urls-matching-transform");
async function transformManifest({ additionalManifestEntries, dontCacheBustURLsMatching, fileDetails, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, transformParam, }) {
const allWarnings = [];
// Take the array of fileDetail objects and convert it into an array of
// {url, revision, size} objects, with \ replaced with /.
const normalizedManifest = fileDetails.map((fileDetails) => {
return {
url: fileDetails.file.replace(/\\/g, '/'),
revision: fileDetails.hash,
size: fileDetails.size,
};
});
const transformsToApply = [];
if (maximumFileSizeToCacheInBytes) {
transformsToApply.push((0, maximum_size_transform_1.maximumSizeTransform)(maximumFileSizeToCacheInBytes));
}
if (modifyURLPrefix) {
transformsToApply.push((0, modify_url_prefix_transform_1.modifyURLPrefixTransform)(modifyURLPrefix));
}
if (dontCacheBustURLsMatching) {
transformsToApply.push((0, no_revision_for_urls_matching_transform_1.noRevisionForURLsMatchingTransform)(dontCacheBustURLsMatching));
}
// Run any manifestTransforms functions second-to-last.
if (manifestTransforms) {
transformsToApply.push(...manifestTransforms);
}
// Run additionalManifestEntriesTransform last.
if (additionalManifestEntries) {
transformsToApply.push((0, additional_manifest_entries_transform_1.additionalManifestEntriesTransform)(additionalManifestEntries));
}
let transformedManifest = normalizedManifest;
for (const transform of transformsToApply) {
const result = await transform(transformedManifest, transformParam);
if (!('manifest' in result)) {
throw new Error(errors_1.errors['bad-manifest-transforms-return-value']);
}
transformedManifest = result.manifest;
allWarnings.push(...(result.warnings || []));
}
// Generate some metadata about the manifest before we clear out the size
// properties from each entry.
const count = transformedManifest.length;
let size = 0;
for (const manifestEntry of transformedManifest) {
size += manifestEntry.size || 0;
delete manifestEntry.size;
}
return {
count,
size,
manifestEntries: transformedManifest,
warnings: allWarnings,
};
}
exports.transformManifest = transformManifest;

View File

@@ -0,0 +1,5 @@
export declare function translateURLToSourcemapPaths(url: string | null, swSrc: string, swDest: string): {
destPath: string | undefined;
srcPath: string | undefined;
warning: string | undefined;
};

View File

@@ -0,0 +1,33 @@
"use strict";
/*
Copyright 2021 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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.translateURLToSourcemapPaths = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const upath_1 = __importDefault(require("upath"));
const errors_1 = require("./errors");
function translateURLToSourcemapPaths(url, swSrc, swDest) {
let destPath = undefined;
let srcPath = undefined;
let warning = undefined;
if (url && !url.startsWith('data:')) {
const possibleSrcPath = upath_1.default.resolve(upath_1.default.dirname(swSrc), url);
if (fs_extra_1.default.existsSync(possibleSrcPath)) {
srcPath = possibleSrcPath;
destPath = upath_1.default.resolve(upath_1.default.dirname(swDest), url);
}
else {
warning = `${errors_1.errors['cant-find-sourcemap']} ${possibleSrcPath}`;
}
}
return { destPath, srcPath, warning };
}
exports.translateURLToSourcemapPaths = translateURLToSourcemapPaths;

View File

@@ -0,0 +1,9 @@
import { GenerateSWOptions, GetManifestOptions, InjectManifestOptions, WebpackGenerateSWOptions, WebpackInjectManifestOptions } from '../types';
export declare class WorkboxConfigError extends Error {
constructor(message?: string);
}
export declare function validateGenerateSWOptions(input: unknown): GenerateSWOptions;
export declare function validateGetManifestOptions(input: unknown): GetManifestOptions;
export declare function validateInjectManifestOptions(input: unknown): InjectManifestOptions;
export declare function validateWebpackGenerateSWOptions(input: unknown): WebpackGenerateSWOptions;
export declare function validateWebpackInjectManifestOptions(input: unknown): WebpackInjectManifestOptions;

View File

@@ -0,0 +1,147 @@
"use strict";
/*
Copyright 2021 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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateWebpackInjectManifestOptions = exports.validateWebpackGenerateSWOptions = exports.validateInjectManifestOptions = exports.validateGetManifestOptions = exports.validateGenerateSWOptions = exports.WorkboxConfigError = void 0;
const better_ajv_errors_1 = require("@apideck/better-ajv-errors");
const common_tags_1 = require("common-tags");
const ajv_1 = __importDefault(require("ajv"));
const errors_1 = require("./errors");
const ajv = new ajv_1.default({
useDefaults: true,
});
const DEFAULT_EXCLUDE_VALUE = [/\.map$/, /^manifest.*\.js$/];
class WorkboxConfigError extends Error {
constructor(message) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
}
}
exports.WorkboxConfigError = WorkboxConfigError;
// Some methods need to do follow-up validation using the JSON schema,
// so return both the validated options and then schema.
function validate(input, methodName) {
// Don't mutate input: https://github.com/GoogleChrome/workbox/issues/2158
const inputCopy = Object.assign({}, input);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const jsonSchema = require(`../schema/${methodName}Options.json`);
const validate = ajv.compile(jsonSchema);
if (validate(inputCopy)) {
// All methods support manifestTransforms, so validate it here.
ensureValidManifestTransforms(inputCopy);
return [inputCopy, jsonSchema];
}
const betterErrors = (0, better_ajv_errors_1.betterAjvErrors)({
basePath: methodName,
data: input,
errors: validate.errors,
// This is needed as JSONSchema6 is expected, but JSONSchemaType works.
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
schema: jsonSchema,
});
const messages = betterErrors.map((err) => (0, common_tags_1.oneLine) `[${err.path}] ${err.message}.
${err.suggestion ? err.suggestion : ''}`);
throw new WorkboxConfigError(messages.join('\n\n'));
}
function ensureValidManifestTransforms(options) {
if ('manifestTransforms' in options &&
!(Array.isArray(options.manifestTransforms) &&
options.manifestTransforms.every((item) => typeof item === 'function'))) {
throw new WorkboxConfigError(errors_1.errors['manifest-transforms']);
}
}
function ensureValidNavigationPreloadConfig(options) {
if (options.navigationPreload &&
(!Array.isArray(options.runtimeCaching) ||
options.runtimeCaching.length === 0)) {
throw new WorkboxConfigError(errors_1.errors['nav-preload-runtime-caching']);
}
}
function ensureValidCacheExpiration(options) {
var _a, _b;
for (const runtimeCaching of options.runtimeCaching || []) {
if (((_a = runtimeCaching.options) === null || _a === void 0 ? void 0 : _a.expiration) &&
!((_b = runtimeCaching.options) === null || _b === void 0 ? void 0 : _b.cacheName)) {
throw new WorkboxConfigError(errors_1.errors['cache-name-required']);
}
}
}
function ensureValidRuntimeCachingOrGlobDirectory(options) {
if (!options.globDirectory &&
(!Array.isArray(options.runtimeCaching) ||
options.runtimeCaching.length === 0)) {
throw new WorkboxConfigError(errors_1.errors['no-manifest-entries-or-runtime-caching']);
}
}
// This is... messy, because we can't rely on the built-in ajv validation for
// runtimeCaching.handler, as it needs to accept {} (i.e. any) due to
// https://github.com/GoogleChrome/workbox/pull/2899
// So we need to perform validation when a string (not a function) is used.
function ensureValidStringHandler(options, jsonSchema) {
var _a, _b, _c, _d;
let validHandlers = [];
/* eslint-disable */
for (const handler of ((_d = (_c = (_b = (_a = jsonSchema.definitions) === null || _a === void 0 ? void 0 : _a.RuntimeCaching) === null || _b === void 0 ? void 0 : _b.properties) === null || _c === void 0 ? void 0 : _c.handler) === null || _d === void 0 ? void 0 : _d.anyOf) || []) {
if ('enum' in handler) {
validHandlers = handler.enum;
break;
}
}
/* eslint-enable */
for (const runtimeCaching of options.runtimeCaching || []) {
if (typeof runtimeCaching.handler === 'string' &&
!validHandlers.includes(runtimeCaching.handler)) {
throw new WorkboxConfigError(errors_1.errors['invalid-handler-string'] + runtimeCaching.handler);
}
}
}
function validateGenerateSWOptions(input) {
const [validatedOptions, jsonSchema] = validate(input, 'GenerateSW');
ensureValidNavigationPreloadConfig(validatedOptions);
ensureValidCacheExpiration(validatedOptions);
ensureValidRuntimeCachingOrGlobDirectory(validatedOptions);
ensureValidStringHandler(validatedOptions, jsonSchema);
return validatedOptions;
}
exports.validateGenerateSWOptions = validateGenerateSWOptions;
function validateGetManifestOptions(input) {
const [validatedOptions] = validate(input, 'GetManifest');
return validatedOptions;
}
exports.validateGetManifestOptions = validateGetManifestOptions;
function validateInjectManifestOptions(input) {
const [validatedOptions] = validate(input, 'InjectManifest');
return validatedOptions;
}
exports.validateInjectManifestOptions = validateInjectManifestOptions;
// The default `exclude: [/\.map$/, /^manifest.*\.js$/]` value can't be
// represented in the JSON schema, so manually set it for the webpack options.
function validateWebpackGenerateSWOptions(input) {
const inputWithExcludeDefault = Object.assign({
// Make a copy, as exclude can be mutated when used.
exclude: Array.from(DEFAULT_EXCLUDE_VALUE),
}, input);
const [validatedOptions, jsonSchema] = validate(inputWithExcludeDefault, 'WebpackGenerateSW');
ensureValidNavigationPreloadConfig(validatedOptions);
ensureValidCacheExpiration(validatedOptions);
ensureValidStringHandler(validatedOptions, jsonSchema);
return validatedOptions;
}
exports.validateWebpackGenerateSWOptions = validateWebpackGenerateSWOptions;
function validateWebpackInjectManifestOptions(input) {
const inputWithExcludeDefault = Object.assign({
// Make a copy, as exclude can be mutated when used.
exclude: Array.from(DEFAULT_EXCLUDE_VALUE),
}, input);
const [validatedOptions] = validate(inputWithExcludeDefault, 'WebpackInjectManifest');
return validatedOptions;
}
exports.validateWebpackInjectManifestOptions = validateWebpackInjectManifestOptions;

View File

@@ -0,0 +1,4 @@
import { GenerateSWOptions, ManifestEntry } from '../types';
export declare 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>>;

View File

@@ -0,0 +1,71 @@
"use strict";
/*
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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeSWUsingDefaultTemplate = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const upath_1 = __importDefault(require("upath"));
const bundle_1 = require("./bundle");
const errors_1 = require("./errors");
const populate_sw_template_1 = require("./populate-sw-template");
async function writeSWUsingDefaultTemplate({ babelPresetEnvTargets, cacheId, cleanupOutdatedCaches, clientsClaim, directoryIndex, disableDevLogs, ignoreURLParametersMatching, importScripts, inlineWorkboxRuntime, manifestEntries, mode, navigateFallback, navigateFallbackDenylist, navigateFallbackAllowlist, navigationPreload, offlineGoogleAnalytics, runtimeCaching, skipWaiting, sourcemap, swDest, }) {
const outputDir = upath_1.default.dirname(swDest);
try {
await fs_extra_1.default.mkdirp(outputDir);
}
catch (error) {
throw new Error(`${errors_1.errors['unable-to-make-sw-directory']}. ` +
`'${error instanceof Error && error.message ? error.message : ''}'`);
}
const unbundledCode = (0, populate_sw_template_1.populateSWTemplate)({
cacheId,
cleanupOutdatedCaches,
clientsClaim,
directoryIndex,
disableDevLogs,
ignoreURLParametersMatching,
importScripts,
manifestEntries,
navigateFallback,
navigateFallbackDenylist,
navigateFallbackAllowlist,
navigationPreload,
offlineGoogleAnalytics,
runtimeCaching,
skipWaiting,
});
try {
const files = await (0, bundle_1.bundle)({
babelPresetEnvTargets,
inlineWorkboxRuntime,
mode,
sourcemap,
swDest,
unbundledCode,
});
const filePaths = [];
for (const file of files) {
const filePath = upath_1.default.resolve(file.name);
filePaths.push(filePath);
await fs_extra_1.default.writeFile(filePath, file.contents);
}
return filePaths;
}
catch (error) {
const err = error;
if (err.code === 'EISDIR') {
// See https://github.com/GoogleChrome/workbox/issues/612
throw new Error(errors_1.errors['sw-write-failure-directory']);
}
throw new Error(`${errors_1.errors['sw-write-failure']} '${err.message}'`);
}
}
exports.writeSWUsingDefaultTemplate = writeSWUsingDefaultTemplate;