mirror of
https://github.com/hanzoai/workbox.git
synced 2026-09-24 17:04:35 +00:00
feat: migrate workbox-webpack-plugin to typescript (#2882)
* feat: migrate workbox-webpack-plugin to typescript * progress on typescript migration * 15e from ts lint * draft * fixing webpack version * running tests * running tests * eslint * passing tests for workbox webpack plugin * passing tests for wb wpp * passing tests for workbox webpack plugin passing tests for wb wpp cleaning imports * cleaning some eslint messages * keeping the checkConditions method signature for backward compatibility * fixing documentation * commiting package-lock * updating the webpack plugin package-lock * Fixing typescript typing issues Co-authored-by: Adriana Jara Salazar <[email protected]> Co-authored-by: Adriana Jara <[email protected]>
This commit is contained in:
committed by
GitHub
co-authored by
Adriana Jara Salazar
Adriana Jara
parent
1b6861794b
commit
d731474fc9
Generated
+25575
-132
File diff suppressed because it is too large
Load Diff
+1
-2
@@ -123,6 +123,5 @@
|
||||
"test_node": "gulp test_node",
|
||||
"test_server": "gulp test_server",
|
||||
"version": "gulp build && git add -A packages"
|
||||
},
|
||||
"version": "0.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,9 +31,9 @@ export function populateSWTemplate({
|
||||
offlineGoogleAnalytics,
|
||||
runtimeCaching = [],
|
||||
skipWaiting,
|
||||
}: GeneratePartial & {manifestEntries: Array<ManifestEntry>}): string {
|
||||
}: GeneratePartial & {manifestEntries?: Array<ManifestEntry>}): string {
|
||||
// There needs to be at least something to precache, or else runtime caching.
|
||||
if (!(manifestEntries.length > 0 || runtimeCaching.length > 0)) {
|
||||
if (!(manifestEntries?.length > 0 || runtimeCaching.length > 0)) {
|
||||
throw new Error(errors['no-manifest-entries-or-runtime-caching']);
|
||||
}
|
||||
|
||||
|
||||
@@ -467,11 +467,14 @@
|
||||
"QueueOptions": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"onSync": {
|
||||
"$ref": "#/definitions/OnSyncCallback"
|
||||
"forceSyncFallback": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"maxRetentionTime": {
|
||||
"type": "number"
|
||||
},
|
||||
"onSync": {
|
||||
"$ref": "#/definitions/OnSyncCallback"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
|
||||
@@ -342,11 +342,14 @@
|
||||
"QueueOptions": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"onSync": {
|
||||
"$ref": "#/definitions/OnSyncCallback"
|
||||
"forceSyncFallback": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"maxRetentionTime": {
|
||||
"type": "number"
|
||||
},
|
||||
"onSync": {
|
||||
"$ref": "#/definitions/OnSyncCallback"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
|
||||
@@ -357,11 +357,14 @@
|
||||
"QueueOptions": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"onSync": {
|
||||
"$ref": "#/definitions/OnSyncCallback"
|
||||
"forceSyncFallback": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"maxRetentionTime": {
|
||||
"type": "number"
|
||||
},
|
||||
"onSync": {
|
||||
"$ref": "#/definitions/OnSyncCallback"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
|
||||
@@ -445,11 +445,14 @@
|
||||
"QueueOptions": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"onSync": {
|
||||
"$ref": "#/definitions/OnSyncCallback"
|
||||
"forceSyncFallback": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"maxRetentionTime": {
|
||||
"type": "number"
|
||||
},
|
||||
"onSync": {
|
||||
"$ref": "#/definitions/OnSyncCallback"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
|
||||
@@ -345,11 +345,14 @@
|
||||
"QueueOptions": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"onSync": {
|
||||
"$ref": "#/definitions/OnSyncCallback"
|
||||
"forceSyncFallback": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"maxRetentionTime": {
|
||||
"type": "number"
|
||||
},
|
||||
"onSync": {
|
||||
"$ref": "#/definitions/OnSyncCallback"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
|
||||
@@ -437,7 +437,8 @@ export interface WebpackPartial {
|
||||
* as `webpack`'s standard `exclude` option.
|
||||
* If not provided, the default value is `[/\.map$/, /^manifest.*\.js$]`.
|
||||
*/
|
||||
exclude?: Array<string | RegExp | ((arg0: string) => boolean)>;
|
||||
//eslint-disable-next-line @typescript-eslint/ban-types
|
||||
exclude?: Array<string | RegExp | ((arg0: any) => boolean)>;
|
||||
/**
|
||||
* One or more chunk names whose corresponding output files should be excluded
|
||||
* from the precache manifest.
|
||||
@@ -449,7 +450,8 @@ export interface WebpackPartial {
|
||||
* [the same rules](https://webpack.js.org/configuration/module/#condition)
|
||||
* as `webpack`'s standard `include` option.
|
||||
*/
|
||||
include?: Array<string | RegExp | ((arg0: string) => boolean)>;
|
||||
//eslint-disable-next-line @typescript-eslint/ban-types
|
||||
include?: Array<string | RegExp | ((arg0: any) => boolean)>;
|
||||
/**
|
||||
* If set to 'production', then an optimized service worker bundle that
|
||||
* excludes debugging info will be produced. If not explicitly configured
|
||||
|
||||
+6688
-45
File diff suppressed because it is too large
Load Diff
@@ -13,12 +13,10 @@
|
||||
"file manifest"
|
||||
],
|
||||
"workbox": {
|
||||
"packageType": "node"
|
||||
"packageType": "node_ts"
|
||||
},
|
||||
"main": "build/index.js",
|
||||
"files": [
|
||||
"build"
|
||||
],
|
||||
"types": "build/index.d.ts",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
@@ -33,6 +31,9 @@
|
||||
"peerDependencies": {
|
||||
"webpack": "^4.4.0 || ^5.9.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/webpack": "^5.28.0"
|
||||
},
|
||||
"author": "Google's Web DevRel Team",
|
||||
"license": "MIT",
|
||||
"repository": "googlechrome/workbox",
|
||||
|
||||
+87
-54
@@ -6,18 +6,15 @@
|
||||
https://opensource.org/licenses/MIT.
|
||||
*/
|
||||
|
||||
const {validateWebpackGenerateSWOptions} =
|
||||
require('workbox-build/build/lib/validate-options');
|
||||
const {bundle} = require('workbox-build/build/lib/bundle');
|
||||
const {populateSWTemplate} =
|
||||
require('workbox-build/build/lib/populate-sw-template');
|
||||
const prettyBytes = require('pretty-bytes');
|
||||
const webpack = require('webpack');
|
||||
|
||||
const getScriptFilesForChunks = require('./lib/get-script-files-for-chunks');
|
||||
const getManifestEntriesFromCompilation =
|
||||
require('./lib/get-manifest-entries-from-compilation');
|
||||
const relativeToOutputPath = require('./lib/relative-to-output-path');
|
||||
import {validateWebpackGenerateSWOptions} from 'workbox-build/build/lib/validate-options';
|
||||
import {bundle} from 'workbox-build/build/lib/bundle';
|
||||
import {populateSWTemplate} from 'workbox-build/build/lib/populate-sw-template';
|
||||
import prettyBytes from 'pretty-bytes';
|
||||
import webpack from 'webpack';
|
||||
import {ManifestEntry, WebpackGenerateSWOptions} from 'workbox-build';
|
||||
import {getScriptFilesForChunks} from './lib/get-script-files-for-chunks';
|
||||
import {getManifestEntriesFromCompilation} from './lib/get-manifest-entries-from-compilation';
|
||||
import {relativeToOutputPath} from './lib/relative-to-output-path';
|
||||
|
||||
// webpack v4/v5 compatibility:
|
||||
// https://github.com/webpack/webpack/issues/11425#issuecomment-686607633
|
||||
@@ -25,7 +22,11 @@ const {RawSource} = webpack.sources || require('webpack-sources');
|
||||
|
||||
// Used to keep track of swDest files written by *any* instance of this plugin.
|
||||
// See https://github.com/GoogleChrome/workbox/issues/2181
|
||||
const _generatedAssetNames = new Set();
|
||||
const _generatedAssetNames = new Set<string>();
|
||||
|
||||
interface GenerateSWConfig extends WebpackGenerateSWOptions {
|
||||
manifestEntries?: Array<ManifestEntry>;
|
||||
}
|
||||
|
||||
/**
|
||||
* This class supports creating a new, ready-to-use service worker file as
|
||||
@@ -38,6 +39,8 @@ const _generatedAssetNames = new Set();
|
||||
* @memberof module:workbox-webpack-plugin
|
||||
*/
|
||||
class GenerateSW {
|
||||
private config: GenerateSWConfig;
|
||||
private alreadyCalled: boolean;
|
||||
// eslint-disable-next-line jsdoc/newline-after-description
|
||||
/**
|
||||
* Creates an instance of GenerateSW.
|
||||
@@ -79,7 +82,7 @@ class GenerateSW {
|
||||
* [asset's metadata](https://github.com/webpack/webpack/issues/9038) is used
|
||||
* to determine whether it's immutable or not.)
|
||||
*
|
||||
* @param {Array<string|RegExp|Function>} [config.exclude=[/\.map$/, /^manifest.*\.js$]]
|
||||
* @param {Array<string|RegExp>} [config.exclude=[/\.map$/, /^manifest.*\.js$]]
|
||||
* One or more specifiers used to exclude assets from the precache manifest.
|
||||
* This is interpreted following
|
||||
* [the same rules](https://webpack.js.org/configuration/module/#condition)
|
||||
@@ -104,7 +107,7 @@ class GenerateSW {
|
||||
* webpack chunks. The content of those chunks will be included in the
|
||||
* generated service worker, via a call to `importScripts()`.
|
||||
*
|
||||
* @param {Array<string|RegExp|Function>} [config.include]
|
||||
* @param {Array<string|RegExp>} [config.include]
|
||||
* One or more specifiers used to include assets in the precache manifest.
|
||||
* This is interpreted following
|
||||
* [the same rules](https://webpack.js.org/configuration/module/#condition)
|
||||
@@ -190,7 +193,7 @@ class GenerateSW {
|
||||
* @param {string} [config.swDest='service-worker.js'] The asset name of the
|
||||
* service worker file that will be created by this plugin.
|
||||
*/
|
||||
constructor(config = {}) {
|
||||
constructor(config: GenerateSWConfig = {}) {
|
||||
this.config = config;
|
||||
this.alreadyCalled = false;
|
||||
}
|
||||
@@ -200,13 +203,16 @@ class GenerateSW {
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
propagateWebpackConfig(compiler) {
|
||||
propagateWebpackConfig(compiler: webpack.Compiler): void {
|
||||
// Because this.config is listed last, properties that are already set
|
||||
// there take precedence over derived properties from the compiler.
|
||||
this.config = Object.assign({
|
||||
mode: compiler.options.mode,
|
||||
sourcemap: Boolean(compiler.options.devtool),
|
||||
}, this.config);
|
||||
this.config = Object.assign(
|
||||
{
|
||||
mode: compiler.options.mode,
|
||||
sourcemap: Boolean(compiler.options.devtool),
|
||||
},
|
||||
this.config,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -214,32 +220,39 @@ class GenerateSW {
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
apply(compiler) {
|
||||
apply(compiler: webpack.Compiler): void {
|
||||
this.propagateWebpackConfig(compiler);
|
||||
|
||||
// webpack v4/v5 compatibility:
|
||||
// https://github.com/webpack/webpack/issues/11425#issuecomment-690387207
|
||||
if (webpack.version.startsWith('4.')) {
|
||||
compiler.hooks.emit.tapPromise(
|
||||
this.constructor.name,
|
||||
(compilation) => this.addAssets(compilation).catch(
|
||||
(error) => compilation.errors.push(error)),
|
||||
compiler.hooks.emit.tapPromise(this.constructor.name, (compilation) =>
|
||||
this.addAssets(compilation).catch((error) => {
|
||||
compilation.errors.push(error);
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
const {PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER} = webpack.Compilation;
|
||||
// Specifically hook into thisCompilation, as per
|
||||
// https://github.com/webpack/webpack/issues/11425#issuecomment-690547848
|
||||
compiler.hooks.thisCompilation.tap(
|
||||
this.constructor.name, (compilation) => {
|
||||
compilation.hooks.processAssets.tapPromise({
|
||||
this.constructor.name,
|
||||
(compilation) => {
|
||||
compilation.hooks.processAssets.tapPromise(
|
||||
{
|
||||
name: this.constructor.name,
|
||||
// TODO(jeffposnick): This may need to change eventually.
|
||||
// See https://github.com/webpack/webpack/issues/11822#issuecomment-726184972
|
||||
stage: PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER - 10,
|
||||
}, () => this.addAssets(compilation).catch(
|
||||
(error) => compilation.errors.push(error)),
|
||||
);
|
||||
},
|
||||
},
|
||||
() =>
|
||||
this.addAssets(compilation).catch(
|
||||
(error: webpack.WebpackError) => {
|
||||
compilation.errors.push(error);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -249,53 +262,69 @@ class GenerateSW {
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
async addAssets(compilation) {
|
||||
async addAssets(compilation: webpack.Compilation): Promise<void> {
|
||||
// See https://github.com/GoogleChrome/workbox/issues/1790
|
||||
if (this.alreadyCalled) {
|
||||
const warningMessage = `${this.constructor.name} has been called ` +
|
||||
const warningMessage =
|
||||
`${this.constructor.name} has been called ` +
|
||||
`multiple times, perhaps due to running webpack in --watch mode. The ` +
|
||||
`precache manifest generated after the first call may be inaccurate! ` +
|
||||
`Please see https://github.com/GoogleChrome/workbox/issues/1790 for ` +
|
||||
`more information.`;
|
||||
|
||||
if (!compilation.warnings.some((warning) => warning instanceof Error &&
|
||||
warning.message === warningMessage)) {
|
||||
compilation.warnings.push(new Error(warningMessage));
|
||||
if (
|
||||
!compilation.warnings.some(
|
||||
(warning) =>
|
||||
warning instanceof Error && warning.message === warningMessage,
|
||||
)
|
||||
) {
|
||||
compilation.warnings.push(
|
||||
Error(warningMessage) as webpack.WebpackError,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
this.alreadyCalled = true;
|
||||
}
|
||||
|
||||
let config;
|
||||
let config: GenerateSWConfig = {};
|
||||
try {
|
||||
// emit might be called multiple times; instead of modifying this.config,
|
||||
// use a validated copy.
|
||||
// See https://github.com/GoogleChrome/workbox/issues/2158
|
||||
config = validateWebpackGenerateSWOptions(this.config);
|
||||
} catch (error) {
|
||||
throw new Error(`Please check your ${this.constructor.name} plugin ` +
|
||||
`configuration:\n${error.message}`);
|
||||
if (error instanceof Error) {
|
||||
throw new Error(
|
||||
`Please check your ${this.constructor.name} plugin ` +
|
||||
`configuration:\n${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure that we don't precache any of the assets generated by *any*
|
||||
// instance of this plugin.
|
||||
config.exclude.push(({asset}) => _generatedAssetNames.has(asset.name));
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
config.exclude!.push(({asset}) => _generatedAssetNames.has(asset.name));
|
||||
|
||||
if (config.importScriptsViaChunks) {
|
||||
// Anything loaded via importScripts() is implicitly cached by the service
|
||||
// worker, and should not be added to the precache manifest.
|
||||
config.excludeChunks = (config.excludeChunks || [])
|
||||
.concat(config.importScriptsViaChunks);
|
||||
config.excludeChunks = (config.excludeChunks || []).concat(
|
||||
config.importScriptsViaChunks,
|
||||
);
|
||||
|
||||
const scripts = getScriptFilesForChunks(
|
||||
compilation, config.importScriptsViaChunks);
|
||||
compilation,
|
||||
config.importScriptsViaChunks,
|
||||
);
|
||||
|
||||
config.importScripts = (config.importScripts || [])
|
||||
.concat(scripts);
|
||||
config.importScripts = (config.importScripts || []).concat(scripts);
|
||||
}
|
||||
|
||||
const {size, sortedEntries} = await getManifestEntriesFromCompilation(
|
||||
compilation, config);
|
||||
compilation,
|
||||
config,
|
||||
);
|
||||
config.manifestEntries = sortedEntries;
|
||||
|
||||
const unbundledCode = populateSWTemplate(config);
|
||||
@@ -305,24 +334,28 @@ class GenerateSW {
|
||||
inlineWorkboxRuntime: config.inlineWorkboxRuntime,
|
||||
mode: config.mode,
|
||||
sourcemap: config.sourcemap,
|
||||
swDest: relativeToOutputPath(compilation, config.swDest),
|
||||
swDest: relativeToOutputPath(compilation, config.swDest!),
|
||||
unbundledCode,
|
||||
});
|
||||
|
||||
for (const file of files) {
|
||||
compilation.emitAsset(file.name, new RawSource(file.contents), {
|
||||
// See https://github.com/webpack-contrib/compression-webpack-plugin/issues/218#issuecomment-726196160
|
||||
minimized: config.mode === 'production',
|
||||
});
|
||||
compilation.emitAsset(
|
||||
file.name,
|
||||
new RawSource(Buffer.from(file.contents)),
|
||||
{
|
||||
// See https://github.com/webpack-contrib/compression-webpack-plugin/issues/218#issuecomment-726196160
|
||||
minimized: config.mode === 'production',
|
||||
},
|
||||
);
|
||||
_generatedAssetNames.add(file.name);
|
||||
}
|
||||
|
||||
if (compilation.getLogger) {
|
||||
const logger = compilation.getLogger(this.constructor.name);
|
||||
logger.info(`The service worker at ${config.swDest} will precache
|
||||
logger.info(`The service worker at ${config.swDest ?? ''} will precache
|
||||
${config.manifestEntries.length} URLs, totaling ${prettyBytes(size)}.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = GenerateSW;
|
||||
export {GenerateSW};
|
||||
+3
-3
@@ -6,14 +6,14 @@
|
||||
https://opensource.org/licenses/MIT.
|
||||
*/
|
||||
|
||||
const GenerateSW = require('./generate-sw');
|
||||
const InjectManifest = require('./inject-manifest');
|
||||
import {GenerateSW} from './generate-sw';
|
||||
import {InjectManifest} from './inject-manifest';
|
||||
|
||||
/**
|
||||
* @module workbox-webpack-plugin
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
export {
|
||||
GenerateSW,
|
||||
InjectManifest,
|
||||
};
|
||||
+148
-88
@@ -6,24 +6,21 @@
|
||||
https://opensource.org/licenses/MIT.
|
||||
*/
|
||||
|
||||
const {escapeRegExp} = require('workbox-build/build/lib/escape-regexp');
|
||||
const {replaceAndUpdateSourceMap} =
|
||||
require('workbox-build/build/lib/replace-and-update-source-map');
|
||||
const {validateWebpackInjectManifestOptions} =
|
||||
require('workbox-build/build/lib/validate-options');
|
||||
const prettyBytes = require('pretty-bytes');
|
||||
const stringify = require('fast-json-stable-stringify');
|
||||
const upath = require('upath');
|
||||
const webpack = require('webpack');
|
||||
|
||||
const getManifestEntriesFromCompilation =
|
||||
require('./lib/get-manifest-entries-from-compilation');
|
||||
const getSourcemapAssetName = require('./lib/get-sourcemap-asset-name');
|
||||
const relativeToOutputPath = require('./lib/relative-to-output-path');
|
||||
import {escapeRegExp} from 'workbox-build/build/lib/escape-regexp';
|
||||
import {replaceAndUpdateSourceMap} from 'workbox-build/build/lib/replace-and-update-source-map';
|
||||
import {validateWebpackInjectManifestOptions} from 'workbox-build/build/lib/validate-options';
|
||||
import prettyBytes from 'pretty-bytes';
|
||||
import stringify from 'fast-json-stable-stringify';
|
||||
import upath from 'upath';
|
||||
import webpack from 'webpack';
|
||||
|
||||
import {getManifestEntriesFromCompilation} from './lib/get-manifest-entries-from-compilation';
|
||||
import {getSourcemapAssetName} from './lib/get-sourcemap-asset-name';
|
||||
import {relativeToOutputPath} from './lib/relative-to-output-path';
|
||||
import {WebpackInjectManifestOptions} from 'workbox-build';
|
||||
// Used to keep track of swDest files written by *any* instance of this plugin.
|
||||
// See https://github.com/GoogleChrome/workbox/issues/2181
|
||||
const _generatedAssetNames = new Set();
|
||||
const _generatedAssetNames = new Set<string>();
|
||||
|
||||
// SingleEntryPlugin in v4 was renamed to EntryPlugin in v5.
|
||||
const SingleEntryPlugin = webpack.EntryPlugin || webpack.SingleEntryPlugin;
|
||||
@@ -44,6 +41,8 @@ const {RawSource} = webpack.sources || require('webpack-sources');
|
||||
* @memberof module:workbox-webpack-plugin
|
||||
*/
|
||||
class InjectManifest {
|
||||
private config: WebpackInjectManifestOptions;
|
||||
private alreadyCalled: boolean;
|
||||
// eslint-disable-next-line jsdoc/newline-after-description
|
||||
/**
|
||||
* Creates an instance of InjectManifest.
|
||||
@@ -121,7 +120,7 @@ class InjectManifest {
|
||||
* @param {Array<Object>} [config.webpackCompilationPlugins] Optional `webpack`
|
||||
* plugins that will be used when compiling the `swSrc` input file.
|
||||
*/
|
||||
constructor(config = {}) {
|
||||
constructor(config: WebpackInjectManifestOptions) {
|
||||
this.config = config;
|
||||
this.alreadyCalled = false;
|
||||
}
|
||||
@@ -131,14 +130,17 @@ class InjectManifest {
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
propagateWebpackConfig(compiler) {
|
||||
propagateWebpackConfig(compiler: webpack.Compiler): void {
|
||||
// Because this.config is listed last, properties that are already set
|
||||
// there take precedence over derived properties from the compiler.
|
||||
this.config = Object.assign({
|
||||
mode: compiler.mode,
|
||||
// Use swSrc with a hardcoded .js extension, in case swSrc is a .ts file.
|
||||
swDest: upath.parse(this.config.swSrc).name + '.js',
|
||||
}, this.config);
|
||||
this.config = Object.assign(
|
||||
{
|
||||
mode: compiler.options.mode,
|
||||
// Use swSrc with a hardcoded .js extension, in case swSrc is a .ts file.
|
||||
swDest: upath.parse(this.config.swSrc).name + '.js',
|
||||
},
|
||||
this.config,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -146,38 +148,47 @@ class InjectManifest {
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
apply(compiler) {
|
||||
apply(compiler: webpack.Compiler): void {
|
||||
this.propagateWebpackConfig(compiler);
|
||||
|
||||
compiler.hooks.make.tapPromise(
|
||||
this.constructor.name,
|
||||
(compilation) => this.handleMake(compilation, compiler).catch(
|
||||
(error) => compilation.errors.push(error)),
|
||||
compiler.hooks.make.tapPromise(this.constructor.name, (compilation) =>
|
||||
this.handleMake(compilation, compiler).catch(
|
||||
(error: webpack.WebpackError) => {
|
||||
compilation.errors.push(error);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// webpack v4/v5 compatibility:
|
||||
// https://github.com/webpack/webpack/issues/11425#issuecomment-690387207
|
||||
if (webpack.version.startsWith('4.')) {
|
||||
compiler.hooks.emit.tapPromise(
|
||||
this.constructor.name,
|
||||
(compilation) => this.addAssets(compilation).catch(
|
||||
(error) => compilation.errors.push(error)),
|
||||
if (webpack.version?.startsWith('4.')) {
|
||||
compiler.hooks.emit.tapPromise(this.constructor.name, (compilation) =>
|
||||
this.addAssets(compilation).catch((error: webpack.WebpackError) => {
|
||||
compilation.errors.push(error);
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
const {PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER} = webpack.Compilation;
|
||||
// Specifically hook into thisCompilation, as per
|
||||
// https://github.com/webpack/webpack/issues/11425#issuecomment-690547848
|
||||
compiler.hooks.thisCompilation.tap(
|
||||
this.constructor.name, (compilation) => {
|
||||
compilation.hooks.processAssets.tapPromise({
|
||||
this.constructor.name,
|
||||
(compilation) => {
|
||||
compilation.hooks.processAssets.tapPromise(
|
||||
{
|
||||
name: this.constructor.name,
|
||||
// TODO(jeffposnick): This may need to change eventually.
|
||||
// See https://github.com/webpack/webpack/issues/11822#issuecomment-726184972
|
||||
stage: PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER - 10,
|
||||
}, () => this.addAssets(compilation).catch(
|
||||
(error) => compilation.errors.push(error)),
|
||||
);
|
||||
},
|
||||
},
|
||||
() =>
|
||||
this.addAssets(compilation).catch(
|
||||
(error: webpack.WebpackError) => {
|
||||
compilation.errors.push(error);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -188,15 +199,19 @@ class InjectManifest {
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
async performChildCompilation(compilation, parentCompiler) {
|
||||
async performChildCompilation(
|
||||
compilation: webpack.Compilation,
|
||||
parentCompiler: webpack.Compiler,
|
||||
): Promise<void> {
|
||||
const outputOptions = {
|
||||
path: parentCompiler.options.output.path,
|
||||
filename: this.config.swDest,
|
||||
};
|
||||
|
||||
const childCompiler = compilation.createChildCompiler(
|
||||
this.constructor.name,
|
||||
outputOptions,
|
||||
this.constructor.name,
|
||||
outputOptions,
|
||||
[],
|
||||
);
|
||||
|
||||
childCompiler.context = parentCompiler.context;
|
||||
@@ -205,25 +220,30 @@ class InjectManifest {
|
||||
|
||||
if (Array.isArray(this.config.webpackCompilationPlugins)) {
|
||||
for (const plugin of this.config.webpackCompilationPlugins) {
|
||||
// plugin has a generic type, eslint complains for an unsafe
|
||||
// assign and unsafe use
|
||||
// eslint-disable-next-line
|
||||
plugin.apply(childCompiler);
|
||||
}
|
||||
}
|
||||
|
||||
new SingleEntryPlugin(
|
||||
parentCompiler.context,
|
||||
this.config.swSrc,
|
||||
this.constructor.name,
|
||||
parentCompiler.context,
|
||||
this.config.swSrc,
|
||||
this.constructor.name,
|
||||
).apply(childCompiler);
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
childCompiler.runAsChild((error, entries, childCompilation) => {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
childCompiler.runAsChild((error, _entries, childCompilation) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
compilation.warnings = compilation.warnings.concat(
|
||||
childCompilation.warnings);
|
||||
childCompilation?.warnings ?? [],
|
||||
);
|
||||
compilation.errors = compilation.errors.concat(
|
||||
childCompilation.errors);
|
||||
childCompilation?.errors ?? [],
|
||||
);
|
||||
|
||||
resolve();
|
||||
}
|
||||
@@ -237,10 +257,15 @@ class InjectManifest {
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
addSrcToAssets(compilation, parentCompiler) {
|
||||
const source = parentCompiler.inputFileSystem.readFileSync(
|
||||
this.config.swSrc).toString();
|
||||
compilation.emitAsset(this.config.swDest, new RawSource(source));
|
||||
addSrcToAssets(
|
||||
compilation: webpack.Compilation,
|
||||
parentCompiler: webpack.Compiler,
|
||||
): void {
|
||||
// eslint-disable-next-line
|
||||
const source = (parentCompiler.inputFileSystem as any).readFileSync(
|
||||
this.config.swSrc,
|
||||
);
|
||||
compilation.emitAsset(this.config.swDest!, new RawSource(source));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -249,15 +274,22 @@ class InjectManifest {
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
async handleMake(compilation, parentCompiler) {
|
||||
async handleMake(
|
||||
compilation: webpack.Compilation,
|
||||
parentCompiler: webpack.Compiler,
|
||||
): Promise<void> {
|
||||
try {
|
||||
this.config = validateWebpackInjectManifestOptions(this.config);
|
||||
} catch (error) {
|
||||
throw new Error(`Please check your ${this.constructor.name} plugin ` +
|
||||
`configuration:\n${error.message}`);
|
||||
if (error instanceof Error) {
|
||||
throw new Error(
|
||||
`Please check your ${this.constructor.name} plugin ` +
|
||||
`configuration:\n${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
this.config.swDest = relativeToOutputPath(compilation, this.config.swDest);
|
||||
this.config.swDest = relativeToOutputPath(compilation, this.config.swDest!);
|
||||
_generatedAssetNames.add(this.config.swDest);
|
||||
|
||||
if (this.config.compileSrc) {
|
||||
@@ -266,10 +298,16 @@ class InjectManifest {
|
||||
this.addSrcToAssets(compilation, parentCompiler);
|
||||
// This used to be a fatal error, but just warn at runtime because we
|
||||
// can't validate it easily.
|
||||
if (Array.isArray(this.config.webpackCompilationPlugins) &&
|
||||
this.config.webpackCompilationPlugins.length > 0) {
|
||||
compilation.warnings.push(new Error('compileSrc is false, so the ' +
|
||||
'webpackCompilationPlugins option will be ignored.'));
|
||||
if (
|
||||
Array.isArray(this.config.webpackCompilationPlugins) &&
|
||||
this.config.webpackCompilationPlugins.length > 0
|
||||
) {
|
||||
compilation.warnings.push(
|
||||
new Error(
|
||||
'compileSrc is false, so the ' +
|
||||
'webpackCompilationPlugins option will be ignored.',
|
||||
) as webpack.WebpackError,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -279,18 +317,25 @@ class InjectManifest {
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
async addAssets(compilation) {
|
||||
async addAssets(compilation: webpack.Compilation): Promise<void> {
|
||||
// See https://github.com/GoogleChrome/workbox/issues/1790
|
||||
if (this.alreadyCalled) {
|
||||
const warningMessage = `${this.constructor.name} has been called ` +
|
||||
const warningMessage =
|
||||
`${this.constructor.name} has been called ` +
|
||||
`multiple times, perhaps due to running webpack in --watch mode. The ` +
|
||||
`precache manifest generated after the first call may be inaccurate! ` +
|
||||
`Please see https://github.com/GoogleChrome/workbox/issues/1790 for ` +
|
||||
`more information.`;
|
||||
|
||||
if (!compilation.warnings.some((warning) => warning instanceof Error &&
|
||||
warning.message === warningMessage)) {
|
||||
compilation.warnings.push(new Error(warningMessage));
|
||||
if (
|
||||
!compilation.warnings.some(
|
||||
(warning) =>
|
||||
warning instanceof Error && warning.message === warningMessage,
|
||||
)
|
||||
) {
|
||||
compilation.warnings.push(
|
||||
new Error(warningMessage) as webpack.WebpackError,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
this.alreadyCalled = true;
|
||||
@@ -300,72 +345,87 @@ class InjectManifest {
|
||||
|
||||
// Ensure that we don't precache any of the assets generated by *any*
|
||||
// instance of this plugin.
|
||||
config.exclude.push(({asset}) => _generatedAssetNames.has(asset.name));
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
config.exclude!.push(({asset}) => _generatedAssetNames.has(asset.name));
|
||||
|
||||
// See https://webpack.js.org/contribute/plugin-patterns/#monitoring-the-watch-graph
|
||||
const absoluteSwSrc = upath.resolve(this.config.swSrc);
|
||||
compilation.fileDependencies.add(absoluteSwSrc);
|
||||
|
||||
const swAsset = compilation.getAsset(config.swDest);
|
||||
const swAssetString = swAsset.source.source();
|
||||
const swAsset = compilation.getAsset(config.swDest!);
|
||||
const swAssetString = swAsset!.source.source().toString();
|
||||
|
||||
const globalRegexp = new RegExp(escapeRegExp(config.injectionPoint), 'g');
|
||||
const globalRegexp = new RegExp(escapeRegExp(config.injectionPoint!), 'g');
|
||||
const injectionResults = swAssetString.match(globalRegexp);
|
||||
|
||||
if (!injectionResults) {
|
||||
throw new Error(`Can't find ${config.injectionPoint} in your SW source.`);
|
||||
throw new Error(
|
||||
`Can't find ${config.injectionPoint ?? ''} in your SW source.`,
|
||||
);
|
||||
}
|
||||
if (injectionResults.length !== 1) {
|
||||
throw new Error(`Multiple instances of ${config.injectionPoint} were ` +
|
||||
throw new Error(
|
||||
`Multiple instances of ${config.injectionPoint ?? ''} were ` +
|
||||
`found in your SW source. Include it only once. For more info, see ` +
|
||||
`https://github.com/GoogleChrome/workbox/issues/2681`);
|
||||
`https://github.com/GoogleChrome/workbox/issues/2681`,
|
||||
);
|
||||
}
|
||||
|
||||
const {size, sortedEntries} = await getManifestEntriesFromCompilation(
|
||||
compilation, config);
|
||||
compilation,
|
||||
config,
|
||||
);
|
||||
|
||||
let manifestString = stringify(sortedEntries);
|
||||
if (this.config.compileSrc &&
|
||||
if (
|
||||
this.config.compileSrc &&
|
||||
// See https://github.com/GoogleChrome/workbox/issues/2729
|
||||
// (TODO: Switch to ?. once our linter supports it.)
|
||||
!(compilation.options &&
|
||||
compilation.options.devtool === 'eval-cheap-source-map' &&
|
||||
compilation.options.optimization &&
|
||||
compilation.options.optimization.minimize)
|
||||
!(
|
||||
compilation.options?.devtool === 'eval-cheap-source-map' &&
|
||||
compilation.options.optimization?.minimize
|
||||
)
|
||||
) {
|
||||
// See https://github.com/GoogleChrome/workbox/issues/2263
|
||||
manifestString = manifestString.replace(/"/g, `'`);
|
||||
}
|
||||
|
||||
const sourcemapAssetName = getSourcemapAssetName(
|
||||
compilation, swAssetString, config.swDest);
|
||||
compilation,
|
||||
swAssetString,
|
||||
config.swDest!,
|
||||
);
|
||||
|
||||
if (sourcemapAssetName) {
|
||||
_generatedAssetNames.add(sourcemapAssetName);
|
||||
const sourcemapAsset = compilation.getAsset(sourcemapAssetName);
|
||||
const {source, map} = await replaceAndUpdateSourceMap({
|
||||
jsFilename: config.swDest,
|
||||
originalMap: JSON.parse(sourcemapAsset.source.source()),
|
||||
jsFilename: config.swDest!,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
originalMap: JSON.parse(sourcemapAsset!.source.source().toString()),
|
||||
originalSource: swAssetString,
|
||||
replaceString: manifestString,
|
||||
searchString: config.injectionPoint,
|
||||
searchString: config.injectionPoint!,
|
||||
});
|
||||
|
||||
compilation.updateAsset(sourcemapAssetName, new RawSource(map));
|
||||
compilation.updateAsset(config.swDest, new RawSource(source));
|
||||
compilation.updateAsset(config.swDest!, new RawSource(source));
|
||||
} else {
|
||||
// If there's no sourcemap associated with swDest, a simple string
|
||||
// replacement will suffice.
|
||||
compilation.updateAsset(config.swDest, new RawSource(
|
||||
swAssetString.replace(config.injectionPoint, manifestString)));
|
||||
compilation.updateAsset(
|
||||
config.swDest!,
|
||||
new RawSource(
|
||||
swAssetString.replace(config.injectionPoint!, manifestString),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (compilation.getLogger) {
|
||||
const logger = compilation.getLogger(this.constructor.name);
|
||||
logger.info(`The service worker at ${config.swDest} will precache
|
||||
logger.info(`The service worker at ${config.swDest ?? ''} will precache
|
||||
${sortedEntries.length} URLs, totaling ${prettyBytes(size)}.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InjectManifest;
|
||||
export {InjectManifest};
|
||||
+5
-4
@@ -6,15 +6,16 @@
|
||||
https://opensource.org/licenses/MIT.
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
import crypto from 'crypto';
|
||||
import type {Asset} from 'webpack';
|
||||
|
||||
/**
|
||||
* @param {WebpackAsset} asset
|
||||
* @param {Asset} asset
|
||||
* @return {string} The MD5 hash of the asset's source.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
module.exports = (asset) => {
|
||||
export function getAssetHash(asset: Asset): string | null {
|
||||
// If webpack has the asset marked as immutable, then we don't need to
|
||||
// use an out-of-band revision for it.
|
||||
// See https://github.com/webpack/webpack/issues/9038
|
||||
@@ -25,4 +26,4 @@ module.exports = (asset) => {
|
||||
return crypto.createHash('md5')
|
||||
.update(Buffer.from(asset.source.source()))
|
||||
.digest('hex');
|
||||
};
|
||||
}
|
||||
+74
-36
@@ -6,12 +6,23 @@
|
||||
https://opensource.org/licenses/MIT.
|
||||
*/
|
||||
|
||||
const {matchPart} = require('webpack').ModuleFilenameHelpers;
|
||||
const {transformManifest} =
|
||||
require('workbox-build/build/lib/transform-manifest');
|
||||
import {
|
||||
Asset,
|
||||
Chunk,
|
||||
Compilation,
|
||||
ModuleFilenameHelpers,
|
||||
WebpackError,
|
||||
} from 'webpack';
|
||||
import {transformManifest} from 'workbox-build/build/lib/transform-manifest';
|
||||
|
||||
const getAssetHash = require('./get-asset-hash');
|
||||
const resolveWebpackURL = require('./resolve-webpack-url');
|
||||
import {
|
||||
WebpackGenerateSWOptions,
|
||||
WebpackInjectManifestOptions,
|
||||
ManifestEntry,
|
||||
FileDetails,
|
||||
} from 'workbox-build';
|
||||
import {getAssetHash} from './get-asset-hash';
|
||||
import {resolveWebpackURL} from './resolve-webpack-url';
|
||||
|
||||
/**
|
||||
* For a given asset, checks whether at least one of the conditions matches.
|
||||
@@ -24,14 +35,21 @@ const resolveWebpackURL = require('./resolve-webpack-url');
|
||||
* @return {boolean} Whether or not at least one condition matches.
|
||||
* @private
|
||||
*/
|
||||
function checkConditions(asset, compilation, conditions = []) {
|
||||
function checkConditions(
|
||||
asset: Asset,
|
||||
compilation: Compilation,
|
||||
|
||||
conditions: Array<
|
||||
//eslint-disable-next-line @typescript-eslint/ban-types
|
||||
string | RegExp | ((arg0: any) => boolean)
|
||||
> = [],
|
||||
): boolean {
|
||||
for (const condition of conditions) {
|
||||
if (typeof condition === 'function') {
|
||||
if (condition({asset, compilation})) {
|
||||
return true;
|
||||
}
|
||||
return condition({asset, compilation});
|
||||
//return compilation !== null;
|
||||
} else {
|
||||
if (matchPart(asset.name, condition)) {
|
||||
if (ModuleFilenameHelpers.matchPart(asset.name, condition)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -49,12 +67,16 @@ function checkConditions(asset, compilation, conditions = []) {
|
||||
*
|
||||
* @param {Compilation} compilation
|
||||
* @param {string} chunkOrGroup
|
||||
* @return {Array<Asset>|null}
|
||||
* @return {Array<string>|null}
|
||||
* @private
|
||||
*/
|
||||
function getNamesOfAssetsInChunkOrGroup(compilation, chunkOrGroup) {
|
||||
const chunkGroup = compilation.namedChunkGroups &&
|
||||
compilation.namedChunkGroups.get(chunkOrGroup);
|
||||
function getNamesOfAssetsInChunkOrGroup(
|
||||
compilation: Compilation,
|
||||
chunkOrGroup: string,
|
||||
): Array<string> | null {
|
||||
const chunkGroup =
|
||||
compilation.namedChunkGroups &&
|
||||
compilation.namedChunkGroups.get(chunkOrGroup);
|
||||
if (chunkGroup) {
|
||||
const assetNames = [];
|
||||
for (const chunk of chunkGroup.chunks) {
|
||||
@@ -62,8 +84,8 @@ function getNamesOfAssetsInChunkOrGroup(compilation, chunkOrGroup) {
|
||||
}
|
||||
return assetNames;
|
||||
} else {
|
||||
const chunk = compilation.namedChunks &&
|
||||
compilation.namedChunks.get(chunkOrGroup);
|
||||
const chunk =
|
||||
compilation.namedChunks && compilation.namedChunks.get(chunkOrGroup);
|
||||
if (chunk) {
|
||||
return getNamesOfAssetsInChunk(chunk);
|
||||
}
|
||||
@@ -77,11 +99,11 @@ function getNamesOfAssetsInChunkOrGroup(compilation, chunkOrGroup) {
|
||||
* Returns the names of all the assets in a chunk.
|
||||
*
|
||||
* @param {Chunk} chunk
|
||||
* @return {Array<Asset>}
|
||||
* @return {Array<string>}
|
||||
* @private
|
||||
*/
|
||||
function getNamesOfAssetsInChunk(chunk) {
|
||||
const assetNames = [];
|
||||
function getNamesOfAssetsInChunk(chunk: Chunk): Array<string> {
|
||||
const assetNames: Array<string> = [];
|
||||
|
||||
assetNames.push(...chunk.files);
|
||||
|
||||
@@ -104,25 +126,34 @@ function getNamesOfAssetsInChunk(chunk) {
|
||||
* based on the criteria provided.
|
||||
* @private
|
||||
*/
|
||||
function filterAssets(compilation, config) {
|
||||
const filteredAssets = new Set();
|
||||
function filterAssets(
|
||||
compilation: Compilation,
|
||||
config: WebpackInjectManifestOptions | WebpackGenerateSWOptions,
|
||||
): Set<Asset> {
|
||||
const filteredAssets = new Set<Asset>();
|
||||
const assets = compilation.getAssets();
|
||||
|
||||
const allowedAssetNames = new Set();
|
||||
const allowedAssetNames = new Set<string>();
|
||||
// See https://github.com/GoogleChrome/workbox/issues/1287
|
||||
if (Array.isArray(config.chunks)) {
|
||||
for (const name of config.chunks) {
|
||||
// See https://github.com/GoogleChrome/workbox/issues/2717
|
||||
const assetsInChunkOrGroup = getNamesOfAssetsInChunkOrGroup(
|
||||
compilation, name);
|
||||
compilation,
|
||||
name,
|
||||
);
|
||||
if (assetsInChunkOrGroup) {
|
||||
for (const assetName of assetsInChunkOrGroup) {
|
||||
allowedAssetNames.add(assetName);
|
||||
}
|
||||
} else {
|
||||
compilation.warnings.push(new Error(`The chunk '${name}' was ` +
|
||||
`provided in your Workbox chunks config, but was not found in the ` +
|
||||
`compilation.`));
|
||||
compilation.warnings.push(
|
||||
new Error(
|
||||
`The chunk '${name}' was ` +
|
||||
`provided in your Workbox chunks config, but was not found in the ` +
|
||||
`compilation.`,
|
||||
) as WebpackError,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,7 +163,9 @@ function filterAssets(compilation, config) {
|
||||
for (const name of config.excludeChunks) {
|
||||
// See https://github.com/GoogleChrome/workbox/issues/2717
|
||||
const assetsInChunkOrGroup = getNamesOfAssetsInChunkOrGroup(
|
||||
compilation, name);
|
||||
compilation,
|
||||
name,
|
||||
);
|
||||
if (assetsInChunkOrGroup) {
|
||||
for (const assetName of assetsInChunkOrGroup) {
|
||||
deniedAssetNames.add(assetName);
|
||||
@@ -165,8 +198,9 @@ function filterAssets(compilation, config) {
|
||||
}
|
||||
|
||||
// Treat an empty config.includes as an implicit inclusion.
|
||||
const isIncluded = !Array.isArray(config.include) ||
|
||||
checkConditions(asset, compilation, config.include);
|
||||
const isIncluded =
|
||||
!Array.isArray(config.include) ||
|
||||
checkConditions(asset, compilation, config.include);
|
||||
if (!isIncluded) {
|
||||
continue;
|
||||
}
|
||||
@@ -178,17 +212,20 @@ function filterAssets(compilation, config) {
|
||||
return filteredAssets;
|
||||
}
|
||||
|
||||
module.exports = async (compilation, config) => {
|
||||
export async function getManifestEntriesFromCompilation(
|
||||
compilation: Compilation,
|
||||
config: WebpackGenerateSWOptions | WebpackInjectManifestOptions,
|
||||
): Promise<{size: number; sortedEntries: ManifestEntry[]}> {
|
||||
const filteredAssets = filterAssets(compilation, config);
|
||||
|
||||
const {publicPath} = compilation.options.output;
|
||||
|
||||
const fileDetails = Array.from(filteredAssets).map((asset) => {
|
||||
return {
|
||||
file: resolveWebpackURL(publicPath, asset.name),
|
||||
file: resolveWebpackURL(publicPath as string, asset.name),
|
||||
hash: getAssetHash(asset),
|
||||
size: asset.source.size() || 0,
|
||||
};
|
||||
} as FileDetails;
|
||||
});
|
||||
|
||||
const {manifestEntries, size, warnings} = await transformManifest({
|
||||
@@ -203,12 +240,13 @@ module.exports = async (compilation, config) => {
|
||||
|
||||
// See https://github.com/GoogleChrome/workbox/issues/2790
|
||||
for (const warning of warnings) {
|
||||
compilation.warnings.push(new Error(warning));
|
||||
compilation.warnings.push(new Error(warning) as WebpackError);
|
||||
}
|
||||
|
||||
// Ensure that the entries are properly sorted by URL.
|
||||
const sortedEntries = manifestEntries.sort(
|
||||
(a, b) => a.url === b.url ? 0 : (a.url > b.url ? 1 : -1));
|
||||
const sortedEntries = manifestEntries.sort((a, b) =>
|
||||
a.url === b.url ? 0 : a.url > b.url ? 1 : -1,
|
||||
);
|
||||
|
||||
return {size, sortedEntries};
|
||||
};
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
const upath = require('upath');
|
||||
|
||||
const resolveWebpackURL = require('./resolve-webpack-url');
|
||||
|
||||
module.exports = (compilation, chunkNames) => {
|
||||
const {chunks} = compilation.getStats().toJson({chunks: true});
|
||||
const {publicPath} = compilation.options.output;
|
||||
const scriptFiles = new Set();
|
||||
|
||||
for (const chunkName of chunkNames) {
|
||||
const chunk = chunks.find((chunk) => chunk.names.includes(chunkName));
|
||||
if (chunk) {
|
||||
for (const file of chunk.files) {
|
||||
// See https://github.com/GoogleChrome/workbox/issues/2161
|
||||
if (upath.extname(file) === '.js') {
|
||||
scriptFiles.add(resolveWebpackURL(publicPath, file));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
compilation.warnings.push(new Error(`${chunkName} was provided to ` +
|
||||
`importScriptsViaChunks, but didn't match any named chunks.`));
|
||||
}
|
||||
}
|
||||
|
||||
if (scriptFiles.size === 0) {
|
||||
compilation.warnings.push(new Error(`There were no assets matching ` +
|
||||
`importScriptsViaChunks: [${chunkNames}].`));
|
||||
}
|
||||
|
||||
return Array.from(scriptFiles);
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
import upath from 'upath';
|
||||
import {Compilation, WebpackError} from 'webpack';
|
||||
|
||||
import {resolveWebpackURL} from './resolve-webpack-url';
|
||||
|
||||
export function getScriptFilesForChunks(
|
||||
compilation: Compilation,
|
||||
chunkNames: Array<string>,
|
||||
): Array<string> {
|
||||
const {chunks} = compilation.getStats().toJson({chunks: true});
|
||||
const {publicPath} = compilation.options.output;
|
||||
const scriptFiles = new Set<string>();
|
||||
|
||||
for (const chunkName of chunkNames) {
|
||||
const chunk = chunks!.find((chunk) => chunk.names?.includes(chunkName));
|
||||
if (chunk) {
|
||||
for (const file of chunk?.files ?? []) {
|
||||
// See https://github.com/GoogleChrome/workbox/issues/2161
|
||||
if (upath.extname(file) === '.js') {
|
||||
scriptFiles.add(resolveWebpackURL(publicPath as string, file));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
compilation.warnings.push(
|
||||
new Error(
|
||||
`${chunkName} was provided to ` +
|
||||
`importScriptsViaChunks, but didn't match any named chunks.`,
|
||||
) as WebpackError,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (scriptFiles.size === 0) {
|
||||
compilation.warnings.push(
|
||||
new Error(
|
||||
`There were no assets matching ` +
|
||||
`importScriptsViaChunks: [${chunkNames.join(' ')}].`,
|
||||
) as WebpackError,
|
||||
);
|
||||
}
|
||||
|
||||
return Array.from(scriptFiles);
|
||||
}
|
||||
+14
-6
@@ -6,8 +6,9 @@
|
||||
https://opensource.org/licenses/MIT.
|
||||
*/
|
||||
|
||||
const sourceMapURL = require('source-map-url');
|
||||
const upath = require('upath');
|
||||
import sourceMapURL from 'source-map-url';
|
||||
import upath from 'upath';
|
||||
import type {Compilation} from 'webpack';
|
||||
|
||||
/**
|
||||
* If our bundled swDest file contains a sourcemap, we would invalidate that
|
||||
@@ -21,13 +22,18 @@ const upath = require('upath');
|
||||
* @param {string} swContents The contents of the swSrc file, which may or
|
||||
* may not include a valid sourcemap comment.
|
||||
* @param {string} swDest The configured swDest value.
|
||||
* @return {string|undefined} If the swContents contains a valid soucemap
|
||||
* @return {string|undefined} If the swContents contains a valid sourcemap
|
||||
* comment pointing to an asset present in the compilation, this will return the
|
||||
* name of that asset. Otherwise, it will return undefined.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
module.exports = (compilation, swContents, swDest) => {
|
||||
export function getSourcemapAssetName(
|
||||
compilation: Compilation,
|
||||
swContents: string,
|
||||
swDest: string,
|
||||
): string | undefined {
|
||||
// eslint-disable-next-line
|
||||
const url = sourceMapURL.getFrom(swContents);
|
||||
if (url) {
|
||||
// Translate the relative URL to what the presumed name for the webpack
|
||||
@@ -37,11 +43,13 @@ module.exports = (compilation, swContents, swDest) => {
|
||||
// See https://github.com/GoogleChrome/workbox/issues/2250
|
||||
const swAssetDirname = upath.dirname(swDest);
|
||||
const sourcemapURLAssetName = upath.normalize(
|
||||
upath.join(swAssetDirname, url));
|
||||
upath.join(swAssetDirname, url),
|
||||
);
|
||||
|
||||
// Not sure if there's a better way to check for asset existence?
|
||||
if (compilation.getAsset(sourcemapURLAssetName)) {
|
||||
return sourcemapURLAssetName;
|
||||
}
|
||||
}
|
||||
};
|
||||
return undefined;
|
||||
}
|
||||
+5
-4
@@ -6,7 +6,8 @@
|
||||
https://opensource.org/licenses/MIT.
|
||||
*/
|
||||
|
||||
const upath = require('upath');
|
||||
import upath from 'upath';
|
||||
import type {Compilation} from 'webpack';
|
||||
|
||||
/**
|
||||
* @param {Object} compilation The webpack compilation.
|
||||
@@ -17,12 +18,12 @@ const upath = require('upath');
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
module.exports = (compilation, swDest) => {
|
||||
export function relativeToOutputPath(compilation: Compilation, swDest: string): string {
|
||||
// See https://github.com/jantimon/html-webpack-plugin/pull/266/files#diff-168726dbe96b3ce427e7fedce31bb0bcR38
|
||||
if (upath.resolve(swDest) === upath.normalize(swDest)) {
|
||||
return upath.relative(compilation.options.output.path, swDest);
|
||||
return upath.relative(compilation.options.output.path!, swDest);
|
||||
}
|
||||
|
||||
// Otherwise, return swDest as-is.
|
||||
return swDest;
|
||||
};
|
||||
}
|
||||
+2
-2
@@ -19,7 +19,7 @@
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
module.exports = (publicPath, ...paths) => {
|
||||
export function resolveWebpackURL(publicPath: string, ...paths: Array<string>): string {
|
||||
// This is a change in webpack v5.
|
||||
// See https://github.com/jantimon/html-webpack-plugin/pull/1516
|
||||
if (publicPath === 'auto') {
|
||||
@@ -27,4 +27,4 @@ module.exports = (publicPath, ...paths) => {
|
||||
} else {
|
||||
return [publicPath, ...paths].join('');
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
declare module 'source-map-url';
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"extends": "../../tsconfig",
|
||||
"compilerOptions": {
|
||||
"esModuleInterop": true,
|
||||
"module": "CommonJS",
|
||||
"outDir": "./build",
|
||||
"resolveJsonModule": true,
|
||||
"rootDir": "./src",
|
||||
"target": "ES2018",
|
||||
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"references": [{"path": "../workbox-build/"}]
|
||||
}
|
||||
@@ -21,23 +21,23 @@ function createFetchEvent(url, requestInit) {
|
||||
return event;
|
||||
}
|
||||
|
||||
describe(`PrecacheStrategy()`, function () {
|
||||
describe(`PrecacheStrategy()`, function() {
|
||||
const sandbox = sinon.createSandbox();
|
||||
|
||||
beforeEach(async function () {
|
||||
beforeEach(async function() {
|
||||
const keys = await caches.keys();
|
||||
await Promise.all(keys.map((key) => caches.delete(key)));
|
||||
sandbox.restore();
|
||||
});
|
||||
|
||||
after(async function () {
|
||||
after(async function() {
|
||||
const keys = await caches.keys();
|
||||
await Promise.all(keys.map((key) => caches.delete(key)));
|
||||
sandbox.restore();
|
||||
});
|
||||
|
||||
describe(`handle()`, function () {
|
||||
it(`falls back to network by default on fetch`, async function () {
|
||||
describe(`handle()`, function() {
|
||||
it(`falls back to network by default on fetch`, async function() {
|
||||
sandbox.stub(self, 'fetch').callsFake((request) => {
|
||||
const response = new Response('Fetched Response');
|
||||
sandbox.replaceGetter(response, 'url', () => request.url);
|
||||
@@ -62,7 +62,7 @@ describe(`PrecacheStrategy()`, function () {
|
||||
expect(cachedUrls).to.eql([`${location.origin}/one`]);
|
||||
});
|
||||
|
||||
it(`falls back to network by default on fetch, and populates the cache if integrity is used`, async function () {
|
||||
it(`falls back to network by default on fetch, and populates the cache if integrity is used`, async function() {
|
||||
sandbox.stub(self, 'fetch').callsFake((request) => {
|
||||
const response = new Response('Fetched Response');
|
||||
sandbox.replaceGetter(response, 'url', () => request.url);
|
||||
@@ -123,7 +123,7 @@ describe(`PrecacheStrategy()`, function () {
|
||||
]);
|
||||
});
|
||||
|
||||
it(`just checks cache if fallbackToNetwork is false`, async function () {
|
||||
it(`just checks cache if fallbackToNetwork is false`, async function() {
|
||||
sandbox.stub(self, 'fetch').callsFake((request) => {
|
||||
const response = new Response('Fetched Response');
|
||||
sandbox.replaceGetter(response, 'url', () => request.url);
|
||||
@@ -145,7 +145,7 @@ describe(`PrecacheStrategy()`, function () {
|
||||
);
|
||||
});
|
||||
|
||||
it(`copies redirected responses`, async function () {
|
||||
it(`copies redirected responses`, async function() {
|
||||
sandbox.stub(self, 'fetch').callsFake((request) => {
|
||||
const response = new Response('Redirected Response');
|
||||
sandbox.replaceGetter(response, 'redirected', () => true);
|
||||
@@ -171,7 +171,7 @@ describe(`PrecacheStrategy()`, function () {
|
||||
expect(await cachedResponse.text()).to.equal('Redirected Response');
|
||||
});
|
||||
|
||||
it(`errors during install if the default plugin returns null`, async function () {
|
||||
it(`errors during install if the default plugin returns null`, async function() {
|
||||
// Also ensure that we don't cache the bad response;
|
||||
// see https://github.com/GoogleChrome/workbox/issues/2737
|
||||
const putStub = sandbox.stub().resolves();
|
||||
@@ -204,7 +204,7 @@ describe(`PrecacheStrategy()`, function () {
|
||||
expect(defaultPluginSpy.callCount).to.eql(1);
|
||||
});
|
||||
|
||||
it(`doesn't error during install if the cacheWillUpdate plugin allows it`, async function () {
|
||||
it(`doesn't error during install if the cacheWillUpdate plugin allows it`, async function() {
|
||||
const errorResponse = new Response('Server Error', {
|
||||
status: 400,
|
||||
});
|
||||
@@ -245,7 +245,7 @@ describe(`PrecacheStrategy()`, function () {
|
||||
expect(defaultPluginSpy.callCount).to.eql(0);
|
||||
});
|
||||
|
||||
it(`errors during install if any of the cacheWillUpdate plugins return null`, async function () {
|
||||
it(`errors during install if any of the cacheWillUpdate plugins return null`, async function() {
|
||||
const errorResponse = new Response('Server Error', {
|
||||
status: 400,
|
||||
});
|
||||
@@ -292,8 +292,8 @@ describe(`PrecacheStrategy()`, function () {
|
||||
});
|
||||
});
|
||||
|
||||
describe('_useDefaultCacheabilityPluginIfNeeded()', function () {
|
||||
it(`should include the expected plugins by default`, async function () {
|
||||
describe('_useDefaultCacheabilityPluginIfNeeded()', function() {
|
||||
it(`should include the expected plugins by default`, async function() {
|
||||
const ps = new PrecacheStrategy();
|
||||
|
||||
ps._useDefaultCacheabilityPluginIfNeeded();
|
||||
@@ -313,7 +313,7 @@ describe(`PrecacheStrategy()`, function () {
|
||||
]);
|
||||
});
|
||||
|
||||
it(`should include the default plugin when the strategy has only non-cacheWillUpdate plugins`, async function () {
|
||||
it(`should include the default plugin when the strategy has only non-cacheWillUpdate plugins`, async function() {
|
||||
const cacheKeyWillBeUsedPlugin = {
|
||||
cacheKeyWillBeUsed: sandbox.stub(),
|
||||
};
|
||||
@@ -340,7 +340,7 @@ describe(`PrecacheStrategy()`, function () {
|
||||
]);
|
||||
});
|
||||
|
||||
it(`should not include the default plugin when the strategy has one cacheWillUpdate plugin`, async function () {
|
||||
it(`should not include the default plugin when the strategy has one cacheWillUpdate plugin`, async function() {
|
||||
const cacheWillUpdatePlugin = {
|
||||
cacheWillUpdate: sandbox.stub(),
|
||||
};
|
||||
@@ -365,7 +365,7 @@ describe(`PrecacheStrategy()`, function () {
|
||||
]);
|
||||
});
|
||||
|
||||
it(`should not include the default plugin when the strategy has multiple cacheWillUpdate plugins`, async function () {
|
||||
it(`should not include the default plugin when the strategy has multiple cacheWillUpdate plugins`, async function() {
|
||||
const cacheWillUpdatePlugin1 = {
|
||||
cacheWillUpdate: sandbox.stub(),
|
||||
};
|
||||
@@ -404,7 +404,7 @@ describe(`PrecacheStrategy()`, function () {
|
||||
]);
|
||||
});
|
||||
|
||||
it(`should remove the default plugin if a cacheWillUpdate plugin has been added after the initial call`, async function () {
|
||||
it(`should remove the default plugin if a cacheWillUpdate plugin has been added after the initial call`, async function() {
|
||||
const cacheWillUpdatePlugin = {
|
||||
cacheWillUpdate: sandbox.stub(),
|
||||
};
|
||||
@@ -430,8 +430,8 @@ describe(`PrecacheStrategy()`, function () {
|
||||
});
|
||||
});
|
||||
|
||||
describe('defaultPrecacheCacheabilityPlugin', function () {
|
||||
it(`should return the same response when the status is 200`, async function () {
|
||||
describe('defaultPrecacheCacheabilityPlugin', function() {
|
||||
it(`should return the same response when the status is 200`, async function() {
|
||||
const response = new Response('', {status: 200});
|
||||
|
||||
const returnedResponse =
|
||||
@@ -444,7 +444,7 @@ describe(`PrecacheStrategy()`, function () {
|
||||
expect(returnedResponse).to.eql(response);
|
||||
});
|
||||
|
||||
it(`should return the same response when the status is 0`, async function () {
|
||||
it(`should return the same response when the status is 0`, async function() {
|
||||
// You can't construct opaque responses, so stub out the getter.
|
||||
const response = new Response('', {status: 599});
|
||||
sandbox.stub(response, 'status').get(() => 0);
|
||||
@@ -459,7 +459,7 @@ describe(`PrecacheStrategy()`, function () {
|
||||
expect(returnedResponse).to.eql(response);
|
||||
});
|
||||
|
||||
it(`should return null when the status is 404`, async function () {
|
||||
it(`should return null when the status is 404`, async function() {
|
||||
const response = new Response('', {status: 404});
|
||||
|
||||
const returnedResponse =
|
||||
|
||||
@@ -38,7 +38,7 @@ const validateServiceWorkerRuntime = require('../../../../infra/testing/validato
|
||||
const webpackBuildCheck = require('../../../../infra/testing/webpack-build-check');
|
||||
const {
|
||||
GenerateSW,
|
||||
} = require('../../../../packages/workbox-webpack-plugin/src/index');
|
||||
} = require('../../../../packages/workbox-webpack-plugin/build/generate-sw');
|
||||
|
||||
describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function () {
|
||||
const WEBPACK_ENTRY_FILENAME = 'webpackEntry.js';
|
||||
|
||||
@@ -39,7 +39,7 @@ const validateServiceWorkerRuntime = require('../../../../infra/testing/validato
|
||||
const webpackBuildCheck = require('../../../../infra/testing/webpack-build-check');
|
||||
const {
|
||||
InjectManifest,
|
||||
} = require('../../../../packages/workbox-webpack-plugin/src/index');
|
||||
} = require('../../../../packages/workbox-webpack-plugin/build/inject-manifest');
|
||||
|
||||
chai.use(chaiMatchPattern);
|
||||
const {expect} = chai;
|
||||
|
||||
@@ -37,7 +37,7 @@ const validateServiceWorkerRuntime = require('../../../../infra/testing/validato
|
||||
const webpackBuildCheck = require('../../../../infra/testing/webpack-build-check');
|
||||
const {
|
||||
GenerateSW,
|
||||
} = require('../../../../packages/workbox-webpack-plugin/src/index');
|
||||
} = require('../../../../packages/workbox-webpack-plugin/build/generate-sw');
|
||||
|
||||
describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function () {
|
||||
const WEBPACK_ENTRY_FILENAME = 'webpackEntry.js';
|
||||
|
||||
@@ -38,7 +38,7 @@ const validateServiceWorkerRuntime = require('../../../../infra/testing/validato
|
||||
const webpackBuildCheck = require('../../../../infra/testing/webpack-build-check');
|
||||
const {
|
||||
InjectManifest,
|
||||
} = require('../../../../packages/workbox-webpack-plugin/src/index');
|
||||
} = require('../../../../packages/workbox-webpack-plugin/build/inject-manifest');
|
||||
|
||||
chai.use(chaiMatchPattern);
|
||||
const {expect} = chai;
|
||||
|
||||
@@ -31,6 +31,9 @@
|
||||
{"path": "./packages/workbox-routing/"},
|
||||
{"path": "./packages/workbox-strategies/"},
|
||||
{"path": "./packages/workbox-streams/"},
|
||||
{
|
||||
"path": "./packages/workbox-webpack-plugin/"
|
||||
},
|
||||
{"path": "./packages/workbox-window/"}
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user