feat: refactoring project

This commit is contained in:
Carlos
2024-11-23 14:56:07 -05:00
parent f0c2a50c18
commit 1c6db5818d
2351 changed files with 39323 additions and 60326 deletions

View File

@@ -9,15 +9,18 @@ const fs = require("fs");
const path = require("path");
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JSON_MODULE_TYPE,
WEBASSEMBLY_MODULE_TYPE_ASYNC,
JAVASCRIPT_MODULE_TYPE_ESM,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JSON_MODULE_TYPE,
WEBASSEMBLY_MODULE_TYPE_ASYNC,
WEBASSEMBLY_MODULE_TYPE_SYNC,
ASSET_MODULE_TYPE,
ASSET_MODULE_TYPE_INLINE,
ASSET_MODULE_TYPE_RESOURCE,
CSS_MODULE_TYPE_AUTO,
CSS_MODULE_TYPE,
CSS_MODULE_TYPE_MODULE
CSS_MODULE_TYPE_MODULE,
CSS_MODULE_TYPE_GLOBAL
} = require("../ModuleTypeConstants");
const Template = require("../Template");
const { cleverMerge } = require("../util/cleverMerge");
@@ -123,8 +126,8 @@ const A = (obj, prop, factory) => {
if (value === undefined) {
obj[prop] = factory();
} else if (Array.isArray(value)) {
/** @type {any[] | undefined} */
let newArray = undefined;
/** @type {EXPECTED_ANY[] | undefined} */
let newArray;
for (let i = 0; i < value.length; i++) {
const item = value[i];
if (item === "...") {
@@ -132,7 +135,9 @@ const A = (obj, prop, factory) => {
newArray = value.slice(0, i);
obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray));
}
const items = /** @type {any[]} */ (/** @type {unknown} */ (factory()));
const items = /** @type {EXPECTED_ANY[]} */ (
/** @type {unknown} */ (factory())
);
if (items !== undefined) {
for (const item of items) {
newArray.push(item);
@@ -161,13 +166,13 @@ const applyWebpackOptionsBaseDefaults = options => {
*/
const applyWebpackOptionsDefaults = (options, compilerIndex) => {
F(options, "context", () => process.cwd());
F(options, "target", () => {
return getDefaultTarget(/** @type {string} */ (options.context));
});
F(options, "target", () =>
getDefaultTarget(/** @type {string} */ (options.context))
);
const { mode, name, target } = options;
let targetProperties =
const targetProperties =
target === false
? /** @type {false} */ (false)
: typeof target === "string"
@@ -217,7 +222,7 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => {
cacheUnaffected: options.experiments.cacheUnaffected,
compilerIndex
});
const cache = !!options.cache;
const cache = Boolean(options.cache);
applySnapshotDefaults(options.snapshot, {
production,
@@ -258,7 +263,7 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => {
applyExternalsPresetsDefaults(options.externalsPresets, {
targetProperties,
buildHttp: !!options.experiments.buildHttp
buildHttp: Boolean(options.experiments.buildHttp)
});
applyLoaderDefaults(
@@ -275,7 +280,7 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => {
validExternalTypes.includes(options.output.library.type)
? /** @type {ExternalsType} */ (options.output.library.type)
: options.output.module
? "module"
? "module-import"
: "var";
});
@@ -283,7 +288,9 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => {
futureDefaults:
/** @type {NonNullable<WebpackOptionsNormalized["experiments"]["futureDefaults"]>} */
(options.experiments.futureDefaults),
outputModule: options.output.module,
outputModule:
/** @type {NonNullable<WebpackOptionsNormalized["output"]["module"]>} */
(options.output.module),
targetProperties
});
@@ -308,7 +315,7 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => {
css:
/** @type {NonNullable<ExperimentsNormalized["css"]>} */
(options.experiments.css),
records: !!(options.recordsInputPath || options.recordsOutputPath)
records: Boolean(options.recordsInputPath || options.recordsOutputPath)
});
options.resolve = cleverMerge(
@@ -399,8 +406,8 @@ const applyCacheDefaults = (
case "filesystem":
F(cache, "name", () =>
compilerIndex !== undefined
? `${name + "-" + mode}__compiler${compilerIndex + 1}__`
: name + "-" + mode
? `${`${name}-${mode}`}__compiler${compilerIndex + 1}__`
: `${name}-${mode}`
);
D(cache, "version", "");
F(cache, "cacheDirectory", () => {
@@ -411,7 +418,7 @@ const applyCacheDefaults = (
try {
if (fs.statSync(path.join(dir, "package.json")).isFile()) break;
// eslint-disable-next-line no-empty
} catch (e) {}
} catch (_err) {}
const parent = path.dirname(dir);
if (dir === parent) {
dir = undefined;
@@ -425,9 +432,8 @@ const applyCacheDefaults = (
return path.resolve(dir, ".pnp/.cache/webpack");
} else if (process.versions.pnp === "3") {
return path.resolve(dir, ".yarn/.cache/webpack");
} else {
return path.resolve(dir, "node_modules/.cache/webpack");
}
return path.resolve(dir, "node_modules/.cache/webpack");
});
F(cache, "cacheLocation", () =>
path.resolve(
@@ -632,19 +638,19 @@ const applyModuleDefaults = (
F(module.parser, ASSET_MODULE_TYPE, () => ({}));
F(
/** @type {NonNullable<ParserOptionsByModuleTypeKnown["asset"]>} */
(module.parser.asset),
(module.parser[ASSET_MODULE_TYPE]),
"dataUrlCondition",
() => ({})
);
if (
typeof (
/** @type {NonNullable<ParserOptionsByModuleTypeKnown["asset"]>} */
(module.parser.asset).dataUrlCondition
(module.parser[ASSET_MODULE_TYPE]).dataUrlCondition
) === "object"
) {
D(
/** @type {NonNullable<ParserOptionsByModuleTypeKnown["asset"]>} */
(module.parser.asset).dataUrlCondition,
(module.parser[ASSET_MODULE_TYPE]).dataUrlCondition,
"maxSize",
8096
);
@@ -662,41 +668,41 @@ const applyModuleDefaults = (
);
if (css) {
F(module.parser, "css", () => ({}));
F(module.parser, CSS_MODULE_TYPE, () => ({}));
D(module.parser.css, "namedExports", true);
D(module.parser[CSS_MODULE_TYPE], "namedExports", true);
F(module.generator, "css", () => ({}));
F(module.generator, CSS_MODULE_TYPE, () => ({}));
applyCssGeneratorOptionsDefaults(
/** @type {NonNullable<GeneratorOptionsByModuleTypeKnown["css"]>} */
(module.generator.css),
(module.generator[CSS_MODULE_TYPE]),
{ targetProperties }
);
F(module.generator, "css/auto", () => ({}));
F(module.generator, CSS_MODULE_TYPE_AUTO, () => ({}));
D(
module.generator["css/auto"],
module.generator[CSS_MODULE_TYPE_AUTO],
"localIdentName",
"[uniqueName]-[id]-[local]"
);
D(module.generator["css/auto"], "exportsConvention", "as-is");
D(module.generator[CSS_MODULE_TYPE_AUTO], "exportsConvention", "as-is");
F(module.generator, "css/module", () => ({}));
F(module.generator, CSS_MODULE_TYPE_MODULE, () => ({}));
D(
module.generator["css/module"],
module.generator[CSS_MODULE_TYPE_MODULE],
"localIdentName",
"[uniqueName]-[id]-[local]"
);
D(module.generator["css/module"], "exportsConvention", "as-is");
D(module.generator[CSS_MODULE_TYPE_MODULE], "exportsConvention", "as-is");
F(module.generator, "css/global", () => ({}));
F(module.generator, CSS_MODULE_TYPE_GLOBAL, () => ({}));
D(
module.generator["css/global"],
module.generator[CSS_MODULE_TYPE_GLOBAL],
"localIdentName",
"[uniqueName]-[id]-[local]"
);
D(module.generator["css/global"], "exportsConvention", "as-is");
D(module.generator[CSS_MODULE_TYPE_GLOBAL], "exportsConvention", "as-is");
}
A(module, "defaultRules", () => {
@@ -828,19 +834,19 @@ const applyModuleDefaults = (
oneOf: [
{
scheme: /^data$/,
type: "asset/inline"
type: ASSET_MODULE_TYPE_INLINE
},
{
type: "asset/resource"
type: ASSET_MODULE_TYPE_RESOURCE
}
]
},
{
assert: { type: "json" },
assert: { type: JSON_MODULE_TYPE },
type: JSON_MODULE_TYPE
},
{
with: { type: "json" },
with: { type: JSON_MODULE_TYPE },
type: JSON_MODULE_TYPE
}
);
@@ -909,196 +915,18 @@ const applyOutputDefaults = (
try {
const packageInfo = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
return packageInfo.name || "";
} catch (e) {
if (/** @type {Error & { code: string }} */ (e).code !== "ENOENT") {
} catch (err) {
if (/** @type {Error & { code: string }} */ (err).code !== "ENOENT") {
/** @type {Error & { code: string }} */
(e).message +=
(err).message +=
`\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`;
throw e;
throw err;
}
return "";
}
});
F(output, "module", () => !!outputModule);
D(output, "filename", output.module ? "[name].mjs" : "[name].js");
F(output, "iife", () => !output.module);
D(output, "importFunctionName", "import");
D(output, "importMetaName", "import.meta");
F(output, "chunkFilename", () => {
const filename =
/** @type {NonNullable<Output["chunkFilename"]>} */
(output.filename);
if (typeof filename !== "function") {
const hasName = filename.includes("[name]");
const hasId = filename.includes("[id]");
const hasChunkHash = filename.includes("[chunkhash]");
const hasContentHash = filename.includes("[contenthash]");
// Anything changing depending on chunk is fine
if (hasChunkHash || hasContentHash || hasName || hasId) return filename;
// Otherwise prefix "[id]." in front of the basename to make it changing
return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2");
}
return output.module ? "[id].mjs" : "[id].js";
});
F(output, "cssFilename", () => {
const filename =
/** @type {NonNullable<Output["cssFilename"]>} */
(output.filename);
if (typeof filename !== "function") {
return filename.replace(/\.[mc]?js(\?|$)/, ".css$1");
}
return "[id].css";
});
F(output, "cssChunkFilename", () => {
const chunkFilename =
/** @type {NonNullable<Output["cssChunkFilename"]>} */
(output.chunkFilename);
if (typeof chunkFilename !== "function") {
return chunkFilename.replace(/\.[mc]?js(\?|$)/, ".css$1");
}
return "[id].css";
});
D(output, "cssHeadDataCompression", !development);
D(output, "assetModuleFilename", "[hash][ext][query]");
D(output, "webassemblyModuleFilename", "[hash].module.wasm");
D(output, "compareBeforeEmit", true);
D(output, "charset", true);
const uniqueNameId = Template.toIdentifier(
/** @type {NonNullable<Output["uniqueName"]>} */ (output.uniqueName)
);
F(output, "hotUpdateGlobal", () => "webpackHotUpdate" + uniqueNameId);
F(output, "chunkLoadingGlobal", () => "webpackChunk" + uniqueNameId);
F(output, "globalObject", () => {
if (tp) {
if (tp.global) return "global";
if (tp.globalThis) return "globalThis";
}
return "self";
});
F(output, "chunkFormat", () => {
if (tp) {
const helpMessage = isAffectedByBrowserslist
? "Make sure that your 'browserslist' includes only platforms that support these features or select an appropriate 'target' to allow selecting a chunk format by default. Alternatively specify the 'output.chunkFormat' directly."
: "Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly.";
if (output.module) {
if (tp.dynamicImport) return "module";
if (tp.document) return "array-push";
throw new Error(
"For the selected environment is no default ESM chunk format available:\n" +
"ESM exports can be chosen when 'import()' is available.\n" +
"JSONP Array push can be chosen when 'document' is available.\n" +
helpMessage
);
} else {
if (tp.document) return "array-push";
if (tp.require) return "commonjs";
if (tp.nodeBuiltins) return "commonjs";
if (tp.importScripts) return "array-push";
throw new Error(
"For the selected environment is no default script chunk format available:\n" +
"JSONP Array push can be chosen when 'document' or 'importScripts' is available.\n" +
"CommonJs exports can be chosen when 'require' or node builtins are available.\n" +
helpMessage
);
}
}
throw new Error(
"Chunk format can't be selected by default when no target is specified"
);
});
D(output, "asyncChunks", true);
F(output, "chunkLoading", () => {
if (tp) {
switch (output.chunkFormat) {
case "array-push":
if (tp.document) return "jsonp";
if (tp.importScripts) return "import-scripts";
break;
case "commonjs":
if (tp.require) return "require";
if (tp.nodeBuiltins) return "async-node";
break;
case "module":
if (tp.dynamicImport || output.module) return "import";
break;
}
if (
tp.require === null ||
tp.nodeBuiltins === null ||
tp.document === null ||
tp.importScripts === null
) {
return "universal";
}
}
return false;
});
F(output, "workerChunkLoading", () => {
if (tp) {
switch (output.chunkFormat) {
case "array-push":
if (tp.importScriptsInWorker) return "import-scripts";
break;
case "commonjs":
if (tp.require) return "require";
if (tp.nodeBuiltins) return "async-node";
break;
case "module":
if (tp.dynamicImportInWorker || output.module) return "import";
break;
}
if (
tp.require === null ||
tp.nodeBuiltins === null ||
tp.importScriptsInWorker === null
) {
return "universal";
}
}
return false;
});
F(output, "wasmLoading", () => {
if (tp) {
if (tp.fetchWasm) return "fetch";
if (tp.nodeBuiltins)
return output.module ? "async-node-module" : "async-node";
if (tp.nodeBuiltins === null || tp.fetchWasm === null) {
return "universal";
}
}
return false;
});
F(output, "workerWasmLoading", () => output.wasmLoading);
F(output, "devtoolNamespace", () => output.uniqueName);
if (output.library) {
F(output.library, "type", () => (output.module ? "module" : "var"));
}
F(output, "path", () => path.join(process.cwd(), "dist"));
F(output, "pathinfo", () => development);
D(output, "sourceMapFilename", "[file].map[query]");
D(
output,
"hotUpdateChunkFilename",
`[id].[fullhash].hot-update.${output.module ? "mjs" : "js"}`
);
D(output, "hotUpdateMainFilename", "[runtime].[fullhash].hot-update.json");
D(output, "crossOriginLoading", false);
F(output, "scriptType", () => (output.module ? "module" : false));
D(
output,
"publicPath",
(tp && (tp.document || tp.importScripts)) || output.scriptType === "module"
? "auto"
: ""
);
D(output, "workerPublicPath", "");
D(output, "chunkLoadTimeout", 120000);
D(output, "hashFunction", futureDefaults ? "xxhash64" : "md4");
D(output, "hashDigest", "hex");
D(output, "hashDigestLength", futureDefaults ? 16 : 20);
D(output, "strictModuleErrorHandling", false);
D(output, "strictModuleExceptionHandling", false);
F(output, "module", () => Boolean(outputModule));
const environment = /** @type {Environment} */ (output.environment);
/**
@@ -1121,7 +949,8 @@ const applyOutputDefaults = (
F(
environment,
"bigIntLiteral",
() => /** @type {boolean | undefined} */ (tp && tp.bigIntLiteral)
() =>
tp && optimistic(/** @type {boolean | undefined} */ (tp.bigIntLiteral))
);
F(
environment,
@@ -1196,6 +1025,187 @@ const applyOutputDefaults = (
() => tp && optimistic(/** @type {boolean | undefined} */ (tp.document))
);
D(output, "filename", output.module ? "[name].mjs" : "[name].js");
F(output, "iife", () => !output.module);
D(output, "importFunctionName", "import");
D(output, "importMetaName", "import.meta");
F(output, "chunkFilename", () => {
const filename =
/** @type {NonNullable<Output["chunkFilename"]>} */
(output.filename);
if (typeof filename !== "function") {
const hasName = filename.includes("[name]");
const hasId = filename.includes("[id]");
const hasChunkHash = filename.includes("[chunkhash]");
const hasContentHash = filename.includes("[contenthash]");
// Anything changing depending on chunk is fine
if (hasChunkHash || hasContentHash || hasName || hasId) return filename;
// Otherwise prefix "[id]." in front of the basename to make it changing
return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2");
}
return output.module ? "[id].mjs" : "[id].js";
});
F(output, "cssFilename", () => {
const filename =
/** @type {NonNullable<Output["cssFilename"]>} */
(output.filename);
if (typeof filename !== "function") {
return filename.replace(/\.[mc]?js(\?|$)/, ".css$1");
}
return "[id].css";
});
F(output, "cssChunkFilename", () => {
const chunkFilename =
/** @type {NonNullable<Output["cssChunkFilename"]>} */
(output.chunkFilename);
if (typeof chunkFilename !== "function") {
return chunkFilename.replace(/\.[mc]?js(\?|$)/, ".css$1");
}
return "[id].css";
});
D(output, "cssHeadDataCompression", !development);
D(output, "assetModuleFilename", "[hash][ext][query]");
D(output, "webassemblyModuleFilename", "[hash].module.wasm");
D(output, "compareBeforeEmit", true);
D(output, "charset", true);
const uniqueNameId = Template.toIdentifier(
/** @type {NonNullable<Output["uniqueName"]>} */ (output.uniqueName)
);
F(output, "hotUpdateGlobal", () => `webpackHotUpdate${uniqueNameId}`);
F(output, "chunkLoadingGlobal", () => `webpackChunk${uniqueNameId}`);
F(output, "globalObject", () => {
if (tp) {
if (tp.global) return "global";
if (tp.globalThis) return "globalThis";
}
return "self";
});
F(output, "chunkFormat", () => {
if (tp) {
const helpMessage = isAffectedByBrowserslist
? "Make sure that your 'browserslist' includes only platforms that support these features or select an appropriate 'target' to allow selecting a chunk format by default. Alternatively specify the 'output.chunkFormat' directly."
: "Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly.";
if (output.module) {
if (environment.dynamicImport) return "module";
if (tp.document) return "array-push";
throw new Error(
"For the selected environment is no default ESM chunk format available:\n" +
"ESM exports can be chosen when 'import()' is available.\n" +
`JSONP Array push can be chosen when 'document' is available.\n${
helpMessage
}`
);
} else {
if (tp.document) return "array-push";
if (tp.require) return "commonjs";
if (tp.nodeBuiltins) return "commonjs";
if (tp.importScripts) return "array-push";
throw new Error(
"For the selected environment is no default script chunk format available:\n" +
"JSONP Array push can be chosen when 'document' or 'importScripts' is available.\n" +
`CommonJs exports can be chosen when 'require' or node builtins are available.\n${
helpMessage
}`
);
}
}
throw new Error(
"Chunk format can't be selected by default when no target is specified"
);
});
D(output, "asyncChunks", true);
F(output, "chunkLoading", () => {
if (tp) {
switch (output.chunkFormat) {
case "array-push":
if (tp.document) return "jsonp";
if (tp.importScripts) return "import-scripts";
break;
case "commonjs":
if (tp.require) return "require";
if (tp.nodeBuiltins) return "async-node";
break;
case "module":
if (environment.dynamicImport) return "import";
break;
}
if (
tp.require === null ||
tp.nodeBuiltins === null ||
tp.document === null ||
tp.importScripts === null
) {
return "universal";
}
}
return false;
});
F(output, "workerChunkLoading", () => {
if (tp) {
switch (output.chunkFormat) {
case "array-push":
if (tp.importScriptsInWorker) return "import-scripts";
break;
case "commonjs":
if (tp.require) return "require";
if (tp.nodeBuiltins) return "async-node";
break;
case "module":
if (environment.dynamicImportInWorker) return "import";
break;
}
if (
tp.require === null ||
tp.nodeBuiltins === null ||
tp.importScriptsInWorker === null
) {
return "universal";
}
}
return false;
});
F(output, "wasmLoading", () => {
if (tp) {
if (tp.fetchWasm) return "fetch";
if (tp.nodeBuiltins)
return output.module ? "async-node-module" : "async-node";
if (tp.nodeBuiltins === null || tp.fetchWasm === null) {
return "universal";
}
}
return false;
});
F(output, "workerWasmLoading", () => output.wasmLoading);
F(output, "devtoolNamespace", () => output.uniqueName);
if (output.library) {
F(output.library, "type", () => (output.module ? "module" : "var"));
}
F(output, "path", () => path.join(process.cwd(), "dist"));
F(output, "pathinfo", () => development);
D(output, "sourceMapFilename", "[file].map[query]");
D(
output,
"hotUpdateChunkFilename",
`[id].[fullhash].hot-update.${output.module ? "mjs" : "js"}`
);
D(output, "hotUpdateMainFilename", "[runtime].[fullhash].hot-update.json");
D(output, "crossOriginLoading", false);
F(output, "scriptType", () => (output.module ? "module" : false));
D(
output,
"publicPath",
(tp && (tp.document || tp.importScripts)) || output.scriptType === "module"
? "auto"
: ""
);
D(output, "workerPublicPath", "");
D(output, "chunkLoadTimeout", 120000);
D(output, "hashFunction", futureDefaults ? "xxhash64" : "md4");
D(output, "hashDigest", "hex");
D(output, "hashDigestLength", futureDefaults ? 16 : 20);
D(output, "strictModuleErrorHandling", false);
D(output, "strictModuleExceptionHandling", false);
const { trustedTypes } = output;
if (trustedTypes) {
F(
@@ -1432,6 +1442,7 @@ const applyOptimizationDefaults = (
D(optimization, "innerGraph", production);
D(optimization, "mangleExports", production);
D(optimization, "concatenateModules", production);
D(optimization, "avoidEntryIife", production);
D(optimization, "runtimeChunk", false);
D(optimization, "emitOnErrors", !production);
D(optimization, "checkWasmTypes", production);
@@ -1632,5 +1643,6 @@ const applyInfrastructureLoggingDefaults = infrastructureLogging => {
D(infrastructureLogging, "appendOnly", !tty);
};
exports.applyWebpackOptionsBaseDefaults = applyWebpackOptionsBaseDefaults;
exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults;
module.exports.applyWebpackOptionsBaseDefaults =
applyWebpackOptionsBaseDefaults;
module.exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults;