webpack/lib/asset/AssetGenerator.js

798 lines
22 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sergey Melyukov @smelukov
*/
"use strict";
const path = require("path");
const { RawSource } = require("webpack-sources");
2022-03-11 21:34:17 +08:00
const ConcatenationScope = require("../ConcatenationScope");
const Generator = require("../Generator");
2024-11-01 04:19:07 +08:00
const {
ASSET_AND_CSS_URL_TYPES,
2025-07-03 17:06:45 +08:00
ASSET_AND_JS_AND_CSS_URL_TYPES,
ASSET_AND_JS_TYPES,
ASSET_TYPES,
CSS_URL_TYPES,
2024-11-01 04:19:07 +08:00
JS_AND_CSS_URL_TYPES,
2025-07-03 17:06:45 +08:00
JS_TYPES,
NO_TYPES
2024-11-01 04:19:07 +08:00
} = require("../ModuleSourceTypesConstants");
const { ASSET_MODULE_TYPE } = require("../ModuleTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
2024-03-16 18:38:58 +08:00
const CssUrlDependency = require("../dependencies/CssUrlDependency");
const createHash = require("../util/createHash");
const { makePathsRelative } = require("../util/identifier");
2025-08-30 03:53:13 +08:00
const memoize = require("../util/memoize");
const nonNumericOnlyHash = require("../util/nonNumericOnlyHash");
2025-08-30 03:53:13 +08:00
const getMimeTypes = memoize(() => require("mime-types"));
/** @typedef {import("webpack-sources").Source} Source */
2024-08-08 02:59:26 +08:00
/** @typedef {import("../../declarations/WebpackOptions").AssetGeneratorDataUrlOptions} AssetGeneratorDataUrlOptions */
/** @typedef {import("../../declarations/WebpackOptions").AssetGeneratorOptions} AssetGeneratorOptions */
2024-08-08 02:59:26 +08:00
/** @typedef {import("../../declarations/WebpackOptions").AssetModuleFilename} AssetModuleFilename */
/** @typedef {import("../../declarations/WebpackOptions").AssetModuleOutputPath} AssetModuleOutputPath */
/** @typedef {import("../../declarations/WebpackOptions").AssetResourceGeneratorOptions} AssetResourceGeneratorOptions */
/** @typedef {import("../../declarations/WebpackOptions").RawPublicPath} RawPublicPath */
/** @typedef {import("../ChunkGraph")} ChunkGraph */
/** @typedef {import("../Compilation").AssetInfo} AssetInfo */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
2025-09-11 08:10:10 +08:00
/** @typedef {import("../Module").NameForCondition} NameForCondition */
2024-08-08 02:59:26 +08:00
/** @typedef {import("../Module").BuildInfo} BuildInfo */
2022-03-11 21:34:17 +08:00
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
2024-11-01 04:19:07 +08:00
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../NormalModule")} NormalModule */
/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("../util/Hash")} Hash */
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
2024-08-08 02:59:26 +08:00
/**
* @template T
* @template U
2025-08-28 18:34:30 +08:00
* @param {null | string | T[] | Set<T> | undefined} a a
* @param {null | string | U[] | Set<U> | undefined} b b
* @returns {T[] & U[]} array
2024-08-08 02:59:26 +08:00
*/
2021-03-22 22:08:06 +08:00
const mergeMaybeArrays = (a, b) => {
const set = new Set();
if (Array.isArray(a)) for (const item of a) set.add(item);
else set.add(a);
if (Array.isArray(b)) for (const item of b) set.add(item);
else set.add(b);
2025-07-03 17:06:45 +08:00
return [...set];
2021-03-22 22:08:06 +08:00
};
2024-08-09 23:42:37 +08:00
/**
2025-04-07 21:09:05 +08:00
* @param {AssetInfo} a a
* @param {AssetInfo} b b
* @returns {AssetInfo} object
2024-08-09 23:42:37 +08:00
*/
const mergeAssetInfo = (a, b) => {
2025-04-07 21:09:05 +08:00
/** @type {AssetInfo} */
const result = { ...a, ...b };
for (const key of Object.keys(a)) {
if (key in b) {
if (a[key] === b[key]) continue;
switch (key) {
case "fullhash":
case "chunkhash":
case "modulehash":
2021-03-22 22:08:06 +08:00
case "contenthash":
result[key] = mergeMaybeArrays(a[key], b[key]);
break;
case "immutable":
case "development":
case "hotModuleReplacement":
2021-12-06 20:15:48 +08:00
case "javascriptModule":
result[key] = a[key] || b[key];
break;
case "related":
2025-04-07 21:09:05 +08:00
result[key] = mergeRelatedInfo(
/** @type {NonNullable<AssetInfo["related"]>} */
(a[key]),
/** @type {NonNullable<AssetInfo["related"]>} */
(b[key])
);
break;
default:
throw new Error(`Can't handle conflicting asset info for ${key}`);
}
}
}
return result;
};
2024-08-09 23:42:37 +08:00
/**
2025-04-07 21:09:05 +08:00
* @param {NonNullable<AssetInfo["related"]>} a a
* @param {NonNullable<AssetInfo["related"]>} b b
* @returns {NonNullable<AssetInfo["related"]>} object
2024-08-09 23:42:37 +08:00
*/
const mergeRelatedInfo = (a, b) => {
const result = { ...a, ...b };
for (const key of Object.keys(a)) {
if (key in b) {
if (a[key] === b[key]) continue;
2021-03-22 22:08:06 +08:00
result[key] = mergeMaybeArrays(a[key], b[key]);
}
}
return result;
};
2024-08-08 02:59:26 +08:00
/**
* @param {"base64" | false} encoding encoding
* @param {Source} source source
* @returns {string} encoded data
*/
2022-01-13 00:23:16 +08:00
const encodeDataUri = (encoding, source) => {
2024-08-08 02:59:26 +08:00
/** @type {string | undefined} */
2022-01-13 00:23:16 +08:00
let encodedContent;
switch (encoding) {
case "base64": {
encodedContent = source.buffer().toString("base64");
break;
}
case false: {
const content = source.source();
if (typeof content !== "string") {
encodedContent = content.toString("utf8");
2022-01-13 00:23:16 +08:00
}
2024-08-08 02:59:26 +08:00
encodedContent = encodeURIComponent(
/** @type {string} */
(encodedContent)
).replace(
2022-01-13 00:23:16 +08:00
/[!'()*]/g,
(character) =>
2024-08-08 02:59:26 +08:00
`%${/** @type {number} */ (character.codePointAt(0)).toString(16)}`
2022-01-13 00:23:16 +08:00
);
break;
}
default:
throw new Error(`Unsupported encoding '${encoding}'`);
}
return encodedContent;
};
/**
2025-05-13 21:03:58 +08:00
* @param {"base64" | false} encoding encoding
* @param {string} content content
* @returns {Buffer} decoded content
*/
2022-01-17 23:52:55 +08:00
const decodeDataUriContent = (encoding, content) => {
const isBase64 = encoding === "base64";
2023-04-13 08:10:12 +08:00
if (isBase64) {
return Buffer.from(content, "base64");
}
// If we can't decode return the original body
try {
return Buffer.from(decodeURIComponent(content), "ascii");
} catch (_) {
return Buffer.from(content, "ascii");
}
2022-01-17 23:52:55 +08:00
};
2021-11-29 20:37:38 +08:00
const DEFAULT_ENCODING = "base64";
2019-11-19 21:32:40 +08:00
class AssetGenerator extends Generator {
2019-11-16 00:27:36 +08:00
/**
* @param {ModuleGraph} moduleGraph the module graph
* @param {AssetGeneratorOptions["dataUrl"]=} dataUrlOptions the options for the data url
2024-08-08 02:59:26 +08:00
* @param {AssetModuleFilename=} filename override for output.assetModuleFilename
* @param {RawPublicPath=} publicPath override for output.assetModulePublicPath
* @param {AssetModuleOutputPath=} outputPath the output path for the emitted file which is not included in the runtime import
* @param {boolean=} emit generate output asset
2019-11-16 00:27:36 +08:00
*/
constructor(
moduleGraph,
dataUrlOptions,
filename,
publicPath,
outputPath,
emit
) {
2019-11-16 00:27:36 +08:00
super();
this.dataUrlOptions = dataUrlOptions;
this.filename = filename;
2021-03-16 02:03:19 +08:00
this.publicPath = publicPath;
this.outputPath = outputPath;
this.emit = emit;
this._moduleGraph = moduleGraph;
2019-11-16 00:27:36 +08:00
}
2021-11-29 20:37:38 +08:00
/**
* @param {NormalModule} module module
* @param {RuntimeTemplate} runtimeTemplate runtime template
* @returns {string} source file name
*/
static getSourceFileName(module, runtimeTemplate) {
2021-11-29 20:37:38 +08:00
return makePathsRelative(
runtimeTemplate.compilation.compiler.context,
2025-08-30 01:28:44 +08:00
/** @type {string} */
(module.getResource()),
2021-11-29 20:37:38 +08:00
runtimeTemplate.compilation.compiler.root
).replace(/^\.\//, "");
}
/**
* @param {NormalModule} module module
* @param {RuntimeTemplate} runtimeTemplate runtime template
* @returns {[string, string]} return full hash and non-numeric full hash
*/
static getFullContentHash(module, runtimeTemplate) {
2025-08-20 18:50:12 +08:00
const hash = createHash(runtimeTemplate.outputOptions.hashFunction);
if (runtimeTemplate.outputOptions.hashSalt) {
hash.update(runtimeTemplate.outputOptions.hashSalt);
}
const source = module.originalSource();
if (source) {
hash.update(source.buffer());
}
if (module.error) {
hash.update(module.error.toString());
}
const fullContentHash = /** @type {string} */ (
hash.digest(runtimeTemplate.outputOptions.hashDigest)
);
/** @type {string} */
const contentHash = nonNumericOnlyHash(
fullContentHash,
2025-08-20 18:50:12 +08:00
runtimeTemplate.outputOptions.hashDigestLength
);
return [fullContentHash, contentHash];
}
/**
* @param {NormalModule} module module for which the code should be generated
* @param {Pick<AssetResourceGeneratorOptions, "filename" | "outputPath">} generatorOptions generator options
* @param {{ runtime: RuntimeSpec, runtimeTemplate: RuntimeTemplate, chunkGraph: ChunkGraph }} generateContext context for generate
* @param {string} contentHash the content hash
* @returns {{ filename: string, originalFilename: string, assetInfo: AssetInfo }} info
*/
static getFilenameWithInfo(
module,
generatorOptions,
{ runtime, runtimeTemplate, chunkGraph },
contentHash
) {
const assetModuleFilename =
generatorOptions.filename ||
2025-08-20 18:50:12 +08:00
runtimeTemplate.outputOptions.assetModuleFilename;
const sourceFilename = AssetGenerator.getSourceFileName(
module,
runtimeTemplate
);
let { path: filename, info: assetInfo } =
runtimeTemplate.compilation.getAssetPathWithInfo(assetModuleFilename, {
module,
runtime,
filename: sourceFilename,
chunkGraph,
contentHash
});
const originalFilename = filename;
if (generatorOptions.outputPath) {
const { path: outputPath, info } =
runtimeTemplate.compilation.getAssetPathWithInfo(
generatorOptions.outputPath,
{
module,
runtime,
filename: sourceFilename,
chunkGraph,
contentHash
}
);
filename = path.posix.join(outputPath, filename);
assetInfo = mergeAssetInfo(assetInfo, info);
}
return { originalFilename, filename, assetInfo };
}
/**
* @param {NormalModule} module module for which the code should be generated
* @param {Pick<AssetResourceGeneratorOptions, "publicPath">} generatorOptions generator options
* @param {GenerateContext} generateContext context for generate
* @param {string} filename the filename
* @param {AssetInfo} assetInfo the asset info
* @param {string} contentHash the content hash
* @returns {{ assetPath: string, assetInfo: AssetInfo }} asset path and info
*/
static getAssetPathWithInfo(
module,
generatorOptions,
{ runtime, runtimeTemplate, type, chunkGraph, runtimeRequirements },
filename,
assetInfo,
contentHash
) {
const sourceFilename = AssetGenerator.getSourceFileName(
module,
runtimeTemplate
);
let assetPath;
if (generatorOptions.publicPath !== undefined && type === "javascript") {
const { path, info } = runtimeTemplate.compilation.getAssetPathWithInfo(
generatorOptions.publicPath,
{
module,
runtime,
filename: sourceFilename,
chunkGraph,
contentHash
}
);
assetInfo = mergeAssetInfo(assetInfo, info);
assetPath = JSON.stringify(path + filename);
} else if (
generatorOptions.publicPath !== undefined &&
type === "css-url"
) {
const { path, info } = runtimeTemplate.compilation.getAssetPathWithInfo(
generatorOptions.publicPath,
{
module,
runtime,
filename: sourceFilename,
chunkGraph,
contentHash
}
);
assetInfo = mergeAssetInfo(assetInfo, info);
assetPath = path + filename;
} else if (type === "javascript") {
// add __webpack_require__.p
runtimeRequirements.add(RuntimeGlobals.publicPath);
assetPath = runtimeTemplate.concatenation(
{ expr: RuntimeGlobals.publicPath },
filename
);
} else if (type === "css-url") {
const compilation = runtimeTemplate.compilation;
const path =
compilation.outputOptions.publicPath === "auto"
? CssUrlDependency.PUBLIC_PATH_AUTO
2025-08-20 18:50:12 +08:00
: compilation.getAssetPath(compilation.outputOptions.publicPath, {
hash: compilation.hash
});
assetPath = path + filename;
}
return {
// eslint-disable-next-line object-shorthand
assetPath: /** @type {string} */ (assetPath),
assetInfo: { sourceFilename, ...assetInfo }
};
}
2022-03-11 21:34:17 +08:00
/**
* @param {NormalModule} module module for which the bailout reason should be determined
* @param {ConcatenationBailoutReasonContext} context context
* @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
*/
getConcatenationBailoutReason(module, context) {
return undefined;
}
2021-11-29 20:37:38 +08:00
/**
* @param {NormalModule} module module
2022-02-22 19:23:24 +08:00
* @returns {string} mime type
2021-11-29 20:37:38 +08:00
*/
getMimeType(module) {
2022-02-22 19:23:24 +08:00
if (typeof this.dataUrlOptions === "function") {
throw new Error(
"This method must not be called when dataUrlOptions is a function"
);
}
2021-11-29 20:37:38 +08:00
2023-06-17 01:13:03 +08:00
/** @type {string | boolean | undefined} */
2024-08-08 02:59:26 +08:00
let mimeType =
/** @type {AssetGeneratorDataUrlOptions} */
(this.dataUrlOptions).mimetype;
2021-11-29 20:37:38 +08:00
if (mimeType === undefined) {
2024-08-08 02:59:26 +08:00
const ext = path.extname(
2025-09-11 08:10:10 +08:00
/** @type {NameForCondition} */
2024-08-08 02:59:26 +08:00
(module.nameForCondition())
);
2021-11-29 20:37:38 +08:00
if (
module.resourceResolveData &&
module.resourceResolveData.mimetype !== undefined
) {
mimeType =
module.resourceResolveData.mimetype +
module.resourceResolveData.parameters;
} else if (ext) {
2025-08-30 03:53:13 +08:00
mimeType = getMimeTypes().lookup(ext);
2022-02-22 19:23:24 +08:00
if (typeof mimeType !== "string") {
throw new Error(
"DataUrl can't be generated automatically, " +
`because there is no mimetype for "${ext}" in mimetype database. ` +
'Either pass a mimetype via "generator.mimetype" or ' +
'use type: "asset/resource" to create a resource file instead of a DataUrl'
);
}
2021-11-29 20:37:38 +08:00
}
}
2022-02-22 19:23:24 +08:00
if (typeof mimeType !== "string") {
throw new Error(
"DataUrl can't be generated automatically. " +
'Either pass a mimetype via "generator.mimetype" or ' +
'use type: "asset/resource" to create a resource file instead of a DataUrl'
);
}
2023-06-17 01:13:03 +08:00
return /** @type {string} */ (mimeType);
2021-11-29 20:37:38 +08:00
}
/**
* @param {NormalModule} module module for which the code should be generated
* @returns {string} DataURI
*/
generateDataUri(module) {
const source = /** @type {Source} */ (module.originalSource());
let encodedSource;
if (typeof this.dataUrlOptions === "function") {
encodedSource = this.dataUrlOptions.call(null, source.source(), {
2025-08-30 01:28:44 +08:00
filename: /** @type {string} */ (module.getResource()),
module
});
} else {
let encoding =
/** @type {AssetGeneratorDataUrlOptions} */
(this.dataUrlOptions).encoding;
if (
encoding === undefined &&
module.resourceResolveData &&
module.resourceResolveData.encoding !== undefined
) {
encoding = module.resourceResolveData.encoding;
}
if (encoding === undefined) {
encoding = DEFAULT_ENCODING;
}
const mimeType = this.getMimeType(module);
let encodedContent;
if (
module.resourceResolveData &&
module.resourceResolveData.encoding === encoding &&
decodeDataUriContent(
module.resourceResolveData.encoding,
2025-05-13 21:03:58 +08:00
/** @type {string} */ (module.resourceResolveData.encodedContent)
).equals(source.buffer())
) {
encodedContent = module.resourceResolveData.encodedContent;
} else {
2025-05-13 21:03:58 +08:00
encodedContent = encodeDataUri(
/** @type {"base64" | false} */ (encoding),
source
);
}
encodedSource = `data:${mimeType}${
encoding ? `;${encoding}` : ""
},${encodedContent}`;
}
return encodedSource;
}
/**
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
2024-10-24 04:30:31 +08:00
* @returns {Source | null} generated code
*/
generate(module, generateContext) {
const {
type,
getData,
runtimeTemplate,
runtimeRequirements,
concatenationScope
} = generateContext;
let content;
const needContent = type === "javascript" || type === "css-url";
2024-10-16 22:42:26 +08:00
const data = getData ? getData() : undefined;
if (
/** @type {BuildInfo} */
(module.buildInfo).dataUrl &&
needContent
) {
2024-10-13 01:37:00 +08:00
const encodedSource = this.generateDataUri(module);
content =
type === "javascript" ? JSON.stringify(encodedSource) : encodedSource;
2024-10-13 01:37:00 +08:00
if (data) {
data.set("url", { [type]: content, ...data.get("url") });
}
} else {
const [fullContentHash, contentHash] = AssetGenerator.getFullContentHash(
module,
runtimeTemplate
2024-10-13 01:37:00 +08:00
);
2024-10-13 01:37:00 +08:00
if (data) {
data.set("fullContentHash", fullContentHash);
data.set("contentHash", contentHash);
2019-11-26 16:53:47 +08:00
}
2024-10-12 22:04:12 +08:00
/** @type {BuildInfo} */
(module.buildInfo).fullContentHash = fullContentHash;
2024-10-13 01:37:00 +08:00
const { originalFilename, filename, assetInfo } =
AssetGenerator.getFilenameWithInfo(
module,
{ filename: this.filename, outputPath: this.outputPath },
generateContext,
contentHash
);
2024-10-13 01:37:00 +08:00
if (data) {
data.set("filename", filename);
}
let { assetPath, assetInfo: newAssetInfo } =
AssetGenerator.getAssetPathWithInfo(
module,
{ publicPath: this.publicPath },
generateContext,
originalFilename,
assetInfo,
contentHash
);
2024-10-11 23:08:56 +08:00
if (data && (type === "javascript" || type === "css-url")) {
data.set("url", { [type]: assetPath, ...data.get("url") });
}
2025-07-09 18:59:21 +08:00
if (data) {
const oldAssetInfo = data.get("assetInfo");
if (oldAssetInfo) {
newAssetInfo = mergeAssetInfo(oldAssetInfo, newAssetInfo);
}
2024-11-01 04:19:07 +08:00
}
if (data) {
2024-10-13 01:37:00 +08:00
data.set("assetInfo", newAssetInfo);
}
// Due to code generation caching module.buildInfo.XXX can't used to store such information
// It need to be stored in the code generation results instead, where it's cached too
// TODO webpack 6 For back-compat reasons we also store in on module.buildInfo
2024-10-12 18:45:07 +08:00
/** @type {BuildInfo} */
(module.buildInfo).filename = filename;
2024-10-12 18:45:07 +08:00
/** @type {BuildInfo} */
2024-10-13 01:37:00 +08:00
(module.buildInfo).assetInfo = newAssetInfo;
content = assetPath;
}
if (type === "javascript") {
if (concatenationScope) {
concatenationScope.registerNamespaceExport(
ConcatenationScope.NAMESPACE_OBJECT_EXPORT
);
return new RawSource(
`${runtimeTemplate.renderConst()} ${
ConcatenationScope.NAMESPACE_OBJECT_EXPORT
} = ${content};`
);
}
runtimeRequirements.add(RuntimeGlobals.module);
return new RawSource(`${RuntimeGlobals.module}.exports = ${content};`);
} else if (type === "css-url") {
return null;
}
return /** @type {Source} */ (module.originalSource());
}
/**
* @param {Error} error the error
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source | null} generated code
*/
generateError(error, module, generateContext) {
switch (generateContext.type) {
case "asset": {
return new RawSource(error.message);
}
case "javascript": {
return new RawSource(
`throw new Error(${JSON.stringify(error.message)});`
);
}
default:
return null;
}
}
/**
* @param {NormalModule} module fresh module
2024-11-01 04:19:07 +08:00
* @returns {SourceTypes} available types (do not mutate)
*/
getTypes(module) {
/** @type {Set<string>} */
const sourceTypes = new Set();
const connections = this._moduleGraph.getIncomingConnections(module);
for (const connection of connections) {
2024-10-12 18:25:10 +08:00
if (!connection.originModule) {
continue;
}
sourceTypes.add(connection.originModule.type.split("/")[0]);
}
2021-07-05 17:22:13 +08:00
if ((module.buildInfo && module.buildInfo.dataUrl) || this.emit === false) {
if (sourceTypes.size > 0) {
if (sourceTypes.has("javascript") && sourceTypes.has("css")) {
2024-11-01 04:19:07 +08:00
return JS_AND_CSS_URL_TYPES;
} else if (sourceTypes.has("css")) {
2024-11-01 04:19:07 +08:00
return CSS_URL_TYPES;
}
return JS_TYPES;
}
return NO_TYPES;
}
if (sourceTypes.size > 0) {
if (sourceTypes.has("javascript") && sourceTypes.has("css")) {
2024-11-01 04:19:07 +08:00
return ASSET_AND_JS_AND_CSS_URL_TYPES;
} else if (sourceTypes.has("css")) {
2024-11-01 04:19:07 +08:00
return ASSET_AND_CSS_URL_TYPES;
}
return ASSET_AND_JS_TYPES;
}
return ASSET_TYPES;
}
/**
* @param {NormalModule} module the module
* @param {string=} type source type
* @returns {number} estimate size of the module
*/
2019-11-27 04:24:41 +08:00
getSize(module, type) {
switch (type) {
case ASSET_MODULE_TYPE: {
const originalSource = module.originalSource();
2019-06-06 05:29:53 +08:00
if (!originalSource) {
return 0;
}
return originalSource.size();
}
default:
2021-07-05 17:22:13 +08:00
if (module.buildInfo && module.buildInfo.dataUrl) {
const originalSource = module.originalSource();
if (!originalSource) {
return 0;
}
// roughly for data url
// Example: m.exports="data:image/png;base64,ag82/f+2=="
// 4/3 = base64 encoding
// 34 = ~ data url header + footer + rounding
return originalSource.size() * 1.34 + 36;
}
2024-07-31 04:21:27 +08:00
// it's only estimated so this number is probably fine
// Example: m.exports=r.p+"0123456789012345678901.ext"
return 42;
}
}
/**
* @param {Hash} hash hash that will be modified
* @param {UpdateHashContext} updateHashContext context for updating hash
*/
2024-08-09 23:42:37 +08:00
updateHash(hash, updateHashContext) {
const { module } = updateHashContext;
2024-08-08 02:59:26 +08:00
if (
/** @type {BuildInfo} */
(module.buildInfo).dataUrl
) {
2021-11-29 20:37:38 +08:00
hash.update("data-url");
2022-02-22 19:23:24 +08:00
// this.dataUrlOptions as function should be pure and only depend on input source and filename
// therefore it doesn't need to be hashed
2021-11-29 20:37:38 +08:00
if (typeof this.dataUrlOptions === "function") {
2022-02-22 19:23:24 +08:00
const ident = /** @type {{ ident?: string }} */ (this.dataUrlOptions)
.ident;
if (ident) hash.update(ident);
2021-11-29 20:37:38 +08:00
} else {
2024-08-08 02:59:26 +08:00
const dataUrlOptions =
/** @type {AssetGeneratorDataUrlOptions} */
(this.dataUrlOptions);
2022-02-28 16:45:00 +08:00
if (
2024-08-08 02:59:26 +08:00
dataUrlOptions.encoding &&
dataUrlOptions.encoding !== DEFAULT_ENCODING
2022-02-28 16:45:00 +08:00
) {
2024-08-08 02:59:26 +08:00
hash.update(dataUrlOptions.encoding);
2022-02-28 16:45:00 +08:00
}
2024-08-08 02:59:26 +08:00
if (dataUrlOptions.mimetype) hash.update(dataUrlOptions.mimetype);
2022-02-22 19:23:24 +08:00
// computed mimetype depends only on module filename which is already part of the hash
2021-11-29 20:37:38 +08:00
}
} else {
hash.update("resource");
2024-08-09 23:42:37 +08:00
const { module, chunkGraph, runtime } = updateHashContext;
const runtimeTemplate =
/** @type {NonNullable<UpdateHashContext["runtimeTemplate"]>} */
(updateHashContext.runtimeTemplate);
2021-11-29 20:37:38 +08:00
const pathData = {
module,
runtime,
filename: AssetGenerator.getSourceFileName(module, runtimeTemplate),
2021-11-29 20:37:38 +08:00
chunkGraph,
contentHash: runtimeTemplate.contentHashReplacement
};
if (typeof this.publicPath === "function") {
2022-02-22 19:23:24 +08:00
hash.update("path");
const assetInfo = {};
hash.update(this.publicPath(pathData, assetInfo));
hash.update(JSON.stringify(assetInfo));
2021-11-29 20:37:38 +08:00
} else if (this.publicPath) {
2022-02-22 19:23:24 +08:00
hash.update("path");
hash.update(this.publicPath);
2021-11-29 20:37:38 +08:00
} else {
hash.update("no-path");
}
const assetModuleFilename =
2025-08-20 18:50:12 +08:00
this.filename || runtimeTemplate.outputOptions.assetModuleFilename;
2022-02-22 19:23:24 +08:00
const { path: filename, info } =
2021-11-29 20:37:38 +08:00
runtimeTemplate.compilation.getAssetPathWithInfo(
assetModuleFilename,
pathData
);
hash.update(filename);
2022-02-22 19:23:24 +08:00
hash.update(JSON.stringify(info));
2021-11-29 20:37:38 +08:00
}
}
}
2019-11-19 21:32:40 +08:00
module.exports = AssetGenerator;