Enhance refactor commands with controller-aware Route() updates and fix code quality violations

Add semantic token highlighting for 'that' variable and comment file references in VS Code extension
Add Phone_Text_Input and Currency_Input components with formatting utilities
Implement client widgets, form standardization, and soft delete functionality
Add modal scroll lock and update documentation
Implement comprehensive modal system with form integration and validation
Fix modal component instantiation using jQuery plugin API
Implement modal system with responsive sizing, queuing, and validation support
Implement form submission with validation, error handling, and loading states
Implement country/state selectors with dynamic data loading and Bootstrap styling
Revert Rsx::Route() highlighting in Blade/PHP files
Target specific PHP scopes for Rsx::Route() highlighting in Blade
Expand injection selector for Rsx::Route() highlighting
Add custom syntax highlighting for Rsx::Route() and Rsx.Route() calls
Update jqhtml packages to v2.2.165
Add bundle path validation for common mistakes (development mode only)
Create Ajax_Select_Input widget and Rsx_Reference_Data controller
Create Country_Select_Input widget with default country support
Initialize Tom Select on Select_Input widgets
Add Tom Select bundle for enhanced select dropdowns
Implement ISO 3166 geographic data system for country/region selection
Implement widget-based form system with disabled state support

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
root
2025-10-30 06:21:56 +00:00
parent e678b987c2
commit f6ac36c632
5683 changed files with 5854736 additions and 22329 deletions

0
node_modules/webpack/LICENSE generated vendored Executable file → Normal file
View File

47
node_modules/webpack/README.md generated vendored
View File

@@ -20,6 +20,7 @@
[![contributors](https://img.shields.io/github/contributors/webpack/webpack.svg)](https://github.com/webpack/webpack/graphs/contributors)
[![discussions](https://img.shields.io/github/discussions/webpack/webpack)](https://github.com/webpack/webpack/discussions)
[![discord](https://img.shields.io/discord/1180618526436888586?label=discord&logo=discord&logoColor=white&style=flat)](https://discord.gg/5sxFZPdx2k)
[![LFX Health Score](https://insights.linuxfoundation.org/api/badge/health-score?project=webpack)](https://insights.linuxfoundation.org/project/webpack)
<h1>webpack</h1>
<p>
@@ -45,7 +46,7 @@
- [Backers](#backers)
- [Special Thanks](#special-thanks-to)
<h2>Install</h2>
## Install
Install with npm:
@@ -59,7 +60,7 @@ Install with yarn:
yarn add webpack --dev
```
<h2>Introduction</h2>
## Introduction
Webpack is a bundler for modules. The main purpose is to bundle JavaScript
files for usage in a browser, yet it is also capable of transforming, bundling,
@@ -87,7 +88,7 @@ Check out webpack's quick [**Get Started**](https://webpack.js.org/guides/gettin
Webpack supports all browsers that are [ES5-compliant](https://kangax.github.io/compat-table/es5/) (IE8 and below are not supported).
Webpack also needs `Promise` for `import()` and `require.ensure()`. If you want to support older browsers, you will need to [load a polyfill](https://webpack.js.org/guides/shimming/) before using these expressions.
<h2>Concepts</h2>
## Concepts
### [Plugins](https://webpack.js.org/plugins/)
@@ -264,7 +265,7 @@ If you're working on webpack itself, or building advanced plugins or integration
[tapable-tracer-npm]: https://img.shields.io/npm/v/tapable-tracer.svg
<h2>Contributing</h2>
## Contributing
**We want contributing to webpack to be fun, enjoyable, and educational for anyone, and everyone.** We have a [vibrant ecosystem](https://medium.com/webpack/contributors-guide/home) that spans beyond this single repo. We welcome you to check out any of the repositories in [our organization](https://github.com/webpack) or [webpack-contrib organization](https://github.com/webpack-contrib) which houses all of our loaders and plugins.
@@ -283,11 +284,11 @@ Contributions go far beyond pull requests and commits. Although we love giving y
To get started have a look at our [documentation on contributing](https://github.com/webpack/webpack/blob/main/CONTRIBUTING.md).
<h3>Creating your own plugins and loaders</h3>
### Creating your own plugins and loaders
If you create a loader or plugin, we would <3 for you to open source it, and put it on npm. We follow the `x-loader`, `x-webpack-plugin` naming convention.
<h2>Support</h2>
## Support
We consider webpack to be a low-level tool used not only individually but also layered beneath other awesome tools. Because of its flexibility, webpack isn't always the _easiest_ entry-level solution, however we do believe it is the most powerful. That said, we're always looking for ways to improve and simplify the tool without compromising functionality. If you have any ideas on ways to accomplish this, we're all ears!
@@ -295,11 +296,11 @@ If you're just getting started, take a look at [our new docs and concepts page](
If you have discovered a 🐜 or have a feature suggestion, feel free to create an issue on GitHub.
<h2>Current project members</h2>
## Current project members
For information about the governance of the Node.js project, see [GOVERNANCE.md](./GOVERNANCE.md).
For information about the governance of the webpack project, see [GOVERNANCE.md](./GOVERNANCE.md).
<h3>TSC (Technical Steering Committee)</h3>
### TSC (Technical Steering Committee)
- [alexander-akait](https://github.com/alexander-akait) -
**Alexander Akait** <<sheo13666q@gmail.com>> (he/him)
@@ -312,18 +313,11 @@ For information about the governance of the Node.js project, see [GOVERNANCE.md]
- [thelarkinn](https://github.com/thelarkinn) -
**Sean Larkin** <<selarkin@microsoft.com>> (he/him)
<h3>Core Collaborators</h3>
### Maintenance
- [jhnns](https://github.com/jhnns) -
**Johannes Ewald** <<mail@johannesewald.de>>
- [sokra](https://github.com/sokra) -
**Tobias Koppers** <<jackworks@protonmail.co>>
- [spacek33z](https://github.com/spacek33z) -
**Kees Kluskens** <<kees@webduck.nl>>
- [TheLarkInn](https://github.com/TheLarkInn) -
**Sean T. Larkin** <<selarkin@microsoft.com>>
This webpack repository is maintained by the [`Core Working Group`](./WORKING_GROUP.md).
<h2>Sponsoring</h2>
## Sponsoring
Most of the core team members, webpack contributors and contributors in the ecosystem do this open source work in their free time. If you use webpack for a serious task, and you'd like us to invest more time on it, please donate. This project increases your income/productivity too. It makes development and applications faster and it reduces the required bandwidth.
@@ -336,7 +330,7 @@ This is how we use the donations:
- Infrastructure cost
- Fees for money handling
<h3>Premium Partners</h3>
### Premium Partners
<div align="center">
@@ -345,7 +339,7 @@ This is how we use the donations:
</div>
<h3>Other Backers and Sponsors</h3>
### Other Backers and Sponsors
Before we started using OpenCollective, donations were made anonymously. Now that we have made the switch, we would like to acknowledge these sponsors (and the ones who continue to donate using OpenCollective). If we've missed someone, please send us a PR, and we'll add you to this list.
@@ -357,7 +351,7 @@ Before we started using OpenCollective, donations were made anonymously. Now tha
</div>
<h3>Gold Sponsors</h3>
### Gold Sponsors
[Become a gold sponsor](https://opencollective.com/webpack#sponsor) and get your logo on our README on GitHub with a link to your site.
@@ -396,7 +390,7 @@ Before we started using OpenCollective, donations were made anonymously. Now tha
</div>
<h3>Silver Sponsors</h3>
### Silver Sponsors
[Become a silver sponsor](https://opencollective.com/webpack#sponsor) and get your logo on our README on GitHub with a link to your site.
@@ -435,7 +429,7 @@ Before we started using OpenCollective, donations were made anonymously. Now tha
</div>
<h3>Bronze Sponsors</h3>
### Bronze Sponsors
[Become a bronze sponsor](https://opencollective.com/webpack#sponsor) and get your logo on our README on GitHub with a link to your site.
@@ -545,7 +539,7 @@ Before we started using OpenCollective, donations were made anonymously. Now tha
</div>
<h3>Backers</h3>
### Backers
[Become a backer](https://opencollective.com/webpack#backer) and get your image on our README on GitHub with a link to your site.
@@ -651,7 +645,8 @@ Before we started using OpenCollective, donations were made anonymously. Now tha
<a href="https://opencollective.com/webpack/backer/99/website?requireActive=false" target="_blank"><img width="30" src="https://opencollective.com/webpack/backer/99/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/100/website?requireActive=false" target="_blank"><img width="30" src="https://opencollective.com/webpack/backer/100/avatar.svg?requireActive=false"></a>
<h2>Special Thanks to</h2>
## Special Thanks to
<p>(In chronological order)</p>
- [@google](https://github.com/google) for [Google Web Toolkit (GWT)](http://www.gwtproject.org/), which aims to compile Java to JavaScript. It features a similar [Code Splitting](http://www.gwtproject.org/doc/latest/DevGuideCodeSplitting.html) as webpack.

9
node_modules/webpack/SECURITY.md generated vendored
View File

@@ -1,9 +0,0 @@
# Reporting Security Issues
If you discover a security issue in webpack, please report it by sending an
email to [webpack@opencollective.com](mailto:webpack@opencollective.com).
This will allow us to assess the risk, and make a fix available before we add a
bug report to the GitHub repository.
Thanks for helping make webpack safe for everyone.

0
node_modules/webpack/hot/dev-server.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/hot/emitter.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/hot/lazy-compilation-node.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/hot/lazy-compilation-web.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/hot/log-apply-result.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/hot/log.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/hot/only-dev-server.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/hot/poll.js generated vendored Executable file → Normal file
View File

0
node_modules/webpack/hot/signal.js generated vendored Executable file → Normal file
View File

View File

@@ -5,7 +5,9 @@
"use strict";
const InitFragment = require("./InitFragment");
const {
getExternalModuleNodeCommonjsInitFragment
} = require("./ExternalModule");
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
@@ -30,11 +32,9 @@ const GetFullHashRuntimeModule = require("./runtime/GetFullHashRuntimeModule");
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/**
* @param {boolean | undefined} module true if ES module
* @param {string} importMetaName `import.meta` name
* @returns {Record<string, {expr: string, req: string[] | null, type?: string, assign: boolean}>} replacements
*/
function getReplacements(module, importMetaName) {
function getReplacements() {
return {
__webpack_require__: {
expr: RuntimeGlobals.require,
@@ -67,9 +67,7 @@ function getReplacements(module, importMetaName) {
assign: true
},
__non_webpack_require__: {
expr: module
? `__WEBPACK_EXTERNAL_createRequire(${importMetaName}.url)`
: "require",
expr: "require",
req: null,
type: undefined, // type is not known, depends on environment
assign: true
@@ -132,19 +130,7 @@ function getReplacements(module, importMetaName) {
const PLUGIN_NAME = "APIPlugin";
/**
* @typedef {object} APIPluginOptions
* @property {boolean=} module the output filename
*/
class APIPlugin {
/**
* @param {APIPluginOptions=} options options
*/
constructor(options = {}) {
this.options = options;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
@@ -154,13 +140,15 @@ class APIPlugin {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
const importMetaName = /** @type {string} */ (
compilation.outputOptions.importMetaName
);
const REPLACEMENTS = getReplacements(
this.options.module,
importMetaName
);
const moduleOutput = compilation.options.output.module;
const nodeTarget = compiler.platform.node;
const nodeEsm = moduleOutput && nodeTarget;
const REPLACEMENTS = getReplacements();
if (nodeEsm) {
REPLACEMENTS.__non_webpack_require__.expr =
"__WEBPACK_EXTERNAL_createRequire_require";
}
compilation.dependencyTemplates.set(
ConstDependency,
@@ -191,13 +179,8 @@ class APIPlugin {
(source, module, renderContext) => {
if (/** @type {BuildInfo} */ (module.buildInfo).needCreateRequire) {
const chunkInitFragments = [
new InitFragment(
`import { createRequire as __WEBPACK_EXTERNAL_createRequire } from ${renderContext.runtimeTemplate.renderNodePrefixForCoreModule(
"module"
)};\n`,
InitFragment.STAGE_HARMONY_IMPORTS,
0,
"external module node-commonjs"
getExternalModuleNodeCommonjsInitFragment(
renderContext.runtimeTemplate
)
];
@@ -217,9 +200,20 @@ class APIPlugin {
parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expression) => {
const dep = toConstantDependency(parser, info.expr, info.req);
if (key === "__non_webpack_require__" && this.options.module) {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).needCreateRequire = true;
if (key === "__non_webpack_require__" && moduleOutput) {
if (nodeTarget) {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).needCreateRequire = true;
} else {
const warning = new WebpackError(
`${PLUGIN_NAME}\n__non_webpack_require__ is only allowed in target node`
);
warning.loc = /** @type {DependencyLocation} */ (
expression.loc
);
warning.module = parser.state.module;
compilation.warnings.push(warning);
}
}
return dep(expression);

0
node_modules/webpack/lib/AbstractMethodError.js generated vendored Executable file → Normal file
View File

View File

@@ -8,13 +8,10 @@
const DependenciesBlock = require("./DependenciesBlock");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./util/Hash")} Hash */
@@ -41,7 +38,7 @@ class AsyncDependenciesBlock extends DependenciesBlock {
}
/**
* @returns {string | null | undefined} The name of the chunk
* @returns {ChunkGroupOptions["name"]} The name of the chunk
*/
get chunkName() {
return this.groupOptions.name;

View File

@@ -13,7 +13,6 @@ const createSchemaValidation = require("./util/create-schema-validation");
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerFunction} BannerFunction */
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */
/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */
/** @typedef {import("./Compilation").PathData} PathData */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */

13
node_modules/webpack/lib/Cache.js generated vendored
View File

@@ -29,16 +29,17 @@ const {
/** @typedef {EXPECTED_ANY} Data */
/**
* @template T
* @callback GotHandler
* @param {TODO} result
* @param {(err?: Error) => void} callback
* @param {T} result
* @param {() => void} callback
* @returns {void}
*/
/**
* @param {number} times times
* @param {(err?: Error) => void} callback callback
* @returns {(err?: Error) => void} callback
* @param {(err?: Error | null) => void} callback callback
* @returns {(err?: Error | null) => void} callback
*/
const needCalls = (times, callback) => (err) => {
if (--times === 0) {
@@ -53,7 +54,7 @@ const needCalls = (times, callback) => (err) => {
class Cache {
constructor() {
this.hooks = {
/** @type {AsyncSeriesBailHook<[string, Etag | null, GotHandler[]], Data>} */
/** @type {AsyncSeriesBailHook<[string, Etag | null, GotHandler<EXPECTED_ANY>[]], Data>} */
get: new AsyncSeriesBailHook(["identifier", "etag", "gotHandlers"]),
/** @type {AsyncParallelHook<[string, Etag | null, Data]>} */
store: new AsyncParallelHook(["identifier", "etag", "data"]),
@@ -76,7 +77,7 @@ class Cache {
* @returns {void}
*/
get(identifier, etag, callback) {
/** @type {GotHandler[]} */
/** @type {GotHandler<T>[]} */
const gotHandlers = [];
this.hooks.get.callAsync(identifier, etag, gotHandlers, (err, result) => {
if (err) {

View File

@@ -12,7 +12,6 @@ const mergeEtags = require("./cache/mergeEtags");
/** @typedef {import("./Cache")} Cache */
/** @typedef {import("./Cache").Etag} Etag */
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./cache/getLazyHashedEtag").HashableObject} HashableObject */
/** @typedef {typeof import("./util/Hash")} HashConstructor */

80
node_modules/webpack/lib/Chunk.js generated vendored
View File

@@ -18,48 +18,56 @@ const {
const { createArrayToSetDeprecationSet } = require("./util/deprecation");
const { mergeRuntime } = require("./util/runtime");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./ChunkGraph").ChunkFilterPredicate} ChunkFilterPredicate */
/** @typedef {import("./ChunkGraph").ChunkSizeOptions} ChunkSizeOptions */
/** @typedef {import("./ChunkGraph").ModuleFilterPredicate} ModuleFilterPredicate */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./ChunkGroup").ChunkGroupOptions} ChunkGroupOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {string | null} ChunkName */
/** @typedef {number | string} ChunkId */
/** @typedef {string | number} ChunkId */
/** @typedef {SortableSet<string>} IdNameHints */
const ChunkFilesSet = createArrayToSetDeprecationSet("chunk.files");
/**
* @typedef {object} WithId an object who has an id property *
* @property {string | number} id the id of the object
* @deprecated
* @typedef {object} ChunkMaps
* @property {Record<ChunkId, string>} hash
* @property {Record<ChunkId, Record<string, string>>} contentHash
* @property {Record<ChunkId, string>} name
*/
/**
* @deprecated
* @typedef {object} ChunkMaps
* @property {Record<string | number, string>} hash
* @property {Record<string | number, Record<string, string>>} contentHash
* @property {Record<string | number, string>} name
* @typedef {Record<ChunkId, ChunkId[]>} ChunkModuleIdMap
*/
/**
* @deprecated
* @typedef {Record<ModuleId, string>} chunkModuleHashMap
*/
/**
* @deprecated
* @typedef {object} ChunkModuleMaps
* @property {Record<string|number, (string|number)[]>} id
* @property {Record<string|number, string>} hash
* @property {ChunkModuleIdMap} id
* @property {chunkModuleHashMap} hash
*/
/** @typedef {Set<Chunk>} Chunks */
/** @typedef {Set<Entrypoint>} Entrypoints */
/** @typedef {Set<ChunkGroup>} Queue */
/** @typedef {SortableSet<ChunkGroup>} SortableChunkGroups */
/** @typedef {Record<string, ChunkId[]>} ChunkChildIdsByOrdersMap */
/** @typedef {Record<string, ChunkChildIdsByOrdersMap>} ChunkChildIdsByOrdersMapByData */
let debugId = 1000;
/**
@@ -90,7 +98,7 @@ class Chunk {
this.cssFilenameTemplate = undefined;
/**
* @private
* @type {SortableSet<ChunkGroup>}
* @type {SortableChunkGroups}
*/
this._groups = new SortableSet(undefined, compareChunkGroupsByIndex);
/** @type {RuntimeSpec} */
@@ -353,9 +361,9 @@ class Chunk {
"Chunk.getChunkModuleMaps",
"DEP_WEBPACK_CHUNK_GET_CHUNK_MODULE_MAPS"
);
/** @type {Record<string|number, (string|number)[]>} */
/** @type {ChunkModuleIdMap} */
const chunkModuleIdMap = Object.create(null);
/** @type {Record<string|number, string>} */
/** @type {chunkModuleHashMap} */
const chunkModuleHashMap = Object.create(null);
for (const asyncChunk of this.getAllAsyncChunks()) {
@@ -408,11 +416,11 @@ class Chunk {
* @returns {ChunkMaps} the chunk map information
*/
getChunkMaps(realHash) {
/** @type {Record<string|number, string>} */
/** @type {Record<ChunkId, string>} */
const chunkHashMap = Object.create(null);
/** @type {Record<string|number, Record<string, string>>} */
/** @type {Record<string, Record<ChunkId, string>>} */
const chunkContentHashMap = Object.create(null);
/** @type {Record<string|number, string>} */
/** @type {Record<ChunkId, string>} */
const chunkNameMap = Object.create(null);
for (const chunk of this.getAllAsyncChunks()) {
@@ -519,7 +527,7 @@ class Chunk {
}
/**
* @returns {SortableSet<ChunkGroup>} the chunkGroups that the said chunk is referenced in
* @returns {SortableChunkGroups} the chunkGroups that the said chunk is referenced in
*/
get groupsIterable() {
this._groups.sort();
@@ -576,16 +584,19 @@ class Chunk {
}
/**
* @returns {Set<Chunk>} a set of all the async chunks
* @returns {Chunks} a set of all the async chunks
*/
getAllAsyncChunks() {
/** @type {Queue} */
const queue = new Set();
/** @type {Chunks} */
const chunks = new Set();
const initialChunks = intersect(
Array.from(this.groupsIterable, (g) => new Set(g.chunks))
);
/** @type {Queue} */
const initialQueue = new Set(this.groupsIterable);
for (const chunkGroup of initialQueue) {
@@ -613,10 +624,12 @@ class Chunk {
}
/**
* @returns {Set<Chunk>} a set of all the initial chunks (including itself)
* @returns {Chunks} a set of all the initial chunks (including itself)
*/
getAllInitialChunks() {
/** @type {Chunks} */
const chunks = new Set();
/** @type {Queue} */
const queue = new Set(this.groupsIterable);
for (const group of queue) {
if (group.isInitial()) {
@@ -628,10 +641,12 @@ class Chunk {
}
/**
* @returns {Set<Chunk>} a set of all the referenced chunks (including itself)
* @returns {Chunks} a set of all the referenced chunks (including itself)
*/
getAllReferencedChunks() {
/** @type {Queue} */
const queue = new Set(this.groupsIterable);
/** @type {Chunks} */
const chunks = new Set();
for (const chunkGroup of queue) {
@@ -647,15 +662,17 @@ class Chunk {
}
/**
* @returns {Set<Entrypoint>} a set of all the referenced entrypoints
* @returns {Entrypoints} a set of all the referenced entrypoints
*/
getAllReferencedAsyncEntrypoints() {
/** @type {Queue} */
const queue = new Set(this.groupsIterable);
/** @type {Entrypoints} */
const entrypoints = new Set();
for (const chunkGroup of queue) {
for (const entrypoint of chunkGroup.asyncEntrypointsIterable) {
entrypoints.add(entrypoint);
entrypoints.add(/** @type {Entrypoint} */ (entrypoint));
}
for (const child of chunkGroup.childrenIterable) {
queue.add(child);
@@ -669,6 +686,7 @@ class Chunk {
* @returns {boolean} true, if the chunk references async chunks
*/
hasAsyncChunks() {
/** @type {Queue} */
const queue = new Set();
const initialChunks = intersect(
@@ -730,7 +748,7 @@ class Chunk {
}
}
}
/** @type {Record<string, (string | number)[]>} */
/** @type {Record<string, ChunkId[]>} */
const result = Object.create(null);
for (const [name, list] of lists) {
list.sort((a, b) => {
@@ -756,7 +774,7 @@ class Chunk {
/**
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {string} type option name
* @returns {{ onChunks: Chunk[], chunks: Set<Chunk> }[] | undefined} referenced chunks for a specific type
* @returns {{ onChunks: Chunk[], chunks: Chunks }[] | undefined} referenced chunks for a specific type
*/
getChildrenOfTypeInOrder(chunkGraph, type) {
const list = [];
@@ -802,10 +820,10 @@ class Chunk {
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {boolean=} includeDirectChildren include direct children (by default only children of async children are included)
* @param {ChunkFilterPredicate=} filterFn function used to filter chunks
* @returns {Record<string|number, Record<string, (string | number)[]>>} a record object of names to lists of child ids(?) by chunk id
* @returns {ChunkChildIdsByOrdersMapByData} a record object of names to lists of child ids(?) by chunk id
*/
getChildIdsByOrdersMap(chunkGraph, includeDirectChildren, filterFn) {
/** @type {Record<string|number, Record<string, (string | number)[]>>} */
/** @type {ChunkChildIdsByOrdersMapByData} */
const chunkMaps = Object.create(null);
/**
@@ -824,7 +842,7 @@ class Chunk {
};
if (includeDirectChildren) {
/** @type {Set<Chunk>} */
/** @type {Chunks} */
const chunks = new Set();
for (const chunkGroup of this.groupsIterable) {
for (const chunk of chunkGroup.chunks) {
@@ -852,7 +870,7 @@ class Chunk {
*/
hasChildByOrder(chunkGraph, type, includeDirectChildren, filterFn) {
if (includeDirectChildren) {
/** @type {Set<Chunk>} */
/** @type {Chunks} */
const chunks = new Set();
for (const chunkGroup of this.groupsIterable) {
for (const chunk of chunkGroup.chunks) {

View File

@@ -31,6 +31,8 @@ const {
/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Chunk").Chunks} Chunks */
/** @typedef {import("./Chunk").Entrypoints} Entrypoints */
/** @typedef {import("./Chunk").ChunkId} ChunkId */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
@@ -79,7 +81,7 @@ class ModuleHashInfo {
const getArray = (set) => [...set];
/**
* @param {SortableSet<Chunk>} chunks the chunks
* @param {SortableChunks} chunks the chunks
* @returns {RuntimeSpecSet} runtimes
*/
const getModuleRuntimes = (chunks) => {
@@ -91,7 +93,7 @@ const getModuleRuntimes = (chunks) => {
};
/**
* @param {WeakMap<Module, Set<string>> | undefined} sourceTypesByModule sourceTypesByModule
* @param {SourceTypesByModule | undefined} sourceTypesByModule sourceTypesByModule
* @returns {(set: SortableSet<Module>) => Map<string, SortableSet<Module>>} modules by source type
*/
const modulesBySourceType = (sourceTypesByModule) => (set) => {
@@ -192,13 +194,14 @@ const isAvailableChunk = (a, b) => {
return true;
};
/** @typedef {SortableSet<Chunk>} SortableChunks */
/** @typedef {Set<Chunk>} EntryInChunks */
/** @typedef {Set<Chunk>} RuntimeInChunks */
/** @typedef {string | number} ModuleId */
class ChunkGraphModule {
constructor() {
/** @type {SortableSet<Chunk>} */
/** @type {SortableChunks} */
this.chunks = new SortableSet();
/** @type {EntryInChunks | undefined} */
this.entryInChunks = undefined;
@@ -217,13 +220,16 @@ class ChunkGraphModule {
}
}
/** @typedef {WeakMap<Module, Set<string>>} SourceTypesByModule */
/** @typedef {Map<Module, Entrypoint>} EntryModules */
class ChunkGraphChunk {
constructor() {
/** @type {SortableSet<Module>} */
this.modules = new SortableSet();
/** @type {WeakMap<Module, Set<string>> | undefined} */
/** @type {SourceTypesByModule | undefined} */
this.sourceTypesByModule = undefined;
/** @type {Map<Module, Entrypoint>} */
/** @type {EntryModules} */
this.entryModules = new Map();
/** @type {SortableSet<RuntimeModule>} */
this.runtimeModules = new SortableSet();
@@ -231,7 +237,7 @@ class ChunkGraphChunk {
this.fullHashModules = undefined;
/** @type {Set<RuntimeModule> | undefined} */
this.dependentHashModules = undefined;
/** @type {Set<string> | undefined} */
/** @type {RuntimeRequirements | undefined} */
this.runtimeRequirements = undefined;
/** @type {Set<string>} */
this.runtimeRequirementsInTree = new Set();
@@ -240,6 +246,11 @@ class ChunkGraphChunk {
}
}
/** @typedef {string | number} RuntimeId */
/** @typedef {Record<ModuleId, string>} IdToHashMap */
/** @typedef {Record<ChunkId, IdToHashMap>} ChunkModuleHashMap */
/** @typedef {Record<ChunkId, ModuleId[]>} ChunkModuleIdMap */
/** @typedef {(a: Module, b: Module) => -1 | 0 | 1} ModuleComparator */
class ChunkGraph {
@@ -265,7 +276,7 @@ class ChunkGraph {
this._blockChunkGroups = new WeakMap();
/**
* @private
* @type {Map<string, string | number>}
* @type {Map<string, RuntimeId>}
*/
this._runtimeIds = new Map();
/** @type {ModuleGraph} */
@@ -452,7 +463,7 @@ class ChunkGraph {
for (const chunk of oldCgm.entryInChunks) {
const cgc = this._getChunkGraphChunk(chunk);
const old = /** @type {Entrypoint} */ (cgc.entryModules.get(oldModule));
/** @type {Map<Module, Entrypoint>} */
/** @type {EntryModules} */
const newEntryModules = new Map();
for (const [m, cg] of cgc.entryModules) {
if (m === oldModule) {
@@ -740,16 +751,16 @@ class ChunkGraph {
* @param {Chunk} chunk the chunk
* @param {ModuleFilterPredicate} filterFn function used to filter modules
* @param {boolean} includeAllChunks all chunks or only async chunks
* @returns {Record<string|number, (string|number)[]>} chunk to module ids object
* @returns {ChunkModuleIdMap} chunk to module ids object
*/
getChunkModuleIdMap(chunk, filterFn, includeAllChunks = false) {
/** @type {Record<string|number, (string|number)[]>} */
/** @type {ChunkModuleIdMap} */
const chunkModuleIdMap = Object.create(null);
for (const asyncChunk of includeAllChunks
? chunk.getAllReferencedChunks()
: chunk.getAllAsyncChunks()) {
/** @type {(string | number)[] | undefined} */
/** @type {ModuleId[] | undefined} */
let array;
for (const module of this.getOrderedChunkModulesIterable(
asyncChunk,
@@ -774,7 +785,7 @@ class ChunkGraph {
* @param {ModuleFilterPredicate} filterFn function used to filter modules
* @param {number} hashLength length of the hash
* @param {boolean} includeAllChunks all chunks or only async chunks
* @returns {Record<string|number, Record<string|number, string>>} chunk to module id to module hash object
* @returns {ChunkModuleHashMap} chunk to module id to module hash object
*/
getChunkModuleRenderedHashMap(
chunk,
@@ -782,11 +793,9 @@ class ChunkGraph {
hashLength = 0,
includeAllChunks = false
) {
/** @type {Record<ChunkId, Record<string|number, string>>} */
/** @type {ChunkModuleHashMap} */
const chunkModuleHashMap = Object.create(null);
/** @typedef {Record<string|number, string>} IdToHashMap */
for (const asyncChunk of includeAllChunks
? chunk.getAllReferencedChunks()
: chunk.getAllAsyncChunks()) {
@@ -800,7 +809,8 @@ class ChunkGraph {
if (idToHashMap === undefined) {
idToHashMap = Object.create(null);
chunkModuleHashMap[/** @type {ChunkId} */ (asyncChunk.id)] =
/** @type {IdToHashMap} */ (idToHashMap);
/** @type {IdToHashMap} */
(idToHashMap);
}
const moduleId = this.getModuleId(module);
const hash = this.getRenderedModuleHash(module, asyncChunk.runtime);
@@ -818,7 +828,7 @@ class ChunkGraph {
/**
* @param {Chunk} chunk the chunk
* @param {ChunkFilterPredicate} filterFn function used to filter chunks
* @returns {Record<string|number, boolean>} chunk map
* @returns {Record<ChunkId, boolean>} chunk map
*/
getChunkConditionMap(chunk, filterFn) {
const map = Object.create(null);
@@ -1219,7 +1229,7 @@ class ChunkGraph {
* @returns {Iterable<Chunk>} iterable of chunks
*/
getChunkEntryDependentChunksIterable(chunk) {
/** @type {Set<Chunk>} */
/** @type {Chunks} */
const set = new Set();
for (const chunkGroup of chunk.groupsIterable) {
if (chunkGroup instanceof Entrypoint) {
@@ -1243,10 +1253,10 @@ class ChunkGraph {
* @returns {Iterable<Chunk>} iterable of chunks and include chunks from children entrypoints
*/
getRuntimeChunkDependentChunksIterable(chunk) {
/** @type {Set<Chunk>} */
/** @type {Chunks} */
const set = new Set();
/** @type {Set<Entrypoint>} */
/** @type {Entrypoints} */
const entrypoints = new Set();
for (const chunkGroup of chunk.groupsIterable) {
@@ -1423,15 +1433,15 @@ class ChunkGraph {
/**
* @param {string} runtime runtime
* @returns {string | number} the id of the runtime
* @returns {RuntimeId} the id of the runtime
*/
getRuntimeId(runtime) {
return /** @type {string | number} */ (this._runtimeIds.get(runtime));
return /** @type {RuntimeId} */ (this._runtimeIds.get(runtime));
}
/**
* @param {string} runtime runtime
* @param {string | number} id the id of the runtime
* @param {RuntimeId} id the id of the runtime
* @returns {void}
*/
setRuntimeId(runtime, id) {
@@ -1531,7 +1541,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
/**
* @param {Module} module the module
* @param {RuntimeSpec} runtime the runtime
* @param {Set<string>} items runtime requirements to be added (ownership of this Set is given to ChunkGraph when transferOwnership not false)
* @param {RuntimeRequirements} items runtime requirements to be added (ownership of this Set is given to ChunkGraph when transferOwnership not false)
* @param {boolean} transferOwnership true: transfer ownership of the items object, false: items is immutable and shared and won't be modified
* @returns {void}
*/
@@ -1565,7 +1575,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
/**
* @param {Chunk} chunk the chunk
* @param {Set<string>} items runtime requirements to be added (ownership of this Set is given to ChunkGraph)
* @param {RuntimeRequirements} items runtime requirements to be added (ownership of this Set is given to ChunkGraph)
* @returns {void}
*/
addChunkRuntimeRequirements(chunk, items) {
@@ -1660,7 +1670,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
for (const type of sourceTypes) hash.update(type);
}
this.moduleGraph.getExportsInfo(module).updateHash(hash, runtime);
return BigInt(`0x${/** @type {string} */ (hash.digest("hex"))}`);
return BigInt(`0x${hash.digest("hex")}`);
});
return graphHash;
}
@@ -1798,7 +1808,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
}
}
hash.update(graphHash);
return /** @type {string} */ (hash.digest("hex"));
return hash.digest("hex");
});
}

View File

@@ -21,8 +21,7 @@ const {
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {{id: number}} HasId */
/** @typedef {{module: Module | null, loc: DependencyLocation, request: string}} OriginRecord */
/** @typedef {{ module: Module | null, loc: DependencyLocation, request: string }} OriginRecord */
/**
* @typedef {object} RawChunkGroupOptions
@@ -114,13 +113,12 @@ class ChunkGroup {
* @returns {void}
*/
addOptions(options) {
for (const _key of Object.keys(options)) {
const key =
/** @type {keyof ChunkGroupOptions} */
(_key);
for (const key of /** @type {(keyof ChunkGroupOptions)[]} */ (
Object.keys(options)
)) {
if (this.options[key] === undefined) {
/** @type {EXPECTED_ANY} */
(this.options)[key] = options[key];
/** @type {ChunkGroupOptions[keyof ChunkGroupOptions]} */
(this.options[key]) = options[key];
} else if (this.options[key] !== options[key]) {
if (key.endsWith("Order")) {
const orderKey =
@@ -144,7 +142,7 @@ class ChunkGroup {
/**
* returns the name of current ChunkGroup
* @returns {string | null | undefined} returns the ChunkGroup name
* @returns {ChunkGroupOptions["name"]} returns the ChunkGroup name
*/
get name() {
return this.options.name;
@@ -373,7 +371,7 @@ class ChunkGroup {
}
/**
* @returns {Array<AsyncDependenciesBlock>} an array containing the blocks
* @returns {AsyncDependenciesBlock[]} an array containing the blocks
*/
getBlocks() {
return this._blocks.getFromCache(getArray);

View File

@@ -9,7 +9,7 @@ const util = require("util");
const memoize = require("./util/memoize");
/** @typedef {import("tapable").Tap} Tap */
/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */
/** @typedef {import("./config/defaults").OutputNormalizedWithDefaults} OutputOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").ChunkHashContext} ChunkHashContext */

View File

@@ -30,7 +30,7 @@ const processAsyncTree = require("./util/processAsyncTree");
/**
* @callback KeepFn
* @param {string} path path
* @returns {boolean | void} true, if the path should be kept
* @returns {boolean | undefined} true, if the path should be kept
*/
const validate = createSchemaValidation(
@@ -170,7 +170,7 @@ const doStat = (fs, filename, callback) => {
* @param {boolean} dry only log instead of fs modification
* @param {Logger} logger logger
* @param {Diff} diff filenames of the assets that shouldn't be there
* @param {(path: string) => boolean | void} isKept check if the entry is ignored
* @param {KeepFn} isKept check if the entry is ignored
* @param {(err?: Error, assets?: Assets) => void} callback callback
* @returns {void}
*/
@@ -436,7 +436,7 @@ class CleanPlugin {
/**
* @param {string} path path
* @returns {boolean | void} true, if needs to be kept
* @returns {boolean | undefined} true, if needs to be kept
*/
const isKept = (path) => {
const result = hooks.keep.call(path);

View File

@@ -14,6 +14,7 @@ const { RuntimeSpecMap, runtimeToString } = require("./util/runtime");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").CodeGenerationResultData} CodeGenerationResultData */
/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
/** @typedef {typeof import("./util/Hash")} Hash */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
@@ -117,7 +118,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
* @param {Module} module the module
* @param {RuntimeSpec} runtime runtime(s)
* @param {string} key data key
* @returns {TODO | undefined} data generated by code generation
* @returns {ReturnType<CodeGenerationResultData["get"]>} data generated by code generation
*/
getData(module, runtime, key) {
const data = this.get(module, runtime).data;
@@ -140,7 +141,7 @@ Caller might not support runtime-dependent code generation (opt-out via optimiza
if (info.runtimeRequirements) {
for (const rr of info.runtimeRequirements) hash.update(rr);
}
return (info.hash = /** @type {string} */ (hash.digest("hex")));
return (info.hash = hash.digest("hex"));
}
/**

View File

@@ -16,9 +16,22 @@ const ConstDependency = require("./dependencies/ConstDependency");
/** @typedef {import("estree").CallExpression} CallExpression */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./dependencies/ContextDependency")} ContextDependency */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/** @typedef {import("./javascript/JavascriptParser").TagData} TagData */
/**
* @typedef {object} CompatibilitySettingsDeclaration
* @property {boolean} updated
* @property {DependencyLocation} loc
* @property {Range} range
*/
/**
* @typedef {object} CompatibilitySettings
* @property {string} name
* @property {CompatibilitySettingsDeclaration} declaration
*/
const nestedWebpackIdentifierTag = Symbol("nested webpack identifier");
const PLUGIN_NAME = "CompatibilityPlugin";
@@ -67,9 +80,12 @@ class CompatibilityPlugin {
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
if (parser.state.current.dependencies.length > 0) {
const last =
parser.state.current.dependencies[
parser.state.current.dependencies.length - 1
];
/** @type {ContextDependency} */
(
parser.state.current.dependencies[
parser.state.current.dependencies.length - 1
]
);
if (
last.critical &&
last.options &&
@@ -99,7 +115,8 @@ class CompatibilityPlugin {
statement.id.name === RuntimeGlobals.require
) {
const newName = `__nested_webpack_require_${
/** @type {Range} */ (statement.range)[0]
/** @type {Range} */
(statement.range)[0]
}__`;
parser.tagVariable(
statement.id.name,
@@ -108,8 +125,8 @@ class CompatibilityPlugin {
name: newName,
declaration: {
updated: false,
loc: statement.id.loc,
range: statement.id.range
loc: /** @type {DependencyLocation} */ (statement.id.loc),
range: /** @type {Range} */ (statement.id.range)
}
}
);
@@ -126,8 +143,8 @@ class CompatibilityPlugin {
name: newName,
declaration: {
updated: false,
loc: pattern.loc,
range: pattern.range
loc: /** @type {DependencyLocation} */ (pattern.loc),
range: /** @type {Range} */ (pattern.range)
}
});
return true;
@@ -139,8 +156,8 @@ class CompatibilityPlugin {
name: "__nested_webpack_exports__",
declaration: {
updated: false,
loc: pattern.loc,
range: pattern.range
loc: /** @type {DependencyLocation} */ (pattern.loc),
range: /** @type {Range} */ (pattern.range)
}
});
return true;
@@ -149,7 +166,7 @@ class CompatibilityPlugin {
.for(nestedWebpackIdentifierTag)
.tap(PLUGIN_NAME, (expr) => {
const { name, declaration } =
/** @type {TagData} */
/** @type {CompatibilitySettings} */
(parser.currentTagData);
if (!declaration.updated) {
const dep = new ConstDependency(name, declaration.range);

View File

@@ -86,12 +86,14 @@ const { isSourceEqual } = require("./util/source");
/** @template T @typedef {import("tapable").AsArray<T>} AsArray<T> */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */
/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */
/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
/** @typedef {import("../declarations/WebpackOptions").HashDigest} HashDigest */
/** @typedef {import("../declarations/WebpackOptions").HashDigestLength} HashDigestLength */
/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */
/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */
/** @typedef {import("../declarations/WebpackOptions").Plugins} Plugins */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./config/defaults").OutputNormalizedWithDefaults} OutputOptionsWithDefaults */
/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("./Cache")} Cache */
/** @typedef {import("./CacheFacade")} CacheFacade */
@@ -106,9 +108,9 @@ const { isSourceEqual } = require("./util/source");
/** @typedef {import("./Compiler").Records} Records */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */
/** @typedef {import("./DependencyTemplate")} DependencyTemplate */
/** @typedef {import("./Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
/** @typedef {import("./Module").NameForCondition} NameForCondition */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */
/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
@@ -132,13 +134,13 @@ const { isSourceEqual } = require("./util/source");
/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsModule} StatsModule */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
/**
* @template T
* @typedef {import("./util/deprecation").FakeHook<T>} FakeHook<T>
*/
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/**
* @callback Callback
* @param {(WebpackError | null)=} err
@@ -147,33 +149,33 @@ const { isSourceEqual } = require("./util/source");
/**
* @callback ModuleCallback
* @param {(WebpackError | null)=} err
* @param {(Module | null)=} result
* @param {WebpackError | null=} err
* @param {Module | null=} result
* @returns {void}
*/
/**
* @callback ModuleFactoryResultCallback
* @param {(WebpackError | null)=} err
* @param {ModuleFactoryResult=} result
* @param {WebpackError | null=} err
* @param {ModuleFactoryResult | null=} result
* @returns {void}
*/
/**
* @callback ModuleOrFactoryResultCallback
* @param {(WebpackError | null)=} err
* @param {Module | ModuleFactoryResult=} result
* @callback ModuleOrModuleFactoryResultCallback
* @param {WebpackError | null=} err
* @param {Module | ModuleFactoryResult | null=} result
* @returns {void}
*/
/**
* @callback ExecuteModuleCallback
* @param {WebpackError | null} err
* @param {ExecuteModuleResult=} result
* @param {WebpackError | null=} err
* @param {ExecuteModuleResult | null=} result
* @returns {void}
*/
/** @typedef {new (...args: EXPECTED_ANY[]) => Dependency} DepConstructor */
/** @typedef {new (...args: EXPECTED_ANY[]) => Dependency} DependencyConstructor */
/** @typedef {Record<string, Source>} CompilationAssets */
@@ -190,6 +192,8 @@ const { isSourceEqual } = require("./util/source");
* @property {AsyncDependenciesBlock[]} blocks
*/
/** @typedef {Set<Chunk>} Chunks */
/**
* @typedef {object} ChunkPathData
* @property {string | number} id
@@ -244,7 +248,6 @@ const { isSourceEqual } = require("./util/source");
* @typedef {object} ExecuteModuleArgument
* @property {Module} module
* @property {ExecuteModuleObject=} moduleObject
* @property {TODO} preparedInfo
* @property {CodeGenerationResult} codeGenerationResult
*/
@@ -479,7 +482,7 @@ const unsafeCacheDependencies = new WeakMap();
/** @type {WeakMap<ModuleWithRestoreFromUnsafeCache, UnsafeCacheData>} */
const unsafeCacheData = new WeakMap();
/** @typedef {{ id: ModuleId, modules?: Map<Module, string | number | undefined>, blocks?: (string | number | null)[] }} References */
/** @typedef {{ id: ModuleId, modules?: Map<Module, ModuleId>, blocks?: (ChunkId | null)[] }} References */
/** @typedef {Map<Module, WeakTupleMap<EXPECTED_ANY[], EXPECTED_ANY>>} ModuleMemCaches */
class Compilation {
@@ -492,7 +495,7 @@ class Compilation {
this._backCompat = compiler._backCompat;
const getNormalModuleLoader = () => deprecatedNormalModuleLoaderHook(this);
/** @typedef {{ additionalAssets?: true | TODO }} ProcessAssetsAdditionalOptions */
/** @typedef {{ additionalAssets?: boolean | ((assets: CompilationAssets) => void) }} ProcessAssetsAdditionalOptions */
/** @type {AsyncSeriesHook<[CompilationAssets], ProcessAssetsAdditionalOptions>} */
const processAssetsHook = new AsyncSeriesHook(["assets"]);
@@ -718,7 +721,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
processAssetsHook.tapAsync(
getOptions(options),
(assets, callback) =>
/** @type {TODO} */ (fn)(...getArgs(), callback)
/** @type {EXPECTED_ANY} */ (fn)(...getArgs(), callback)
);
},
/** @type {AsyncSeriesHook<T>["tapPromise"]} */
@@ -751,7 +754,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
/** @type {SyncHook<[Dependency, EntryOptions, Module]>} */
succeedEntry: new SyncHook(["entry", "options", "module"]),
/** @type {SyncWaterfallHook<[(string[] | ReferencedExport)[], Dependency, RuntimeSpec]>} */
/** @type {SyncWaterfallHook<[ReferencedExports, Dependency, RuntimeSpec]>} */
dependencyReferencedExports: new SyncWaterfallHook([
"referencedExports",
"dependency",
@@ -811,33 +814,33 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
/** @type {SyncBailHook<[], boolean | void>} */
shouldRecord: new SyncBailHook([]),
/** @type {SyncHook<[Chunk, Set<string>, RuntimeRequirementsContext]>} */
/** @type {SyncHook<[Chunk, RuntimeRequirements, RuntimeRequirementsContext]>} */
additionalChunkRuntimeRequirements: new SyncHook([
"chunk",
"runtimeRequirements",
"context"
]),
/** @type {HookMap<SyncBailHook<[Chunk, Set<string>, RuntimeRequirementsContext], void>>} */
/** @type {HookMap<SyncBailHook<[Chunk, RuntimeRequirements, RuntimeRequirementsContext], void>>} */
runtimeRequirementInChunk: new HookMap(
() => new SyncBailHook(["chunk", "runtimeRequirements", "context"])
),
/** @type {SyncHook<[Module, Set<string>, RuntimeRequirementsContext]>} */
/** @type {SyncHook<[Module, RuntimeRequirements, RuntimeRequirementsContext]>} */
additionalModuleRuntimeRequirements: new SyncHook([
"module",
"runtimeRequirements",
"context"
]),
/** @type {HookMap<SyncBailHook<[Module, Set<string>, RuntimeRequirementsContext], void>>} */
/** @type {HookMap<SyncBailHook<[Module, RuntimeRequirements, RuntimeRequirementsContext], void>>} */
runtimeRequirementInModule: new HookMap(
() => new SyncBailHook(["module", "runtimeRequirements", "context"])
),
/** @type {SyncHook<[Chunk, Set<string>, RuntimeRequirementsContext]>} */
/** @type {SyncHook<[Chunk, RuntimeRequirements, RuntimeRequirementsContext]>} */
additionalTreeRuntimeRequirements: new SyncHook([
"chunk",
"runtimeRequirements",
"context"
]),
/** @type {HookMap<SyncBailHook<[Chunk, Set<string>, RuntimeRequirementsContext], void>>} */
/** @type {HookMap<SyncBailHook<[Chunk, RuntimeRequirements, RuntimeRequirementsContext], void>>} */
runtimeRequirementInTree: new HookMap(
() => new SyncBailHook(["chunk", "runtimeRequirements", "context"])
),
@@ -910,7 +913,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
// TODO webpack 6 remove
/** @deprecated */
additionalChunkAssets:
/** @type {FakeHook<Pick<AsyncSeriesHook<[Set<Chunk>]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
/** @type {FakeHook<Pick<AsyncSeriesHook<[Chunks]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
(
createProcessAssetsHook(
"additionalChunkAssets",
@@ -934,7 +937,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
// TODO webpack 6 remove
/** @deprecated */
optimizeChunkAssets:
/** @type {FakeHook<Pick<AsyncSeriesHook<[Set<Chunk>]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
/** @type {FakeHook<Pick<AsyncSeriesHook<[Chunks]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
(
createProcessAssetsHook(
"optimizeChunkAssets",
@@ -946,7 +949,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
// TODO webpack 6 remove
/** @deprecated */
afterOptimizeChunkAssets:
/** @type {FakeHook<Pick<AsyncSeriesHook<[Set<Chunk>]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
/** @type {FakeHook<Pick<AsyncSeriesHook<[Chunks]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
(
createProcessAssetsHook(
"afterOptimizeChunkAssets",
@@ -1057,7 +1060,9 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
const options = /** @type {WebpackOptions} */ (compiler.options);
this.options = options;
this.outputOptions = options && options.output;
this.outputOptions =
/** @type {OutputOptionsWithDefaults} */
(options && options.output);
/** @type {boolean} */
this.bail = (options && options.bail) || false;
/** @type {boolean} */
@@ -1082,11 +1087,15 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
this.moduleMemCaches = undefined;
/** @type {ModuleMemCaches | undefined} */
this.moduleMemCaches2 = undefined;
/** @type {ModuleGraph} */
this.moduleGraph = new ModuleGraph();
/** @type {ChunkGraph} */
this.chunkGraph = /** @type {TODO} */ (undefined);
/** @type {CodeGenerationResults} */
this.codeGenerationResults = /** @type {TODO} */ (undefined);
this.chunkGraph = new ChunkGraph(
this.moduleGraph,
this.outputOptions.hashFunction
);
/** @type {CodeGenerationResults | undefined} */
this.codeGenerationResults = undefined;
/** @type {AsyncQueue<Module, Module, Module>} */
this.processDependenciesQueue = new AsyncQueue({
@@ -1142,7 +1151,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
this.entrypoints = new Map();
/** @type {Entrypoint[]} */
this.asyncEntrypoints = [];
/** @type {Set<Chunk>} */
/** @type {Chunks} */
this.chunks = new Set();
/** @type {ChunkGroup[]} */
this.chunkGroups = [];
@@ -1179,7 +1188,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
this.children = [];
/** @type {Map<string, LogEntry[]>} */
this.logging = new Map();
/** @type {Map<DepConstructor, ModuleFactory>} */
/** @type {Map<DependencyConstructor, ModuleFactory>} */
this.dependencyFactories = new Map();
/** @type {DependencyTemplates} */
this.dependencyTemplates = new DependencyTemplates(
@@ -1187,7 +1196,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
);
/** @type {Record<string, number>} */
this.childrenCounters = {};
/** @type {Set<number|string> | null} */
/** @type {Set<number> | null} */
this.usedChunkIds = null;
/** @type {Set<number> | null} */
this.usedModuleIds = null;
@@ -1624,7 +1633,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
* @returns {void}
*/
_processModuleDependencies(module, callback) {
/** @type {Array<{factory: ModuleFactory, dependencies: Dependency[], context: string|undefined, originModule: Module|null}>} */
/** @type {{ factory: ModuleFactory, dependencies: Dependency[], context: string | undefined, originModule: Module | null }[]} */
const sortedDependencies = [];
/** @type {DependenciesBlock} */
@@ -1632,7 +1641,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
/** @type {Map<ModuleFactory, Map<string, Dependency[]>>} */
let dependencies;
/** @type {DepConstructor} */
/** @type {DependencyConstructor} */
let factoryCacheKey;
/** @type {ModuleFactory} */
let factoryCacheKey2;
@@ -1815,7 +1824,9 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
const resourceIdent = dep.getResourceIdentifier();
if (resourceIdent !== undefined && resourceIdent !== null) {
const category = dep.category;
const constructor = /** @type {DepConstructor} */ (dep.constructor);
const constructor =
/** @type {DependencyConstructor} */
(dep.constructor);
if (factoryCacheKey === constructor) {
// Fast path 1: same constructor as prev item
if (listCacheKey1 === category && listCacheKey2 === resourceIdent) {
@@ -1950,6 +1961,116 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
moduleGraph.setResolvedModule(originModule, dependency, module);
}
/**
* @param {FactorizeModuleOptions} options options
* @param {ModuleOrModuleFactoryResultCallback} callback callback
* @returns {void}
*/
_factorizeModule(
{
currentProfile,
factory,
dependencies,
originModule,
factoryResult,
contextInfo,
context
},
callback
) {
if (currentProfile !== undefined) {
currentProfile.markFactoryStart();
}
factory.create(
{
contextInfo: {
issuer: originModule
? /** @type {NameForCondition} */ (originModule.nameForCondition())
: "",
issuerLayer: originModule ? originModule.layer : null,
compiler: this.compiler.name,
...contextInfo
},
resolveOptions: originModule ? originModule.resolveOptions : undefined,
context:
context ||
(originModule
? /** @type {string} */ (originModule.context)
: this.compiler.context),
dependencies
},
(err, result) => {
if (result) {
// TODO webpack 6: remove
// For backward-compat
if (result.module === undefined && result instanceof Module) {
result = {
module: result
};
}
if (!factoryResult) {
const {
fileDependencies,
contextDependencies,
missingDependencies
} = result;
if (fileDependencies) {
this.fileDependencies.addAll(fileDependencies);
}
if (contextDependencies) {
this.contextDependencies.addAll(contextDependencies);
}
if (missingDependencies) {
this.missingDependencies.addAll(missingDependencies);
}
}
}
if (err) {
const notFoundError = new ModuleNotFoundError(
originModule,
err,
/** @type {DependencyLocation} */
(dependencies.map((d) => d.loc).find(Boolean))
);
return callback(notFoundError, factoryResult ? result : undefined);
}
if (!result) {
return callback();
}
if (currentProfile !== undefined) {
currentProfile.markFactoryEnd();
}
callback(null, factoryResult ? result : result.module);
}
);
}
/**
* @overload
* @param {FactorizeModuleOptions & { factoryResult?: false }} options options
* @param {ModuleCallback} callback callback
* @returns {void}
*/
/**
* @overload
* @param {FactorizeModuleOptions & { factoryResult: true }} options options
* @param {ModuleFactoryResultCallback} callback callback
* @returns {void}
*/
/**
* @param {FactorizeModuleOptions & { factoryResult?: false } | FactorizeModuleOptions & { factoryResult: true }} options options
* @param {ModuleCallback | ModuleFactoryResultCallback} callback callback
*/
factorizeModule(options, callback) {
this.factorizeQueue.add(
options,
/** @type {ModuleOrModuleFactoryResultCallback} */
(callback)
);
}
/**
* @typedef {object} HandleModuleCreationOptions
* @property {ModuleFactory} factory
@@ -2197,92 +2318,6 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
});
}
/**
* @param {FactorizeModuleOptions} options options object
* @param {ModuleOrFactoryResultCallback} callback callback
* @returns {void}
*/
_factorizeModule(
{
currentProfile,
factory,
dependencies,
originModule,
factoryResult,
contextInfo,
context
},
callback
) {
if (currentProfile !== undefined) {
currentProfile.markFactoryStart();
}
factory.create(
{
contextInfo: {
issuer: originModule
? /** @type {string} */ (originModule.nameForCondition())
: "",
issuerLayer: originModule ? originModule.layer : null,
compiler: /** @type {string} */ (this.compiler.name),
...contextInfo
},
resolveOptions: originModule ? originModule.resolveOptions : undefined,
context:
context ||
(originModule
? /** @type {string} */ (originModule.context)
: /** @type {string} */ (this.compiler.context)),
dependencies
},
(err, result) => {
if (result) {
// TODO webpack 6: remove
// For backward-compat
if (result.module === undefined && result instanceof Module) {
result = {
module: result
};
}
if (!factoryResult) {
const {
fileDependencies,
contextDependencies,
missingDependencies
} = result;
if (fileDependencies) {
this.fileDependencies.addAll(fileDependencies);
}
if (contextDependencies) {
this.contextDependencies.addAll(contextDependencies);
}
if (missingDependencies) {
this.missingDependencies.addAll(missingDependencies);
}
}
}
if (err) {
const notFoundError = new ModuleNotFoundError(
originModule,
err,
/** @type {DependencyLocation} */
(dependencies.map((d) => d.loc).find(Boolean))
);
return callback(notFoundError, factoryResult ? result : undefined);
}
if (!result) {
return callback();
}
if (currentProfile !== undefined) {
currentProfile.markFactoryEnd();
}
callback(null, factoryResult ? result : result.module);
}
);
}
/**
* @param {string} context context string path
* @param {Dependency} dependency dependency used to create Module chain
@@ -2311,7 +2346,9 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
new WebpackError("Parameter 'dependency' must be a Dependency")
);
}
const Dep = /** @type {DepConstructor} */ (dependency.constructor);
const Dep =
/** @type {DependencyConstructor} */
(dependency.constructor);
const moduleFactory = this.dependencyFactories.get(Dep);
if (!moduleFactory) {
return callback(
@@ -2409,8 +2446,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
);
} else {
entryData[target].push(entry);
for (const _key of Object.keys(options)) {
const key = /** @type {keyof EntryOptions} */ (_key);
for (const key_ of Object.keys(options)) {
const key = /** @type {keyof EntryOptions} */ (key_);
if (options[key] === undefined) continue;
if (entryData.options[key] === options[key]) continue;
if (
@@ -2421,10 +2458,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
continue;
}
if (entryData.options[key] === undefined) {
/** @type {TODO} */
(entryData.options)[key] =
/** @type {NonNullable<EntryOptions[keyof EntryOptions]>} */
(options[key]);
/** @type {EntryOptions[keyof EntryOptions]} */
(entryData.options[key]) = options[key];
} else {
return callback(
new WebpackError(
@@ -2629,8 +2664,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
}
/**
* @param {readonly ModuleGraphConnection[]} connections connections
* @returns {symbol|boolean} result
* @param {Readonly<ModuleGraphConnection[]>} connections connections
* @returns {symbol | boolean} result
*/
const reduceAffectType = (connections) => {
let affected = false;
@@ -2714,9 +2749,9 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
*/
const computeReferences = (module) => {
const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module));
/** @type {Map<Module, string | number | undefined> | undefined} */
/** @type {Map<Module, ModuleId> | undefined} */
let modules;
/** @type {(string | number | null)[] | undefined} */
/** @type {(ChunkId | null)[] | undefined} */
let blocks;
const outgoing = moduleGraph.getOutgoingConnectionsByModule(module);
if (outgoing !== undefined) {
@@ -3097,15 +3132,10 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
this.addModuleQueue.clear();
return callback(err);
};
const chunkGraph = new ChunkGraph(
this.moduleGraph,
this.outputOptions.hashFunction
);
this.chunkGraph = chunkGraph;
if (this._backCompat) {
for (const module of this.modules) {
ChunkGraph.setChunkGraphForModule(module, chunkGraph);
ChunkGraph.setChunkGraphForModule(module, this.chunkGraph);
}
}
@@ -3150,7 +3180,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
const module = this.moduleGraph.getModule(dep);
if (module) {
chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint);
this.chunkGraph.connectChunkAndEntryModule(chunk, module, entrypoint);
entryModules.add(module);
const modulesList = chunkGraphInit.get(entrypoint);
if (modulesList === undefined) {
@@ -3549,7 +3579,9 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
let statModulesGenerated = 0;
const { chunkGraph, moduleGraph, dependencyTemplates, runtimeTemplate } =
this;
const results = this.codeGenerationResults;
const results =
/** @type {CodeGenerationResults} */
(this.codeGenerationResults);
/** @type {WebpackError[]} */
const errors = [];
/** @type {NotCodeGeneratedModules | undefined} */
@@ -3560,8 +3592,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
let delayedModules = new Set();
asyncLib.eachLimit(
jobs,
/** @type {number} */
(this.options.parallelism),
this.options.parallelism,
(job, callback) => {
const { module } = job;
const { codeGenerationDependencies } = module;
@@ -3745,7 +3776,9 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
chunkGraph = this.chunkGraph,
modules = this.modules,
chunks = this.chunks,
codeGenerationResults = this.codeGenerationResults,
codeGenerationResults = /** @type {CodeGenerationResults} */ (
this.codeGenerationResults
),
chunkGraphEntries = this._getChunkGraphEntries()
} = {}) {
const context = { chunkGraph, codeGenerationResults };
@@ -3825,6 +3858,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
this.logger.time("runtime requirements.chunks");
for (const chunk of chunks) {
/** @type {RuntimeRequirements} */
const set = new Set();
for (const module of chunkGraph.getChunkModulesIterable(chunk)) {
const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements(
@@ -3845,6 +3879,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
this.logger.time("runtime requirements.entries");
for (const treeEntry of chunkGraphEntries) {
/** @type {RuntimeRequirements} */
const set = new Set();
for (const chunk of treeEntry.getAllReferencedChunks()) {
const runtimeRequirements =
@@ -3984,12 +4019,10 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
if (name) {
const entrypoint = this.namedChunkGroups.get(name);
if (entrypoint instanceof Entrypoint) {
if (entrypoint !== undefined) {
if (module) {
entrypoint.addOrigin(module, loc, request);
}
return entrypoint;
if (module) {
entrypoint.addOrigin(module, loc, request);
}
return entrypoint;
} else if (entrypoint) {
throw new Error(
`Cannot add an async entrypoint with the name '${name}', because there is already an chunk group with this name`
@@ -4112,7 +4145,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
/**
* @param {Dependency} dependency the dependency
* @param {RuntimeSpec} runtime the runtime
* @returns {(string[] | ReferencedExport)[]} referenced exports
* @returns {ReferencedExports} referenced exports
*/
getDependencyReferencedExports(dependency, runtime) {
const referencedExports = dependency.getReferencedExports(
@@ -4320,10 +4353,10 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
* @param {Module} module module
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {RuntimeSpec} runtime runtime
* @param {OutputOptions["hashFunction"]} hashFunction hash function
* @param {HashFunction} hashFunction hash function
* @param {RuntimeTemplate} runtimeTemplate runtime template
* @param {OutputOptions["hashDigest"]} hashDigest hash digest
* @param {OutputOptions["hashDigestLength"]} hashDigestLength hash digest length
* @param {HashDigest} hashDigest hash digest
* @param {HashDigestLength} hashDigestLength hash digest length
* @param {WebpackError[]} errors errors
* @returns {string} module hash digest
*/
@@ -4339,13 +4372,13 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
) {
let moduleHashDigest;
try {
const moduleHash = createHash(/** @type {HashFunction} */ (hashFunction));
const moduleHash = createHash(hashFunction);
module.updateHash(moduleHash, {
chunkGraph,
runtime,
runtimeTemplate
});
moduleHashDigest = /** @type {string} */ (moduleHash.digest(hashDigest));
moduleHashDigest = moduleHash.digest(hashDigest);
} catch (err) {
errors.push(new ModuleHashingError(module, /** @type {Error} */ (err)));
moduleHashDigest = "XXXXXX";
@@ -4367,7 +4400,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
const hashFunction = outputOptions.hashFunction;
const hashDigest = outputOptions.hashDigest;
const hashDigestLength = outputOptions.hashDigestLength;
const hash = createHash(/** @type {HashFunction} */ (hashFunction));
const hash = createHash(hashFunction);
if (outputOptions.hashSalt) {
hash.update(outputOptions.hashSalt);
}
@@ -4555,22 +4588,20 @@ This prevents using hashes of each other and should be avoided.`);
this.logger.timeAggregate("hashing: hash runtime modules");
try {
this.logger.time("hashing: hash chunks");
const chunkHash = createHash(
/** @type {HashFunction} */ (hashFunction)
);
const chunkHash = createHash(hashFunction);
if (outputOptions.hashSalt) {
chunkHash.update(outputOptions.hashSalt);
}
chunk.updateHash(chunkHash, chunkGraph);
this.hooks.chunkHash.call(chunk, chunkHash, {
chunkGraph,
codeGenerationResults: this.codeGenerationResults,
codeGenerationResults:
/** @type {CodeGenerationResults} */
(this.codeGenerationResults),
moduleGraph: this.moduleGraph,
runtimeTemplate: this.runtimeTemplate
});
const chunkHashDigest = /** @type {string} */ (
chunkHash.digest(hashDigest)
);
const chunkHashDigest = chunkHash.digest(hashDigest);
hash.update(chunkHashDigest);
chunk.hash = chunkHashDigest;
chunk.renderedHash = chunk.hash.slice(0, hashDigestLength);
@@ -4604,7 +4635,7 @@ This prevents using hashes of each other and should be avoided.`);
this.logger.timeAggregateEnd("hashing: hash chunks");
this.logger.time("hashing: hash digest");
this.hooks.fullHash.call(hash);
this.fullHash = /** @type {string} */ (hash.digest(hashDigest));
this.fullHash = hash.digest(hashDigest);
this.hash = this.fullHash.slice(0, hashDigestLength);
this.logger.timeEnd("hashing: hash digest");
@@ -4613,17 +4644,13 @@ This prevents using hashes of each other and should be avoided.`);
for (const module of /** @type {Iterable<RuntimeModule>} */ (
chunkGraph.getChunkFullHashModulesIterable(chunk)
)) {
const moduleHash = createHash(
/** @type {HashFunction} */ (hashFunction)
);
const moduleHash = createHash(hashFunction);
module.updateHash(moduleHash, {
chunkGraph,
runtime: chunk.runtime,
runtimeTemplate
});
const moduleHashDigest = /** @type {string} */ (
moduleHash.digest(hashDigest)
);
const moduleHashDigest = moduleHash.digest(hashDigest);
const oldHash = chunkGraph.getModuleHash(module, chunk.runtime);
chunkGraph.setModuleHashes(
module,
@@ -4637,12 +4664,10 @@ This prevents using hashes of each other and should be avoided.`);
(codeGenerationJobsMap.get(oldHash)).get(module)
).hash = moduleHashDigest;
}
const chunkHash = createHash(/** @type {HashFunction} */ (hashFunction));
const chunkHash = createHash(hashFunction);
chunkHash.update(chunk.hash);
chunkHash.update(this.hash);
const chunkHashDigest =
/** @type {string} */
(chunkHash.digest(hashDigest));
const chunkHashDigest = chunkHash.digest(hashDigest);
chunk.hash = chunkHashDigest;
chunk.renderedHash = chunk.hash.slice(0, hashDigestLength);
this.hooks.contentHash.call(chunk);
@@ -4980,7 +5005,9 @@ This prevents using hashes of each other and should be avoided.`);
hash: /** @type {string} */ (this.hash),
fullHash: /** @type {string} */ (this.fullHash),
outputOptions,
codeGenerationResults: this.codeGenerationResults,
codeGenerationResults:
/** @type {CodeGenerationResults} */
(this.codeGenerationResults),
moduleTemplates: this.moduleTemplates,
dependencyTemplates: this.dependencyTemplates,
chunkGraph: this.chunkGraph,
@@ -5193,7 +5220,7 @@ This prevents using hashes of each other and should be avoided.`);
* from parent (or top level compiler) and creates a child Compilation
* @param {string} name name of the child compiler
* @param {Partial<OutputOptions>=} outputOptions // Need to convert config schema to types for this
* @param {Array<WebpackPluginInstance | WebpackPluginFunction>=} plugins webpack plugins that will be applied
* @param {Plugins=} plugins webpack plugins that will be applied
* @returns {Compiler} creates a child Compiler instance
*/
createChildCompiler(name, outputOptions, plugins) {
@@ -5408,7 +5435,6 @@ This prevents using hashes of each other and should be avoided.`);
const moduleArgument = {
module,
codeGenerationResult,
preparedInfo: undefined,
moduleObject: undefined
};
moduleArgumentsMap.set(module, moduleArgument);
@@ -5584,7 +5610,7 @@ This prevents using hashes of each other and should be avoided.`);
checkConstraints() {
const chunkGraph = this.chunkGraph;
/** @type {Set<number|string>} */
/** @type {Set<ModuleId>} */
const usedIds = new Set();
for (const module of this.modules) {
@@ -5639,19 +5665,6 @@ This prevents using hashes of each other and should be avoided.`);
* @returns {void}
*/
// Workaround for typescript as it doesn't support function overloading in jsdoc within a class
/* eslint-disable jsdoc/require-asterisk-prefix */
Compilation.prototype.factorizeModule = /**
@type {{
(options: FactorizeModuleOptions & { factoryResult?: false }, callback: ModuleCallback): void;
(options: FactorizeModuleOptions & { factoryResult: true }, callback: ModuleFactoryResultCallback): void;
}} */ (
function factorizeModule(options, callback) {
this.factorizeQueue.add(options, /** @type {TODO} */ (callback));
}
);
/* eslint-enable jsdoc/require-asterisk-prefix */
// Hide from typescript
const compilationPrototype = Compilation.prototype;

71
node_modules/webpack/lib/Compiler.js generated vendored
View File

@@ -38,9 +38,9 @@ const webpack = require(".");
/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */
/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */
/** @typedef {import("../declarations/WebpackOptions").Plugins} Plugins */
/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./HotModuleReplacementPlugin").ChunkHashes} ChunkHashes */
/** @typedef {import("./HotModuleReplacementPlugin").ChunkModuleHashes} ChunkModuleHashes */
@@ -70,23 +70,18 @@ const webpack = require(".");
/**
* @template T
* @callback RunCallback
* @param {Error | null} err
* @param {T=} result
* @template [R=void]
* @typedef {import("./webpack").Callback<T, R>} Callback
*/
/**
* @template T
* @callback Callback
* @param {(Error | null)=} err
* @param {T=} result
*/
/** @typedef {import("./webpack").ErrorCallback} ErrorCallback */
/**
* @callback RunAsChildCallback
* @param {Error | null} err
* @param {Chunk[]=} entries
* @param {Compilation=} compilation
* @returns {void}
*/
/**
@@ -122,7 +117,8 @@ const webpack = require(".");
/** @typedef {{ buildInfo: BuildInfo, references: WeakReferences | undefined, memCache: MemCache }} ModuleMemCachesItem */
/**
* @param {string[]} array an array
* @template T
* @param {T[]} array an array
* @returns {boolean} true, if the array is sorted
*/
const isSorted = (array) => {
@@ -478,12 +474,13 @@ class Compiler {
/**
* @param {WatchOptions} watchOptions the watcher's options
* @param {RunCallback<Stats>} handler signals when the call finishes
* @returns {Watching} a compiler watcher
* @param {Callback<Stats>} handler signals when the call finishes
* @returns {Watching | undefined} a compiler watcher
*/
watch(watchOptions, handler) {
if (this.running) {
return handler(new ConcurrentCompilationError());
handler(new ConcurrentCompilationError());
return;
}
this.running = true;
@@ -493,12 +490,13 @@ class Compiler {
}
/**
* @param {RunCallback<Stats>} callback signals when the call finishes
* @param {Callback<Stats>} callback signals when the call finishes
* @returns {void}
*/
run(callback) {
if (this.running) {
return callback(new ConcurrentCompilationError());
callback(new ConcurrentCompilationError());
return;
}
/** @type {Logger | undefined} */
@@ -695,7 +693,7 @@ class Compiler {
/**
* @param {Compilation} compilation the compilation
* @param {Callback<void>} callback signals when the assets are emitted
* @param {ErrorCallback} callback signals when the assets are emitted
* @returns {void}
*/
emitAssets(compilation, callback) {
@@ -1028,7 +1026,7 @@ ${other}`);
this.hooks.afterEmit.callAsync(compilation, (err) => {
if (err) return callback(err);
return callback();
return callback(null);
});
}
);
@@ -1046,7 +1044,7 @@ ${other}`);
}
/**
* @param {Callback<void>} callback signals when the call finishes
* @param {ErrorCallback} callback signals when the call finishes
* @returns {void}
*/
emitRecords(callback) {
@@ -1065,12 +1063,12 @@ ${other}`);
} else if (this.recordsOutputPath) {
this._emitRecords(callback);
} else {
callback();
callback(null);
}
}
/**
* @param {Callback<void>} callback signals when the call finishes
* @param {ErrorCallback} callback signals when the call finishes
* @returns {void}
*/
_emitRecords(callback) {
@@ -1119,7 +1117,7 @@ ${other}`);
}
/**
* @param {Callback<void>} callback signals when the call finishes
* @param {ErrorCallback} callback signals when the call finishes
* @returns {void}
*/
readRecords(callback) {
@@ -1140,28 +1138,29 @@ ${other}`);
this._readRecords(callback);
} else {
this.records = {};
callback();
callback(null);
}
}
/**
* @param {Callback<void>} callback signals when the call finishes
* @param {ErrorCallback} callback signals when the call finishes
* @returns {void}
*/
_readRecords(callback) {
if (!this.recordsInputPath) {
this.records = {};
return callback();
return callback(null);
}
/** @type {InputFileSystem} */
(this.inputFileSystem).stat(this.recordsInputPath, (err) => {
// It doesn't exist
// We can ignore this.
if (err) return callback();
if (err) return callback(null);
/** @type {InputFileSystem} */
(this.inputFileSystem).readFile(
/** @type {string} */ (this.recordsInputPath),
/** @type {string} */
(this.recordsInputPath),
(err, content) => {
if (err) return callback(err);
@@ -1177,7 +1176,7 @@ ${other}`);
);
}
return callback();
return callback(null);
}
);
});
@@ -1188,7 +1187,7 @@ ${other}`);
* @param {string} compilerName the compiler's name
* @param {number} compilerIndex the compiler's index
* @param {Partial<OutputOptions>=} outputOptions the output options
* @param {WebpackPluginInstance[]=} plugins the plugins to apply
* @param {Plugins=} plugins the plugins to apply
* @returns {Compiler} a child compiler
*/
createChildCompiler(
@@ -1239,7 +1238,10 @@ ${other}`);
childCompiler.root = this.root;
if (Array.isArray(plugins)) {
for (const plugin of plugins) {
if (plugin) {
if (typeof plugin === "function") {
/** @type {WebpackPluginFunction} */
(plugin).call(childCompiler, childCompiler);
} else if (plugin) {
plugin.apply(childCompiler);
}
}
@@ -1311,8 +1313,7 @@ ${other}`);
fs: /** @type {InputFileSystem} */ (this.inputFileSystem),
resolverFactory: this.resolverFactory,
options: this.options.module,
associatedObjectForCache: this.root,
layers: this.options.experiments.layers
associatedObjectForCache: this.root
});
this._lastNormalModuleFactory = normalModuleFactory;
this.hooks.normalModuleFactory.call(normalModuleFactory);
@@ -1334,7 +1335,7 @@ ${other}`);
}
/**
* @param {RunCallback<Compilation>} callback signals when the compilation finishes
* @param {Callback<Compilation>} callback signals when the compilation finishes
* @returns {void}
*/
compile(callback) {
@@ -1385,7 +1386,7 @@ ${other}`);
}
/**
* @param {RunCallback<void>} callback signals when the compiler closes
* @param {ErrorCallback} callback signals when the compiler closes
* @returns {void}
*/
close(callback) {

View File

@@ -10,16 +10,18 @@ const {
NAMESPACE_OBJECT_EXPORT
} = require("./util/concatenate");
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./optimize/ConcatenatedModule").ConcatenatedModuleInfo} ConcatenatedModuleInfo */
/** @typedef {import("./optimize/ConcatenatedModule").ModuleInfo} ModuleInfo */
/** @typedef {import("./optimize/ConcatenatedModule").ExportName} Ids */
const MODULE_REFERENCE_REGEXP =
/^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_directImport)?(_deferredImport)?(?:_asiSafe(\d))?__$/;
/**
* @typedef {object} ModuleReferenceOptions
* @property {string[]} ids the properties/exports of the module
* @property {Ids} ids the properties/exports of the module
* @property {boolean} call true, when this referenced export is called
* @property {boolean} directImport true, when this referenced export is directly imported (not via property access)
* @property {boolean} deferredImport true, when this referenced export is deferred
@@ -187,4 +189,7 @@ class ConcatenationScope {
ConcatenationScope.DEFAULT_EXPORT = DEFAULT_EXPORT;
ConcatenationScope.NAMESPACE_OBJECT_EXPORT = NAMESPACE_OBJECT_EXPORT;
/** @type {WeakMap<Chunk, Set<string>>} */
ConcatenationScope.chunkUsedNames = new WeakMap();
module.exports = ConcatenationScope;

View File

@@ -78,7 +78,7 @@ class ConditionalInitFragment extends InitFragment {
/**
* @param {GenerateContext} context context
* @returns {string | Source=} the source code that will be included at the end of the module
* @returns {string | Source | undefined} the source code that will be included at the end of the module
*/
getEndContent(context) {
if (this.runtimeCondition === false || !this.endContent) return "";

View File

@@ -24,12 +24,13 @@ const { parseResource } = require("./util/identifier");
/** @typedef {import("estree").Super} Super */
/** @typedef {import("estree").VariableDeclaration} VariableDeclaration */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/** @typedef {Set<string>} Declarations */
/**
* @param {Set<string>} declarations set of declarations
* @param {Declarations} declarations set of declarations
* @param {Identifier | Pattern} pattern pattern to collect declarations from
*/
const collectDeclaration = (declarations, pattern) => {
@@ -65,12 +66,12 @@ const collectDeclaration = (declarations, pattern) => {
/**
* @param {Statement} branch branch to get hoisted declarations from
* @param {boolean} includeFunctionDeclarations whether to include function declarations
* @returns {Array<string>} hoisted declarations
* @returns {string[]} hoisted declarations
*/
const getHoistedDeclarations = (branch, includeFunctionDeclarations) => {
/** @type {Set<string>} */
/** @type {Declarations} */
const declarations = new Set();
/** @type {Array<Statement | null | undefined>} */
/** @type {(Statement | null | undefined)[]} */
const stack = [branch];
while (stack.length > 0) {
const node = stack.pop();

View File

@@ -5,7 +5,6 @@
"use strict";
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./ContextModuleFactory")} ContextModuleFactory */
const PLUGIN_NAME = "ContextExclusionPlugin";

View File

@@ -30,25 +30,27 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Chunk").ChunkId} ChunkId */
/** @typedef {import("./Chunk").ChunkName} ChunkName */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Dependency").RawReferencedExports} RawReferencedExports */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").BuildCallback} BuildCallback */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./Module").FileSystemDependencies} FileSystemDependencies */
/** @typedef {import("./Module").BuildMeta} BuildMeta */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").LibIdent} LibIdent */
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
@@ -56,7 +58,6 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./javascript/JavascriptParser").ImportAttributes} ImportAttributes */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @template T @typedef {import("./util/LazySet")<T>} LazySet<T> */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */
@@ -65,17 +66,17 @@ const makeSerializable = require("./util/makeSerializable");
* @typedef {object} ContextOptions
* @property {ContextMode} mode
* @property {boolean} recursive
* @property {RegExp} regExp
* @property {("strict" | boolean)=} namespaceObject
* @property {RegExp | false | null} regExp
* @property {"strict" | boolean=} namespaceObject
* @property {string=} addon
* @property {(string | null)=} chunkName
* @property {(RegExp | null)=} include
* @property {(RegExp | null)=} exclude
* @property {ChunkName=} chunkName
* @property {RegExp | null=} include
* @property {RegExp | null=} exclude
* @property {RawChunkGroupOptions=} groupOptions
* @property {string=} typePrefix
* @property {string=} category
* @property {(string[][] | null)=} referencedExports exports referenced from modules (won't be mangled)
* @property {string=} layer
* @property {RawReferencedExports | null=} referencedExports exports referenced from modules (won't be mangled)
* @property {string | null=} layer
* @property {ImportAttributes=} attributes
*/
@@ -93,6 +94,7 @@ const makeSerializable = require("./util/makeSerializable");
* @callback ResolveDependenciesCallback
* @param {Error | null} err
* @param {ContextElementDependency[]=} dependencies
* @returns {void}
*/
/**
@@ -106,8 +108,6 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {Record<ModuleId, FakeMapType>} FakeMap */
const SNAPSHOT_OPTIONS = { timestamp: true };
class ContextModule extends Module {
/**
* @param {ResolveDependencies} resolveDependencies function to get dependencies in this context
@@ -254,10 +254,12 @@ class ContextModule extends Module {
} else if (this.options.namespaceObject) {
identifier += "|namespace object";
}
if (this.options.attributes) {
identifier += `|importAttributes: ${JSON.stringify(this.options.attributes)}`;
}
if (this.layer) {
identifier += `|layer: ${this.layer}`;
}
return identifier;
}
@@ -334,7 +336,7 @@ class ContextModule extends Module {
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
* @returns {LibIdent | null} an identifier for library inclusion
*/
libIdent(options) {
let identifier;
@@ -532,6 +534,8 @@ class ContextModule extends Module {
}
if (!this.context && !this.options.resource) return callback();
const snapshotOptions = compilation.options.snapshot.contextModule;
compilation.fileSystemInfo.createSnapshot(
startTime,
null,
@@ -541,7 +545,7 @@ class ContextModule extends Module {
? [this.options.resource]
: /** @type {string[]} */ (this.options.resource),
null,
SNAPSHOT_OPTIONS,
snapshotOptions,
(err, snapshot) => {
if (err) return callback(err);
/** @type {BuildInfo} */
@@ -553,10 +557,10 @@ class ContextModule extends Module {
}
/**
* @param {LazySet<string>} fileDependencies set where file dependencies are added to
* @param {LazySet<string>} contextDependencies set where context dependencies are added to
* @param {LazySet<string>} missingDependencies set where missing dependencies are added to
* @param {LazySet<string>} buildDependencies set where build dependencies are added to
* @param {FileSystemDependencies} fileDependencies set where file dependencies are added to
* @param {FileSystemDependencies} contextDependencies set where context dependencies are added to
* @param {FileSystemDependencies} missingDependencies set where missing dependencies are added to
* @param {FileSystemDependencies} buildDependencies set where build dependencies are added to
*/
addCacheDependencies(
fileDependencies,
@@ -578,7 +582,7 @@ class ContextModule extends Module {
/**
* @param {Dependency[]} dependencies all dependencies
* @param {ChunkGraph} chunkGraph chunk graph
* @returns {Map<string, string | number>} map with user requests
* @returns {Map<string, ModuleId>} map with user requests
*/
getUserRequestMap(dependencies, chunkGraph) {
const moduleGraph = chunkGraph.moduleGraph;

View File

@@ -17,11 +17,11 @@ const { join } = require("./util/fs");
/** @typedef {import("./ContextModule").ContextModuleOptions} ContextModuleOptions */
/** @typedef {import("./ContextModule").ResolveDependenciesCallback} ResolveDependenciesCallback */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
/** @typedef {import("./ModuleFactory").ModuleFactoryCallback} ModuleFactoryCallback */
/** @typedef {import("./ResolverFactory")} ResolverFactory */
/** @typedef {import("./dependencies/ContextDependency")} ContextDependency */
/** @typedef {import("./dependencies/ContextDependency").ContextOptions} ContextOptions */
/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
/**
* @template T
@@ -31,9 +31,23 @@ const { join } = require("./util/fs");
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {{ context: string, request: string }} ContextAlternativeRequest */
/**
* @typedef {object} ContextResolveData
* @property {string} context
* @property {string} request
* @property {ModuleFactoryCreateData["resolveOptions"]} resolveOptions
* @property {LazySet<string>} fileDependencies
* @property {LazySet<string>} missingDependencies
* @property {LazySet<string>} contextDependencies
* @property {ContextDependency[]} dependencies
*/
/** @typedef {ContextResolveData & ContextOptions} BeforeContextResolveData */
/** @typedef {BeforeContextResolveData & { resource: string | string[], resourceQuery: string | undefined, resourceFragment: string | undefined, resolveDependencies: ContextModuleFactory["resolveDependencies"] }} AfterContextResolveData */
const EMPTY_RESOLVE_OPTIONS = {};
module.exports = class ContextModuleFactory extends ModuleFactory {
class ContextModuleFactory extends ModuleFactory {
/**
* @param {ResolverFactory} resolverFactory resolverFactory
*/
@@ -45,9 +59,9 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
"options"
]);
this.hooks = Object.freeze({
/** @type {AsyncSeriesWaterfallHook<[TODO]>} */
/** @type {AsyncSeriesWaterfallHook<[BeforeContextResolveData], BeforeContextResolveData | false | void>} */
beforeResolve: new AsyncSeriesWaterfallHook(["data"]),
/** @type {AsyncSeriesWaterfallHook<[TODO]>} */
/** @type {AsyncSeriesWaterfallHook<[AfterContextResolveData], AfterContextResolveData | false | void>} */
afterResolve: new AsyncSeriesWaterfallHook(["data"]),
/** @type {SyncWaterfallHook<[string[]]>} */
contextModuleFiles: new SyncWaterfallHook(["files"]),
@@ -91,9 +105,9 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
*/
create(data, callback) {
const context = data.context;
const dependencies = data.dependencies;
const dependencies = /** @type {ContextDependency[]} */ (data.dependencies);
const resolveOptions = data.resolveOptions;
const dependency = /** @type {ContextDependency} */ (dependencies[0]);
const dependency = dependencies[0];
const fileDependencies = new LazySet();
const missingDependencies = new LazySet();
const contextDependencies = new LazySet();
@@ -130,7 +144,9 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
const request = beforeResolveResult.request;
const resolveOptions = beforeResolveResult.resolveOptions;
/** @type {undefined | string[]} */
let loaders;
/** @type {undefined | string} */
let resource;
let loadersPrefix = "";
const idx = request.lastIndexOf("!");
@@ -170,7 +186,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
asyncLib.parallel(
[
(callback) => {
const results = /** @type ResolveRequest[] */ ([]);
const results = /** @type {ResolveRequest[]} */ ([]);
/**
* @param {ResolveRequest} obj obj
* @returns {void}
@@ -210,7 +226,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
},
(err, result) => {
if (err) return callback(err);
callback(null, /** @type {string} */ (result));
callback(null, result);
}
);
},
@@ -241,8 +257,8 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
(loaderResult.length > 0 ? "!" : ""),
resource:
contextResult.length > 1
? contextResult.map((r) => r.path)
: contextResult[0].path,
? /** @type {string[]} */ (contextResult.map((r) => r.path))
: /** @type {string} */ (contextResult[0].path),
resolveDependencies: this.resolveDependencies.bind(this),
resourceQuery: contextResult[0].query,
resourceFragment: contextResult[0].fragment,
@@ -337,6 +353,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
* @param {string} directory directory
* @param {(context: string, subResource: string, callback: () => void) => void} addSubDirectory addSubDirectoryFn
* @param {ResolveDependenciesCallback} callback callback
* @returns {void}
*/
const addDirectory = (ctx, directory, addSubDirectory, callback) => {
fs.readdir(directory, (err, files) => {
@@ -478,4 +495,6 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
});
}
}
};
}
module.exports = ContextModuleFactory;

View File

@@ -10,6 +10,8 @@ const { join } = require("./util/fs");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./ContextModule").ContextModuleOptions} ContextModuleOptions */
/** @typedef {import("./ContextModuleFactory").BeforeContextResolveData} BeforeContextResolveData */
/** @typedef {import("./ContextModuleFactory").AfterContextResolveData} AfterContextResolveData */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {Record<string, string>} NewContentCreateContextMap */
@@ -19,7 +21,7 @@ const PLUGIN_NAME = "ContextReplacementPlugin";
class ContextReplacementPlugin {
/**
* @param {RegExp} resourceRegExp A regular expression that determines which files will be selected
* @param {(string | ((context: TODO) => void) | RegExp | boolean)=} newContentResource A new resource to replace the match
* @param {(string | ((context: BeforeContextResolveData | AfterContextResolveData) => void) | RegExp | boolean)=} newContentResource A new resource to replace the match
* @param {(boolean | NewContentCreateContextMap | RegExp)=} newContentRecursive If true, all subdirectories are searched for matches
* @param {RegExp=} newContentRegExp A regular expression that determines which files will be selected
*/
@@ -122,7 +124,14 @@ class ContextReplacementPlugin {
});
cmf.hooks.afterResolve.tap(PLUGIN_NAME, (result) => {
if (!result) return;
if (resourceRegExp.test(result.resource)) {
const isMatchResourceRegExp = () => {
if (Array.isArray(result.resource)) {
return result.resource.some((item) => resourceRegExp.test(item));
}
return resourceRegExp.test(result.resource);
};
if (isMatchResourceRegExp()) {
if (newContentResource !== undefined) {
if (
newContentResource.startsWith("/") ||
@@ -130,10 +139,15 @@ class ContextReplacementPlugin {
) {
result.resource = newContentResource;
} else {
const rootPath =
typeof result.resource === "string"
? result.resource
: /** @type {string} */
(result.resource.find((item) => resourceRegExp.test(item)));
result.resource = join(
/** @type {InputFileSystem} */
(compiler.inputFileSystem),
result.resource,
rootPath,
newContentResource
);
}
@@ -153,18 +167,27 @@ class ContextReplacementPlugin {
if (typeof newContentCallback === "function") {
const origResource = result.resource;
newContentCallback(result);
if (
result.resource !== origResource &&
!result.resource.startsWith("/") &&
(result.resource.length <= 1 || result.resource[1] !== ":")
) {
// When the function changed it to an relative path
result.resource = join(
/** @type {InputFileSystem} */
(compiler.inputFileSystem),
origResource,
result.resource
);
if (result.resource !== origResource) {
const newResource = Array.isArray(result.resource)
? result.resource
: [result.resource];
for (let i = 0; i < newResource.length; i++) {
if (
!newResource[i].startsWith("/") &&
(newResource[i].length <= 1 || newResource[i][1] !== ":")
) {
// When the function changed it to an relative path
newResource[i] = join(
/** @type {InputFileSystem} */
(compiler.inputFileSystem),
origResource[i],
newResource[i]
);
}
}
result.resource = newResource;
}
} else {
for (const d of result.dependencies) {

View File

@@ -22,14 +22,14 @@ const {
const createHash = require("./util/createHash");
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./Module").ValueCacheVersion} ValueCacheVersion */
/** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */
/** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").DestructuringAssignmentProperty} DestructuringAssignmentProperty */
/** @typedef {import("./javascript/JavascriptParser").DestructuringAssignmentProperties} DestructuringAssignmentProperties */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/** @typedef {import("./logging/Logger").Logger} Logger */
@@ -45,7 +45,6 @@ const createHash = require("./util/createHash");
* @property {string| (() => string)=} version
*/
/** @typedef {string | Set<string>} ValueCacheVersion */
/** @typedef {(value: { module: NormalModule, key: string, readonly version: ValueCacheVersion }) => CodeValuePrimitive} GeneratorFn */
class RuntimeValue {
@@ -125,7 +124,7 @@ class RuntimeValue {
}
/**
* @param {Set<DestructuringAssignmentProperty> | undefined} properties properties
* @param {DestructuringAssignmentProperties | undefined} properties properties
* @returns {Set<string> | undefined} used keys
*/
function getObjKeys(properties) {
@@ -376,10 +375,7 @@ class DefinePlugin {
);
const { runtimeTemplate } = compilation;
const mainHash = createHash(
/** @type {HashFunction} */
(compilation.outputOptions.hashFunction)
);
const mainHash = createHash(compilation.outputOptions.hashFunction);
mainHash.update(
/** @type {string} */
(compilation.valueCacheVersions.get(VALUE_DEP_MAIN)) || ""
@@ -834,7 +830,7 @@ class DefinePlugin {
compilation.valueCacheVersions.set(
VALUE_DEP_MAIN,
/** @type {string} */ (mainHash.digest("hex").slice(0, 8))
mainHash.digest("hex").slice(0, 8)
);
}
);

View File

@@ -14,30 +14,26 @@ const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDepende
const StaticExportsDependency = require("./dependencies/StaticExportsDependency");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./LibManifestPlugin").ManifestModuleData} ManifestModuleData */
/** @typedef {import("./Module").ModuleId} ModuleId */
/** @typedef {import("./Module").BuildCallback} BuildCallback */
/** @typedef {import("./Module").BuildMeta} BuildMeta */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").LibIdent} LibIdent */
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").SourceContext} SourceContext */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./dependencies/StaticExportsDependency").Exports} Exports */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
@@ -48,8 +44,8 @@ const makeSerializable = require("./util/makeSerializable");
/**
* @typedef {object} DelegatedModuleData
* @property {BuildMeta=} buildMeta build meta
* @property {true | string[]=} exports exports
* @property {number | string} id module id
* @property {Exports=} exports exports
* @property {ModuleId} id module id
*/
const RUNTIME_REQUIREMENTS = new Set([
@@ -89,7 +85,7 @@ class DelegatedModule extends Module {
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
* @returns {LibIdent | null} an identifier for library inclusion
*/
libIdent(options) {
return typeof this.originalRequest === "string"

View File

@@ -8,8 +8,6 @@
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */

View File

@@ -7,10 +7,8 @@
const memoize = require("./util/memoize");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */
@@ -62,10 +60,12 @@ const memoize = require("./util/memoize");
* @property {boolean=} hidden export is not visible, because another export blends over it
*/
/** @typedef {Set<string>} ExportsSpecExcludeExports */
/**
* @typedef {object} ExportsSpec
* @property {(string | ExportSpec)[] | true | null} exports exported names, true for unknown exports or null for no exports
* @property {Set<string>=} excludeExports when exports = true, list of unaffected exports
* @property {ExportsSpecExcludeExports=} excludeExports when exports = true, list of unaffected exports
* @property {(Set<string> | null)=} hideExports list of maybe prior exposed, but now hidden exports
* @property {ModuleGraphConnection=} from when reexported: from which module
* @property {number=} priority when reexported: with which priority
@@ -80,6 +80,9 @@ const memoize = require("./util/memoize");
* @property {boolean=} canMangle when false, referenced export can not be mangled, defaults to true
*/
/** @typedef {string[][]} RawReferencedExports */
/** @typedef {(string[] | ReferencedExport)[]} ReferencedExports */
/** @typedef {(moduleGraphConnection: ModuleGraphConnection, runtime: RuntimeSpec) => ConnectionState} GetConditionFn */
const TRANSITIVE = Symbol("transitive");
@@ -105,9 +108,6 @@ class Dependency {
this.weak = false;
// TODO check if this can be moved into ModuleDependency
/** @type {boolean | undefined} */
this.defer = false;
// TODO check if this can be moved into ModuleDependency
/** @type {boolean | undefined} */
this.optional = false;
this._locSL = 0;
this._locSC = 0;
@@ -230,7 +230,7 @@ class Dependency {
* Returns list of exports referenced by this dependency
* @param {ModuleGraph} moduleGraph module graph
* @param {RuntimeSpec} runtime the runtime for which the module is analysed
* @returns {(string[] | ReferencedExport)[]} referenced exports
* @returns {ReferencedExports} referenced exports
*/
getReferencedExports(moduleGraph, runtime) {
return Dependency.EXPORTS_OBJECT_REFERENCED;
@@ -315,7 +315,6 @@ class Dependency {
write(this._locEC);
write(this._locI);
write(this._locN);
write(this.defer);
}
/**
@@ -330,13 +329,12 @@ class Dependency {
this._locEC = read();
this._locI = read();
this._locN = read();
this.defer = read();
}
}
/** @type {string[][]} */
/** @type {RawReferencedExports} */
Dependency.NO_EXPORTS_REFERENCED = [];
/** @type {string[][]} */
/** @type {RawReferencedExports} */
Dependency.EXPORTS_OBJECT_REFERENCED = [[]];
// TODO remove in webpack 6

View File

@@ -8,12 +8,10 @@
const { DEFAULTS } = require("./config/defaults");
const createHash = require("./util/createHash");
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Compilation").DependencyConstructor} DependencyConstructor */
/** @typedef {import("./DependencyTemplate")} DependencyTemplate */
/** @typedef {typeof import("./util/Hash")} Hash */
/** @typedef {new (...args: EXPECTED_ANY[]) => Dependency} DependencyConstructor */
class DependencyTemplates {
/**
* @param {string | Hash} hashFunction the hash function to use
@@ -50,7 +48,7 @@ class DependencyTemplates {
updateHash(part) {
const hash = createHash(this._hashFunction);
hash.update(`${this._hash}${part}`);
this._hash = /** @type {string} */ (hash.digest("hex"));
this._hash = hash.digest("hex");
}
getHash() {

View File

@@ -12,24 +12,18 @@ const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").BuildCallback} BuildCallback */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").SourceContext} SourceContext */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./util/Hash")} Hash */

View File

@@ -84,7 +84,7 @@ class DllReferencePlugin {
// Store the error in the params so that it can
// be added as a compilation error later on.
const manifestPath = makePathsRelative(
/** @type {string} */ (compiler.options.context),
compiler.context,
manifest,
compiler.root
);
@@ -142,9 +142,7 @@ class DllReferencePlugin {
source,
type: this.options.type,
scope: this.options.scope,
context:
/** @type {string} */
(this.options.context || compiler.options.context),
context: this.options.context || compiler.context,
content:
/** @type {DllReferencePluginOptionsContent} */
(resolvedContent),

View File

@@ -11,8 +11,6 @@ const EntryDependency = require("./dependencies/EntryDependency");
/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescriptionNormalized */
/** @typedef {import("../declarations/WebpackOptions").EntryDynamicNormalized} EntryDynamic */
/** @typedef {import("../declarations/WebpackOptions").EntryItem} EntryItem */
/** @typedef {import("../declarations/WebpackOptions").EntryStaticNormalized} EntryStatic */
/** @typedef {import("./Compiler")} Compiler */
const PLUGIN_NAME = "DynamicEntryPlugin";

View File

@@ -76,11 +76,6 @@ class EntryOptionPlugin {
wasmLoading: desc.wasmLoading,
library: desc.library
};
if (desc.layer !== undefined && !compiler.options.experiments.layers) {
throw new Error(
"'entryOptions.layer' is only allowed when 'experiments.layers' is enabled"
);
}
if (desc.chunkLoading) {
const EnableChunkLoadingPlugin = require("./javascript/EnableChunkLoadingPlugin");

View File

@@ -9,10 +9,7 @@ const WebpackError = require("./WebpackError");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {"asyncWebAssembly" | "topLevelAwait" | "external promise" | "external script" | "external import" | "external module"} Feature */
class EnvironmentNotSupportAsyncWarning extends WebpackError {

View File

@@ -12,7 +12,8 @@ const RuntimeGlobals = require("./RuntimeGlobals");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */
/** @typedef {import("../declarations/WebpackOptions").DevtoolNamespace} DevtoolNamespace */
/** @typedef {import("../declarations/WebpackOptions").DevtoolModuleFilenameTemplate} DevtoolModuleFilenameTemplate */
/** @typedef {import("./Compiler")} Compiler */
/** @type {WeakMap<Source, Source>} */
@@ -30,9 +31,9 @@ const devtoolWarning = new RawSource(`/*
/**
* @typedef {object} EvalDevToolModulePluginOptions
* @property {OutputOptions["devtoolNamespace"]=} namespace namespace
* @property {DevtoolNamespace=} namespace namespace
* @property {string=} sourceUrlComment source url comment
* @property {OutputOptions["devtoolModuleFilenameTemplate"]=} moduleFilenameTemplate module filename template
* @property {DevtoolModuleFilenameTemplate=} moduleFilenameTemplate module filename template
*/
const PLUGIN_NAME = "EvalDevToolModulePlugin";

View File

@@ -17,7 +17,6 @@ const { makePathsAbsolute } = require("./util/identifier");
/** @typedef {import("webpack-sources").RawSourceMap} RawSourceMap */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").DevTool} DevToolOptions */
/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./Compiler")} Compiler */
@@ -39,9 +38,9 @@ const PLUGIN_NAME = "EvalSourceMapDevToolPlugin";
class EvalSourceMapDevToolPlugin {
/**
* @param {SourceMapDevToolPluginOptions | string} inputOptions Options object
* @param {SourceMapDevToolPluginOptions | string=} inputOptions Options object
*/
constructor(inputOptions) {
constructor(inputOptions = {}) {
/** @type {SourceMapDevToolPluginOptions} */
let options;
if (typeof inputOptions === "string") {
@@ -134,7 +133,7 @@ class EvalSourceMapDevToolPlugin {
// Clone (flat) the sourcemap to ensure that the mutations below do not persist.
sourceMap = { ...sourceMap };
const context = /** @type {string} */ (compiler.options.context);
const context = compiler.context;
const root = compiler.root;
const modules = sourceMap.sources.map((source) => {
if (!source.startsWith("webpack://")) return source;

View File

@@ -12,6 +12,8 @@ const { forEachRuntime } = require("./util/runtime");
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").RuntimeSpec} RuntimeSpec */
/** @typedef {import("./Dependency").ExportsSpecExcludeExports} ExportsSpecExcludeExports */
/** @typedef {import("./dependencies/HarmonyImportDependency")} HarmonyImportDependency */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleGraphConnection")} ModuleGraphConnection */
@@ -22,6 +24,32 @@ const { forEachRuntime } = require("./util/runtime");
/** @typedef {typeof UsageState.OnlyPropertiesUsed | typeof UsageState.NoInfo | typeof UsageState.Unknown | typeof UsageState.Used} RuntimeUsageStateType */
/** @typedef {typeof UsageState.Unused | RuntimeUsageStateType} UsageStateType */
/** @typedef {string} ExportInfoName */
/** @typedef {Map<string, RuntimeUsageStateType>} UsedInRuntime */
/** @typedef {{ module: Module, export: ExportInfoName[], deferred: boolean }} TargetItemWithoutConnection */
/** @typedef {{ module: Module, connection: ModuleGraphConnection, export: ExportInfoName[] | undefined }} TargetItemWithConnection */
/** @typedef {(target: TargetItemWithConnection) => boolean} ResolveTargetFilter */
/** @typedef {(module: Module) => boolean} ValidTargetModuleFilter */
/** @typedef {{ connection: ModuleGraphConnection, export: ExportInfoName[], priority: number }} TargetItem */
/** @typedef {Map<Dependency | undefined, TargetItem>} Target */
/** @typedef {string | null} ExportInfoUsedName */
/** @typedef {boolean | null} ExportInfoProvided */
/** @typedef {Map<ExportInfoName, ExportInfo>} Exports */
/** @typedef {string | string[] | false} UsedName */
/** @typedef {Set<ExportInfo>} AlreadyVisitedExportInfo */
/**
* @typedef {object} RestoreProvidedDataExports
* @property {ExportInfoName} name
* @property {ExportInfo["provided"]} provided
* @property {ExportInfo["canMangleProvide"]} canMangleProvide
* @property {ExportInfo["terminalBinding"]} terminalBinding
* @property {RestoreProvidedData | undefined} exportsInfo
*/
const UsageState = Object.freeze({
Unused: /** @type {0} */ (0),
OnlyPropertiesUsed: /** @type {1} */ (1),
@@ -34,15 +62,6 @@ const RETURNS_TRUE = () => true;
const CIRCULAR = Symbol("circular target");
/**
* @typedef {object} RestoreProvidedDataExports
* @property {ExportInfoName} name
* @property {ExportInfo["provided"]} provided
* @property {ExportInfo["canMangleProvide"]} canMangleProvide
* @property {ExportInfo["terminalBinding"]} terminalBinding
* @property {RestoreProvidedData | undefined} exportsInfo
*/
class RestoreProvidedData {
/**
* @param {RestoreProvidedDataExports[]} exports exports
@@ -87,14 +106,11 @@ makeSerializable(
"RestoreProvidedData"
);
/** @typedef {Map<ExportInfoName, ExportInfo>} Exports */
/** @typedef {string | string[] | false} UsedName */
class ExportsInfo {
constructor() {
/** @type {Exports} */
this._exports = new Map();
this._otherExportsInfo = new ExportInfo(/** @type {TODO} */ (null));
this._otherExportsInfo = new ExportInfo(null);
this._sideEffectsOnlyInfo = new ExportInfo("*side effects only*");
this._exportsAreOrdered = false;
/** @type {ExportsInfo=} */
@@ -171,7 +187,7 @@ class ExportsInfo {
*/
_sortExportsMap(exports) {
if (exports.size > 1) {
/** @type {string[]} */
/** @type {ExportInfoName[]} */
const namesInOrder = [];
for (const entry of exports.values()) {
namesInOrder.push(entry.name);
@@ -308,7 +324,7 @@ class ExportsInfo {
/**
* @param {boolean=} canMangle true, if exports can still be mangled (defaults to false)
* @param {Set<string>=} excludeExports list of unaffected exports
* @param {ExportsSpecExcludeExports=} excludeExports list of unaffected exports
* @param {Dependency=} targetKey use this as key for the target
* @param {ModuleGraphConnection=} targetModule set this module as target
* @param {number=} priority priority
@@ -505,7 +521,7 @@ class ExportsInfo {
/**
* @param {RuntimeSpec} runtime the runtime
* @returns {SortableSet<string> | boolean | null} set of used exports, or true (when namespace object is used), or false (when unused), or null (when unknown)
* @returns {SortableSet<ExportInfoName> | boolean | null} set of used exports, or true (when namespace object is used), or false (when unused), or null (when unknown)
*/
getUsedExports(runtime) {
switch (this._otherExportsInfo.getUsed(runtime)) {
@@ -517,6 +533,7 @@ class ExportsInfo {
return true;
}
/** @type {ExportInfoName[]} */
const array = [];
if (!this._exportsAreOrdered) this._sortExports();
for (const exportInfo of this._exports.values()) {
@@ -548,11 +565,11 @@ class ExportsInfo {
return false;
}
}
return /** @type {SortableSet<string>} */ (new SortableSet(array));
return /** @type {SortableSet<ExportInfoName>} */ (new SortableSet(array));
}
/**
* @returns {null | true | string[]} list of exports when known
* @returns {null | true | ExportInfoName[]} list of exports when known
*/
getProvidedExports() {
switch (this._otherExportsInfo.provided) {
@@ -564,7 +581,7 @@ class ExportsInfo {
return true;
}
/** @type {string[]} */
/** @type {ExportInfoName[]} */
const array = [];
if (!this._exportsAreOrdered) this._sortExports();
for (const exportInfo of this._exports.values()) {
@@ -831,32 +848,14 @@ class ExportsInfo {
}
}
/** @typedef {Map<string, RuntimeUsageStateType>} UsedInRuntime */
/** @typedef {{ module: Module, export: string[], deferred: boolean }} TargetItemWithoutConnection */
/** @typedef {{ module: Module, connection: ModuleGraphConnection, export: string[] | undefined }} TargetItemWithConnection */
/** @typedef {(target: TargetItemWithConnection) => boolean} ResolveTargetFilter */
/** @typedef {(module: Module) => boolean} ValidTargetModuleFilter */
/** @typedef {{ connection: ModuleGraphConnection, export: string[], priority: number }} TargetItem */
/** @typedef {Map<Dependency | undefined, TargetItem>} Target */
/** @typedef {string} ExportInfoName */
/** @typedef {string | null} ExportInfoUsedName */
/** @typedef {boolean | null} ExportInfoProvided */
class ExportInfo {
/**
* @param {ExportInfoName} name the original name of the export
* @param {ExportInfoName | null} name the original name of the export
* @param {ExportInfo=} initFrom init values from this ExportInfo
*/
constructor(name, initFrom) {
/** @type {ExportInfoName} */
this.name = name;
this.name = /** @type {ExportInfoName} */ (name);
/**
* @private
* @type {ExportInfoUsedName}
@@ -1058,8 +1057,8 @@ class ExportInfo {
}
} else {
let changed = false;
forEachRuntime(runtime, (_runtime) => {
const runtime = /** @type {string} */ (_runtime);
forEachRuntime(runtime, (runtime_) => {
const runtime = /** @type {string} */ (runtime_);
const usedInRuntime =
/** @type {UsedInRuntime} */
(this._usedInRuntime);
@@ -1148,7 +1147,7 @@ class ExportInfo {
/**
* @param {Dependency} key the key
* @param {ModuleGraphConnection} connection the target module if a single one
* @param {(string[] | null)=} exportName the exported name
* @param {ExportInfoName[] | null=} exportName the exported name
* @param {number=} priority priority
* @returns {boolean} true, if something has changed
*/
@@ -1158,7 +1157,7 @@ class ExportInfo {
this._target = new Map();
this._target.set(key, {
connection,
export: /** @type {string[]} */ (exportName),
export: /** @type {ExportInfoName[]} */ (exportName),
priority
});
return true;
@@ -1168,7 +1167,7 @@ class ExportInfo {
if (oldTarget === null && !connection) return false;
this._target.set(key, {
connection,
export: /** @type {string[]} */ (exportName),
export: /** @type {ExportInfoName[]} */ (exportName),
priority
});
this._maxTarget = undefined;
@@ -1182,7 +1181,7 @@ class ExportInfo {
: oldTarget.export)
) {
oldTarget.connection = connection;
oldTarget.export = /** @type {string[]} */ (exportName);
oldTarget.export = /** @type {ExportInfoName[]} */ (exportName);
oldTarget.priority = priority;
this._maxTarget = undefined;
return true;
@@ -1331,7 +1330,7 @@ class ExportInfo {
/**
* @param {ModuleGraph} moduleGraph the module graph
* @param {ValidTargetModuleFilter} validTargetModuleFilter a valid target module
* @param {Set<ExportInfo>} alreadyVisited set of already visited export info to avoid circular references
* @param {AlreadyVisitedExportInfo} alreadyVisited set of already visited export info to avoid circular references
* @returns {TargetItemWithoutConnection | null | undefined | false} the target, undefined when there is no target, false when no target is valid
*/
_findTarget(moduleGraph, validTargetModuleFilter, alreadyVisited) {
@@ -1345,7 +1344,9 @@ class ExportInfo {
module: rawTarget.connection.module,
export: rawTarget.export,
deferred: Boolean(
rawTarget.connection.dependency && rawTarget.connection.dependency.defer
rawTarget.connection.dependency &&
/** @type {HarmonyImportDependency} */
(rawTarget.connection.dependency).defer
)
};
for (;;) {
@@ -1387,13 +1388,13 @@ class ExportInfo {
/**
* @param {ModuleGraph} moduleGraph the module graph
* @param {ResolveTargetFilter} resolveTargetFilter filter function to further resolve target
* @param {Set<ExportInfo> | undefined} alreadyVisited set of already visited export info to avoid circular references
* @param {AlreadyVisitedExportInfo | undefined} alreadyVisited set of already visited export info to avoid circular references
* @returns {TargetItemWithConnection | CIRCULAR | undefined} the target
*/
_getTarget(moduleGraph, resolveTargetFilter, alreadyVisited) {
/**
* @param {TargetItem | undefined | null} inputTarget unresolved target
* @param {Set<ExportInfo>} alreadyVisited set of already visited export info to avoid circular references
* @param {AlreadyVisitedExportInfo} alreadyVisited set of already visited export info to avoid circular references
* @returns {TargetItemWithConnection | CIRCULAR | null} resolved target
*/
const resolveTarget = (inputTarget, alreadyVisited) => {

View File

@@ -29,22 +29,23 @@ const { register } = require("./util/serialization");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").UnsafeCacheData} UnsafeCacheData */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./ExportsInfo")} ExportsInfo */
/** @typedef {import("./Generator").GenerateContext} GenerateContext */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").ModuleId} ModuleId */
/** @typedef {import("./Module").BuildCallback} BuildCallback */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").LibIdent} LibIdent */
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
@@ -53,7 +54,6 @@ const { register } = require("./util/serialization");
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */
/** @typedef {import("./javascript/JavascriptParser").ImportAttributes} ImportAttributes */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
@@ -88,7 +88,7 @@ const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([
const EMPTY_RUNTIME_REQUIREMENTS = new Set([]);
/**
* @param {string|string[]} variableName the variable name or path
* @param {string | string[]} variableName the variable name or path
* @param {string} type the module system
* @returns {SourceData} the generated source
*/
@@ -108,8 +108,10 @@ const getSourceForGlobalVariableExternal = (variableName, type) => {
};
};
/** @typedef {string | string[]} ModuleAndSpecifiers */
/**
* @param {string|string[]} moduleAndSpecifiers the module request
* @param {ModuleAndSpecifiers} moduleAndSpecifiers the module request
* @returns {SourceData} the generated source
*/
const getSourceForCommonJsExternal = (moduleAndSpecifiers) => {
@@ -128,7 +130,24 @@ const getSourceForCommonJsExternal = (moduleAndSpecifiers) => {
};
/**
* @param {string | string[]} moduleAndSpecifiers the module request
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {InitFragment<ChunkRenderContext>} code
*/
const getExternalModuleNodeCommonjsInitFragment = (runtimeTemplate) => {
const importMetaName = runtimeTemplate.outputOptions.importMetaName;
return new InitFragment(
`import { createRequire as __WEBPACK_EXTERNAL_createRequire } from ${runtimeTemplate.renderNodePrefixForCoreModule(
"module"
)};\n${runtimeTemplate.renderConst()} __WEBPACK_EXTERNAL_createRequire_require = __WEBPACK_EXTERNAL_createRequire(${importMetaName}.url);\n`,
InitFragment.STAGE_HARMONY_IMPORTS,
0,
"external module node-commonjs"
);
};
/**
* @param {ModuleAndSpecifiers} moduleAndSpecifiers the module request
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
@@ -136,25 +155,13 @@ const getSourceForCommonJsExternalInNodeModule = (
moduleAndSpecifiers,
runtimeTemplate
) => {
const importMetaName =
/** @type {string} */
(runtimeTemplate.outputOptions.importMetaName);
// /** @type {boolean} */
// (runtimeTemplate.supportNodePrefixForCoreModules())
const chunkInitFragments = [
new InitFragment(
`import { createRequire as __WEBPACK_EXTERNAL_createRequire } from ${runtimeTemplate.renderNodePrefixForCoreModule("module")};\n`,
InitFragment.STAGE_HARMONY_IMPORTS,
0,
"external module node-commonjs"
)
getExternalModuleNodeCommonjsInitFragment(runtimeTemplate)
];
if (!Array.isArray(moduleAndSpecifiers)) {
return {
chunkInitFragments,
expression: `__WEBPACK_EXTERNAL_createRequire(${importMetaName}.url)(${JSON.stringify(
expression: `__WEBPACK_EXTERNAL_createRequire_require(${JSON.stringify(
moduleAndSpecifiers
)})`
};
@@ -162,14 +169,14 @@ const getSourceForCommonJsExternalInNodeModule = (
const moduleName = moduleAndSpecifiers[0];
return {
chunkInitFragments,
expression: `__WEBPACK_EXTERNAL_createRequire(${importMetaName}.url)(${JSON.stringify(
expression: `__WEBPACK_EXTERNAL_createRequire_require(${JSON.stringify(
moduleName
)})${propertyAccess(moduleAndSpecifiers, 1)}`
};
};
/**
* @param {string|string[]} moduleAndSpecifiers the module request
* @param {ModuleAndSpecifiers} moduleAndSpecifiers the module request
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {ImportDependencyMeta=} dependencyMeta the dependency meta
* @returns {SourceData} the generated source
@@ -263,7 +270,6 @@ class ModuleExternalInitFragment extends InitFragment {
}
}
const identifier = `__WEBPACK_EXTERNAL_MODULE_${ident}__`;
super(
"",
InitFragment.STAGE_HARMONY_IMPORTS,
@@ -273,8 +279,8 @@ class ModuleExternalInitFragment extends InitFragment {
this._ident = ident;
this._request = request;
this._dependencyMeta = dependencyMeta;
this._imported = imported;
this._identifier = identifier;
this._identifier = this.buildIdentifier(ident);
this._imported = this.buildImported(imported);
}
/**
@@ -337,6 +343,28 @@ class ModuleExternalInitFragment extends InitFragment {
getNamespaceIdentifier() {
return this._identifier;
}
/**
* @param {string} ident ident
* @returns {string} identifier
*/
buildIdentifier(ident) {
return `__WEBPACK_EXTERNAL_MODULE_${ident}__`;
}
/**
* @param {Imported} imported imported
* @returns {Imported} normalized imported
*/
buildImported(imported) {
if (Array.isArray(imported)) {
return imported.map(([name]) => {
const ident = `${this._ident}_${name}`;
return [name, this.buildIdentifier(ident)];
});
}
return imported;
}
}
register(
@@ -398,7 +426,7 @@ const generateModuleRemapping = (
};
/**
* @param {string|string[]} moduleAndSpecifiers the module request
* @param {ModuleAndSpecifiers} moduleAndSpecifiers the module request
* @param {ExportsInfo} exportsInfo exports info of this module
* @param {RuntimeSpec} runtime the runtime
* @param {RuntimeTemplate} runtimeTemplate the runtime template
@@ -433,21 +461,7 @@ const getSourceForModuleExternal = (
imported = [];
break;
default:
imported = [];
if (exportsInfo.isUsed(runtime) === false) {
// no used, only
}
for (const [name] of usedExports.entries()) {
let counter = 0;
let finalName = name;
if (concatenationScope) {
while (!concatenationScope.registerUsedName(finalName)) {
finalName = `${name}_${counter++}`;
}
}
imported.push([name, finalName]);
}
imported = [...usedExports.entries()];
}
}
@@ -458,7 +472,24 @@ const getSourceForModuleExternal = (
dependencyMeta,
runtimeTemplate.outputOptions.hashFunction
);
const specifiers = imported === true ? undefined : imported;
const normalizedImported = initFragment.getImported();
const specifiers =
normalizedImported === true
? undefined
: /** @type {[string, string][]} */ (
normalizedImported.map(([name, rawFinalName]) => {
let finalName = rawFinalName;
let counter = 0;
if (concatenationScope) {
while (!concatenationScope.registerUsedName(finalName)) {
finalName = `${finalName}_${counter++}`;
}
}
return [name, finalName];
})
);
const baseAccess = `${initFragment.getNamespaceIdentifier()}${propertyAccess(
moduleAndSpecifiers,
1
@@ -498,7 +529,7 @@ const getSourceForModuleExternal = (
};
/**
* @param {string|string[]} urlAndGlobal the script request
* @param {string | string[]} urlAndGlobal the script request
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
@@ -546,9 +577,9 @@ const checkExternalVariable = (variableName, request, runtimeTemplate) =>
)} }\n`;
/**
* @param {string|number} id the module id
* @param {ModuleId | string} id the module id
* @param {boolean} optional true, if the module is optional
* @param {string|string[]} request the request path
* @param {string | string[]} request the request path
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
@@ -575,7 +606,7 @@ const getSourceForAmdOrUmdExternal = (
/**
* @param {boolean} optional true, if the module is optional
* @param {string|string[]} request the request path
* @param {string | string[]} request the request path
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
@@ -596,10 +627,11 @@ const getSourceForDefaultCase = (optional, request, runtimeTemplate) => {
};
/** @typedef {Record<string, string | string[]>} RequestRecord */
/** @typedef {string | string[] | RequestRecord} ExternalModuleRequest */
class ExternalModule extends Module {
/**
* @param {string | string[] | RequestRecord} request request
* @param {ExternalModuleRequest} request request
* @param {string} type type
* @param {string} userRequest user request
* @param {DependencyMeta=} dependencyMeta dependency meta
@@ -608,7 +640,7 @@ class ExternalModule extends Module {
super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
// Info from Factory
/** @type {string | string[] | Record<string, string | string[]>} */
/** @type {ExternalModuleRequest} */
this.request = request;
/** @type {string} */
this.externalType = type;
@@ -638,7 +670,7 @@ class ExternalModule extends Module {
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
* @returns {LibIdent | null} an identifier for library inclusion
*/
libIdent(options) {
return this.userRequest;
@@ -1020,9 +1052,7 @@ class ExternalModule extends Module {
scope.registerRawExport(specifier, finalName);
}
} else if (concatenationScope) {
sourceString = `${
runtimeTemplate.supportsConst() ? "const" : "var"
} ${ConcatenationScope.NAMESPACE_OBJECT_EXPORT} = ${sourceString};`;
sourceString = `${runtimeTemplate.renderConst()} ${ConcatenationScope.NAMESPACE_OBJECT_EXPORT} = ${sourceString};`;
concatenationScope.registerNamespaceExport(
ConcatenationScope.NAMESPACE_OBJECT_EXPORT
);
@@ -1126,3 +1156,5 @@ makeSerializable(ExternalModule, "webpack/lib/ExternalModule");
module.exports = ExternalModule;
module.exports.ModuleExternalInitFragment = ModuleExternalInitFragment;
module.exports.getExternalModuleNodeCommonjsInitFragment =
getExternalModuleNodeCommonjsInitFragment;

View File

@@ -14,16 +14,33 @@ const HarmonyImportDependency = require("./dependencies/HarmonyImportDependency"
const ImportDependency = require("./dependencies/ImportDependency");
const { cachedSetProperty, resolveByProperty } = require("./util/cleverMerge");
/** @typedef {import("../declarations/WebpackOptions").ExternalItemFunctionData} ExternalItemFunctionData */
/** @typedef {import("enhanced-resolve").ResolveContext} ResolveContext */
/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
/** @typedef {import("../declarations/WebpackOptions").ExternalItemValue} ExternalItemValue */
/** @typedef {import("../declarations/WebpackOptions").ExternalItemObjectKnown} ExternalItemObjectKnown */
/** @typedef {import("../declarations/WebpackOptions").ExternalItemObjectUnknown} ExternalItemObjectUnknown */
/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */
/** @typedef {import("./Compilation").DepConstructor} DepConstructor */
/** @typedef {import("./ExternalModule").DependencyMeta} DependencyMeta */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleFactory").IssuerLayer} IssuerLayer */
/** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/** @typedef {((context: string, request: string, callback: (err?: Error | null, result?: string | false, resolveRequest?: import('enhanced-resolve').ResolveRequest) => void) => void)} ExternalItemFunctionDataGetResolveCallbackResult */
/** @typedef {((context: string, request: string) => Promise<string>)} ExternalItemFunctionDataGetResolveResult */
/** @typedef {(options?: ResolveOptions) => ExternalItemFunctionDataGetResolveCallbackResult | ExternalItemFunctionDataGetResolveResult} ExternalItemFunctionDataGetResolve */
/**
* @typedef {object} ExternalItemFunctionData
* @property {string} context the directory in which the request is placed
* @property {ModuleFactoryCreateDataContextInfo} contextInfo contextual information
* @property {string} dependencyType the category of the referencing dependency
* @property {ExternalItemFunctionDataGetResolve} getResolve get a resolve function with the current resolver options
* @property {string} request the request as written by the user in the require/import expression/statement
*/
/** @typedef {((data: ExternalItemFunctionData, callback: (err?: (Error | null), result?: ExternalItemValue) => void) => void)} ExternalItemFunctionCallback */
/** @typedef {((data: import("../lib/ExternalModuleFactoryPlugin").ExternalItemFunctionData) => Promise<ExternalItemValue>)} ExternalItemFunctionPromise */
const UNSPECIFIED_EXTERNAL_TYPE_REGEXP = /^[a-z0-9-]+ /;
const EMPTY_RESOLVE_OPTIONS = {};
@@ -79,7 +96,7 @@ const PLUGIN_NAME = "ExternalModuleFactoryPlugin";
class ExternalModuleFactoryPlugin {
/**
* @param {string | undefined} type default external type
* @param {string} type default external type
* @param {Externals} externals externals config
*/
constructor(type, externals) {
@@ -140,7 +157,7 @@ class ExternalModuleFactoryPlugin {
}
}
const resolvedType = /** @type {string} */ (type || globalType);
const resolvedType = type || globalType;
// TODO make it pluggable/add hooks to `ExternalModule` to allow output modules own externals?
/** @type {DependencyMeta | undefined} */
@@ -159,7 +176,7 @@ class ExternalModuleFactoryPlugin {
: undefined;
dependencyMeta = {
attributes: dependency.assertions,
attributes: dependency.attributes,
externalType
};
} else if (dependency instanceof CssImportDependency) {
@@ -265,6 +282,7 @@ class ExternalModuleFactoryPlugin {
dependencyType,
contextInfo,
getResolve: (options) => (context, request, callback) => {
/** @type {ResolveContext} */
const resolveContext = {
fileDependencies: data.fileDependencies,
missingDependencies: data.missingDependencies,
@@ -307,7 +325,9 @@ class ExternalModuleFactoryPlugin {
},
cb
);
if (promise && promise.then) promise.then((r) => cb(null, r), cb);
if (promise && promise.then) {
promise.then((r) => cb(null, r), cb);
}
}
return;
} else if (typeof externals === "object") {

View File

@@ -11,13 +11,13 @@ const ConcatenatedModule = require("./optimize/ConcatenatedModule");
/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./optimize/ConcatenatedModule").ConcatenatedModuleInfo} ConcatenatedModuleInfo */
/** @typedef {import("./ExternalModule").Imported} Imported */
const PLUGIN_NAME = "ExternalsPlugin";
class ExternalsPlugin {
/**
* @param {string | undefined} type default external type
* @param {string} type default external type
* @param {Externals} externals externals config
*/
constructor(type, externals) {
@@ -41,20 +41,23 @@ class ExternalsPlugin {
const { concatenatedModuleInfo } =
ConcatenatedModule.getCompilationHooks(compilation);
concatenatedModuleInfo.tap(PLUGIN_NAME, (updatedInfo, moduleInfo) => {
const rawExportMap =
/** @type {ConcatenatedModuleInfo} */ updatedInfo.rawExportMap;
const rawExportMap = updatedInfo.rawExportMap;
if (!rawExportMap) {
return;
}
const chunkInitFragments =
/** @type {ConcatenatedModuleInfo} */ moduleInfo.chunkInitFragments;
const moduleExternalInitFragments = chunkInitFragments
? chunkInitFragments.filter(
(fragment) => fragment instanceof ModuleExternalInitFragment
)
: [];
const chunkInitFragments = moduleInfo.chunkInitFragments;
const moduleExternalInitFragments =
/** @type {ModuleExternalInitFragment[]} */
(
chunkInitFragments
? /** @type {unknown[]} */
(chunkInitFragments).filter(
(fragment) => fragment instanceof ModuleExternalInitFragment
)
: []
);
let initFragmentChanged = false;
@@ -62,12 +65,16 @@ class ExternalsPlugin {
const imported = fragment.getImported();
if (Array.isArray(imported)) {
const newImported = imported.map(([specifier, finalName]) => [
specifier,
rawExportMap.has(specifier)
? rawExportMap.get(specifier)
: finalName
]);
const newImported =
/** @type {Imported} */
(
imported.map(([specifier, finalName]) => [
specifier,
rawExportMap.has(specifier)
? rawExportMap.get(specifier)
: finalName
])
);
fragment.setImported(newImported);
initFragmentChanged = true;
}

View File

@@ -18,7 +18,6 @@ const makeSerializable = require("./util/makeSerializable");
const memoize = require("./util/memoize");
const processAsyncTree = require("./util/processAsyncTree");
/** @typedef {import("enhanced-resolve").Resolver} Resolver */
/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
/** @typedef {import("enhanced-resolve").ResolveFunctionAsync} ResolveFunctionAsync */
/** @typedef {import("./WebpackError")} WebpackError */
@@ -28,8 +27,6 @@ const processAsyncTree = require("./util/processAsyncTree");
/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
/** @typedef {import("./util/fs").IStats} IStats */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/fs").PathLike} PathLike */
/** @typedef {import("./util/fs").StringCallback} StringCallback */
/**
* @template T
* @typedef {import("./util/AsyncQueue").Callback<T>} ProcessorCallback
@@ -48,8 +45,8 @@ let FS_ACCURACY = 2000;
const EMPTY_SET = new Set();
const RBDT_RESOLVE_CJS = 0;
const RBDT_RESOLVE_ESM = 1;
const RBDT_RESOLVE_INITIAL = 0;
const RBDT_RESOLVE_FILE = 1;
const RBDT_RESOLVE_DIRECTORY = 2;
const RBDT_RESOLVE_CJS_FILE = 3;
const RBDT_RESOLVE_CJS_FILE_AS_CHILD = 4;
@@ -59,7 +56,7 @@ const RBDT_FILE = 7;
const RBDT_DIRECTORY_DEPENDENCIES = 8;
const RBDT_FILE_DEPENDENCIES = 9;
/** @typedef {RBDT_RESOLVE_CJS | RBDT_RESOLVE_ESM | RBDT_RESOLVE_DIRECTORY | RBDT_RESOLVE_CJS_FILE | RBDT_RESOLVE_CJS_FILE_AS_CHILD | RBDT_RESOLVE_ESM_FILE | RBDT_DIRECTORY | RBDT_FILE | RBDT_DIRECTORY_DEPENDENCIES | RBDT_FILE_DEPENDENCIES} JobType */
/** @typedef {RBDT_RESOLVE_INITIAL | RBDT_RESOLVE_FILE | RBDT_RESOLVE_DIRECTORY | RBDT_RESOLVE_CJS_FILE | RBDT_RESOLVE_CJS_FILE_AS_CHILD | RBDT_RESOLVE_ESM_FILE | RBDT_DIRECTORY | RBDT_FILE | RBDT_DIRECTORY_DEPENDENCIES | RBDT_FILE_DEPENDENCIES} JobType */
const INVALID = Symbol("invalid");
@@ -168,13 +165,18 @@ class SnapshotIterator {
}
}
/** @typedef {Map<string, TODO> | Set<string> | undefined} SnapshotMap */
/** @typedef {(snapshot: Snapshot) => SnapshotMap[]} GetMapsFunction */
/**
* @template T
* @typedef {(snapshot: Snapshot) => T[]} GetMapsFunction
*/
/**
* @template T
*/
class SnapshotIterable {
/**
* @param {Snapshot} snapshot snapshot
* @param {GetMapsFunction} getMaps get maps function
* @param {GetMapsFunction<T>} getMaps get maps function
*/
constructor(snapshot, getMaps) {
this.snapshot = snapshot;
@@ -185,9 +187,9 @@ class SnapshotIterable {
let state = 0;
/** @type {IterableIterator<string>} */
let it;
/** @type {GetMapsFunction} */
/** @type {GetMapsFunction<T>} */
let getMaps;
/** @type {SnapshotMap[]} */
/** @type {T[]} */
let maps;
/** @type {Snapshot} */
let snapshot;
@@ -206,7 +208,9 @@ class SnapshotIterable {
if (maps.length > 0) {
const map = maps.pop();
if (map !== undefined) {
it = map.keys();
it =
/** @type {Set<EXPECTED_ANY> | Map<string, EXPECTED_ANY>} */
(map).keys();
state = 2;
} else {
break;
@@ -539,8 +543,9 @@ class Snapshot {
}
/**
* @param {GetMapsFunction} getMaps first
* @returns {Iterable<string>} iterable
* @template T
* @param {GetMapsFunction<T>} getMaps first
* @returns {SnapshotIterable<T>} iterable
*/
_createIterable(getMaps) {
return new SnapshotIterable(this, getMaps);
@@ -658,6 +663,9 @@ class SnapshotOptimization {
* @returns {void}
*/
optimize(newSnapshot, capturedFiles) {
if (capturedFiles.size === 0) {
return;
}
/**
* @param {SnapshotOptimizationEntry} entry optimization entry
* @returns {void}
@@ -727,6 +735,7 @@ class SnapshotOptimization {
) {
continue;
}
/** @type {Set<string>} */
const nonSharedFiles = new Set();
const snapshotContent =
/** @type {NonNullable<SnapshotOptimizationEntry["snapshotContent"]>} */
@@ -1203,34 +1212,34 @@ class FileSystemInfo {
processor: this._getManagedItemDirectoryInfo.bind(this)
});
const _unmanagedPaths = [...unmanagedPaths];
this.unmanagedPathsWithSlash =
/** @type {string[]} */
(_unmanagedPaths.filter((p) => typeof p === "string")).map((p) =>
join(fs, p, "_").slice(0, -1)
);
this.unmanagedPathsRegExps =
/** @type {RegExp[]} */
(_unmanagedPaths.filter((p) => typeof p !== "string"));
/** @type {string[]} */
this.unmanagedPathsWithSlash = _unmanagedPaths
.filter((p) => typeof p === "string")
.map((p) => join(fs, p, "_").slice(0, -1));
/** @type {RegExp[]} */
this.unmanagedPathsRegExps = _unmanagedPaths.filter(
(p) => typeof p !== "string"
);
this.managedPaths = [...managedPaths];
this.managedPathsWithSlash =
/** @type {string[]} */
(this.managedPaths.filter((p) => typeof p === "string")).map((p) =>
join(fs, p, "_").slice(0, -1)
);
/** @type {string[]} */
this.managedPathsWithSlash = this.managedPaths
.filter((p) => typeof p === "string")
.map((p) => join(fs, p, "_").slice(0, -1));
/** @type {RegExp[]} */
this.managedPathsRegExps = this.managedPaths.filter(
(p) => typeof p !== "string"
);
this.managedPathsRegExps =
/** @type {RegExp[]} */
(this.managedPaths.filter((p) => typeof p !== "string"));
this.immutablePaths = [...immutablePaths];
this.immutablePathsWithSlash =
/** @type {string[]} */
(this.immutablePaths.filter((p) => typeof p === "string")).map((p) =>
join(fs, p, "_").slice(0, -1)
);
this.immutablePathsRegExps =
/** @type {RegExp[]} */
(this.immutablePaths.filter((p) => typeof p !== "string"));
/** @type {string[]} */
this.immutablePathsWithSlash = this.immutablePaths
.filter((p) => typeof p === "string")
.map((p) => join(fs, p, "_").slice(0, -1));
/** @type {RegExp[]} */
this.immutablePathsRegExps = this.immutablePaths.filter(
(p) => typeof p !== "string"
);
this._cachedDeprecatedFileTimestamps = undefined;
this._cachedDeprecatedContextTimestamps = undefined;
@@ -1614,16 +1623,12 @@ class FileSystemInfo {
/**
* @param {Job} job job
* @returns {`resolve commonjs file ${string}${string}`|`resolve esm file ${string}${string}`|`resolve esm ${string}${string}`|`resolve directory ${string}`|`file ${string}`|`unknown ${string} ${string}`|`resolve commonjs ${string}${string}`|`directory ${string}`|`file dependencies ${string}`|`directory dependencies ${string}`} result
* @returns {string} result
*/
const jobToString = (job) => {
switch (job.type) {
case RBDT_RESOLVE_CJS:
return `resolve commonjs ${job.path}${expectedToString(
job.expected
)}`;
case RBDT_RESOLVE_ESM:
return `resolve esm ${job.path}${expectedToString(job.expected)}`;
case RBDT_RESOLVE_FILE:
return `resolve file ${job.path}${expectedToString(job.expected)}`;
case RBDT_RESOLVE_DIRECTORY:
return `resolve directory ${job.path}`;
case RBDT_RESOLVE_CJS_FILE:
@@ -1665,7 +1670,7 @@ class FileSystemInfo {
deps,
(dep) =>
/** @type {Job} */ ({
type: RBDT_RESOLVE_CJS,
type: RBDT_RESOLVE_INITIAL,
context,
path: dep,
expected: undefined,
@@ -1769,27 +1774,23 @@ class FileSystemInfo {
}
);
};
switch (type) {
case RBDT_RESOLVE_CJS: {
const isDirectory = /[\\/]$/.test(path);
if (isDirectory) {
resolveDirectory(path.slice(0, -1));
} else {
resolveFile(path, "f", resolveCjs);
}
break;
}
case RBDT_RESOLVE_ESM: {
const isDirectory = /[\\/]$/.test(path);
if (isDirectory) {
resolveDirectory(path.slice(0, -1));
} else {
resolveFile(path);
}
const resolvedType =
type === RBDT_RESOLVE_INITIAL
? /[\\/]$/.test(path)
? RBDT_RESOLVE_DIRECTORY
: RBDT_RESOLVE_FILE
: type;
switch (resolvedType) {
case RBDT_RESOLVE_FILE: {
resolveFile(
path,
"f",
/\.mjs$/.test(path) ? resolveEsm : resolveCjs
);
break;
}
case RBDT_RESOLVE_DIRECTORY: {
resolveDirectory(path);
resolveDirectory(RBDT_RESOLVE_INITIAL ? path.slice(0, -1) : path);
break;
}
case RBDT_RESOLVE_CJS_FILE: {
@@ -1867,7 +1868,13 @@ class FileSystemInfo {
// Check commonjs cache for the module
/** @type {NodeModule | undefined} */
const module = require.cache[path];
if (module && Array.isArray(module.children)) {
if (
module &&
Array.isArray(module.children) &&
// https://github.com/nodejs/node/issues/59868
// Force use `es-module-lexer` for mjs
!/\.mjs$/.test(path)
) {
children: for (const child of module.children) {
const childPath = child.filename;
if (childPath) {
@@ -1947,6 +1954,7 @@ class FileSystemInfo {
const context = dirname(this.fs, path);
const source = /** @type {Buffer} */ (content).toString();
const [imports] = lexer.parse(source);
const added = new Set();
for (const imp of imports) {
try {
let dependency;
@@ -1964,9 +1972,11 @@ class FileSystemInfo {
continue;
}
// we should not track Node.js build dependencies
// We should not track Node.js build dependencies
if (dependency.startsWith("node:")) continue;
if (builtinModules.has(dependency)) continue;
// Avoid extra jobs for identical imports
if (added.has(dependency)) continue;
push({
type: RBDT_RESOLVE_ESM_FILE,
@@ -1975,6 +1985,7 @@ class FileSystemInfo {
expected: imp.d > -1 ? false : undefined,
issuer: job
});
added.add(dependency);
} catch (err1) {
logger.warn(
`Parsing of ${path} for build dependencies failed at 'import(${source.slice(
@@ -2336,6 +2347,9 @@ class FileSystemInfo {
* @param {ManagedFiles} capturedFiles captured files
*/
const processCapturedFiles = (capturedFiles) => {
if (capturedFiles.size === 0) {
return;
}
switch (mode) {
case 3:
this._fileTshsOptimization.optimize(snapshot, capturedFiles);
@@ -2424,6 +2438,9 @@ class FileSystemInfo {
* @param {ManagedContexts} capturedDirectories captured directories
*/
const processCapturedDirectories = (capturedDirectories) => {
if (capturedDirectories.size === 0) {
return;
}
switch (mode) {
case 3:
this._contextTshsOptimization.optimize(snapshot, capturedDirectories);
@@ -2569,6 +2586,9 @@ class FileSystemInfo {
* @param {ManagedMissing} capturedMissing captured missing
*/
const processCapturedMissing = (capturedMissing) => {
if (capturedMissing.size === 0) {
return;
}
this._missingExistenceOptimization.optimize(snapshot, capturedMissing);
for (const path of capturedMissing) {
const cache = this._fileTimestamps.get(path);
@@ -3330,7 +3350,7 @@ class FileSystemInfo {
hash.update(/** @type {string | Buffer} */ (content));
const digest = /** @type {string} */ (hash.digest("hex"));
const digest = hash.digest("hex");
this._fileHashes.set(path, digest);
@@ -3341,7 +3361,7 @@ class FileSystemInfo {
/**
* @private
* @param {string} path path
* @param {(err: WebpackError | null, timestampAndHash?: TimestampAndHash) => void} callback callback
* @param {(err: WebpackError | null, timestampAndHash?: TimestampAndHash | string) => void} callback callback
*/
_getFileTimestampAndHash(path, callback) {
/**
@@ -3361,7 +3381,7 @@ class FileSystemInfo {
return callback(null, result);
}
this._fileTshs.set(path, hash);
return callback(null, /** @type {TODO} */ (hash));
return callback(null, hash);
}
this.fileTimestampQueue.add(path, (err, entry) => {
if (err) {
@@ -3598,7 +3618,7 @@ class FileSystemInfo {
}
}
const digest = /** @type {string} */ (hash.digest("hex"));
const digest = hash.digest("hex");
/** @type {ContextFileSystemInfoEntry} */
const result = {
safeTime,
@@ -3661,7 +3681,7 @@ class FileSystemInfo {
null,
(entry.resolved = {
safeTime,
timestampHash: /** @type {string} */ (hash.digest("hex"))
timestampHash: hash.digest("hex")
})
);
}
@@ -3723,7 +3743,7 @@ class FileSystemInfo {
/** @type {ContextHash} */
const result = {
hash: /** @type {string} */ (hash.digest("hex"))
hash: hash.digest("hex")
};
if (symlinks) result.symlinks = symlinks;
return result;
@@ -3770,10 +3790,7 @@ class FileSystemInfo {
for (const h of hashes) {
hash.update(h);
}
callback(
null,
(entry.resolved = /** @type {string} */ (hash.digest("hex")))
);
callback(null, (entry.resolved = hash.digest("hex")));
}
);
}
@@ -3819,22 +3836,20 @@ class FileSystemInfo {
{
path,
fromImmutablePath: () =>
/** @type {ContextTimestampAndHash | null} */ (null),
/** @type {ContextTimestampAndHash | Omit<ContextTimestampAndHash, "safeTime"> | string | null} */ (
null
),
fromManagedItem: (info) => ({
safeTime: 0,
timestampHash: info,
hash: info || ""
}),
fromSymlink: (file, target, callback) => {
callback(
null,
/** @type {TODO} */
({
timestampHash: target,
hash: target,
symlinks: new Set([target])
})
);
callback(null, {
timestampHash: target,
hash: target,
symlinks: new Set([target])
});
},
fromFile: (file, stat, callback) => {
this._getFileTimestampAndHash(file, callback);
@@ -3892,8 +3907,8 @@ class FileSystemInfo {
/** @type {ContextTimestampAndHash} */
const result = {
safeTime,
timestampHash: /** @type {string} */ (tsHash.digest("hex")),
hash: /** @type {string} */ (hash.digest("hex"))
timestampHash: tsHash.digest("hex"),
hash: hash.digest("hex")
};
if (symlinks) result.symlinks = symlinks;
return result;
@@ -3961,8 +3976,8 @@ class FileSystemInfo {
null,
(entry.resolved = {
safeTime,
timestampHash: /** @type {string} */ (tsHash.digest("hex")),
hash: /** @type {string} */ (hash.digest("hex"))
timestampHash: tsHash.digest("hex"),
hash: hash.digest("hex")
})
);
}

View File

@@ -13,11 +13,10 @@ const ArrayQueue = require("./util/ArrayQueue");
const TupleQueue = require("./util/TupleQueue");
const { getEntryRuntime, mergeRuntimeOwned } = require("./util/runtime");
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Dependency").ReferencedExport} ReferencedExport */
/** @typedef {import("./Dependency").ReferencedExports} ReferencedExports */
/** @typedef {import("./ExportsInfo")} ExportsInfo */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
@@ -61,7 +60,7 @@ class FlagDependencyUsagePlugin {
/**
* @param {Module} module module to process
* @param {(string[] | ReferencedExport)[]} usedExports list of used exports
* @param {ReferencedExports} usedExports list of used exports
* @param {RuntimeSpec} runtime part of which runtime
* @param {boolean} forceSideEffects always apply side effects
* @returns {void}
@@ -168,7 +167,7 @@ class FlagDependencyUsagePlugin {
* @returns {void}
*/
const processModule = (module, runtime, forceSideEffects) => {
/** @type {Map<Module, (string[] | ReferencedExport)[] | Map<string, string[] | ReferencedExport>>} */
/** @type {Map<Module, ReferencedExports | Map<string, string[] | ReferencedExport>>} */
const map = new Map();
/** @type {ArrayQueue<DependenciesBlock>} */

View File

@@ -8,11 +8,9 @@
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./ConcatenationScope")} ConcatenationScope */
/** @typedef {import("./DependencyTemplate")} DependencyTemplate */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module").CodeGenerationResultData} CodeGenerationResultData */
/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
@@ -22,15 +20,6 @@
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/**
* @template T
* @typedef {import("./InitFragment")<T>} InitFragment
*/
/** @typedef {Map<"url", { [key: string]: string }> & Map<"fullContentHash", string> & Map<"contentHash", string> & Map<"filename", string> & Map<"assetInfo", AssetInfo> & Map<"chunkInitFragments", InitFragment<GenerateContext>[]>} KnownGenerateContextData */
/** @typedef {KnownGenerateContextData & Record<string, EXPECTED_ANY>} GenerateContextData */
/**
* @typedef {object} GenerateContext
* @property {DependencyTemplates} dependencyTemplates mapping from dependencies to templates
@@ -42,7 +31,7 @@
* @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules
* @property {CodeGenerationResults=} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that)
* @property {string} type which kind of code should be generated
* @property {() => GenerateContextData=} getData get access to the code generation data
* @property {() => CodeGenerationResultData=} getData get access to the code generation data
*/
/**

View File

@@ -5,11 +5,8 @@
"use strict";
/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Module")} Module */
/** @typedef {import(".").Entrypoint} Entrypoint */
/**

View File

@@ -7,8 +7,6 @@
const WebpackError = require("./WebpackError");
/** @typedef {import("./Module")} Module */
/**
* @template T
* @callback Callback

View File

@@ -44,13 +44,13 @@ const {
/** @typedef {import("estree").CallExpression} CallExpression */
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("estree").SpreadElement} SpreadElement */
/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputNormalized */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Chunk").ChunkId} ChunkId */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").Records} Records */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
@@ -59,10 +59,12 @@ const {
/** @typedef {import("./javascript/JavascriptParserHelpers").Range} Range */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {string[]} Requests */
/**
* @typedef {object} HMRJavascriptParserHooks
* @property {SyncBailHook<[Expression | SpreadElement, string[]], void>} hotAcceptCallback
* @property {SyncBailHook<[CallExpression, string[]], void>} hotAcceptWithoutCallback
* @property {SyncBailHook<[Expression | SpreadElement, Requests], void>} hotAcceptCallback
* @property {SyncBailHook<[CallExpression, Requests], void>} hotAcceptWithoutCallback
*/
/** @typedef {number} HotIndex */
@@ -147,7 +149,7 @@ class HotModuleReplacementPlugin {
/** @type {BasicEvaluatedExpression[]} */
(arg.items).filter((param) => param.isString());
}
/** @type {string[]} */
/** @type {Requests} */
const requests = [];
if (params.length > 0) {
for (const [idx, param] of params.entries()) {
@@ -400,13 +402,11 @@ class HotModuleReplacementPlugin {
* @returns {string} module hash
*/
const getModuleHash = (module) => {
if (
compilation.codeGenerationResults.has(module, chunk.runtime)
) {
return compilation.codeGenerationResults.getHash(
module,
chunk.runtime
);
const codeGenerationResults =
/** @type {CodeGenerationResults} */
(compilation.codeGenerationResults);
if (codeGenerationResults.has(module, chunk.runtime)) {
return codeGenerationResults.getHash(module, chunk.runtime);
}
nonCodeGeneratedModules.add(module, chunk.runtime);
return chunkGraph.getModuleHash(module, chunk.runtime);
@@ -500,14 +500,14 @@ class HotModuleReplacementPlugin {
) {
return;
}
const codeGenerationResults =
/** @type {CodeGenerationResults} */
(compilation.codeGenerationResults);
for (const [module, chunk] of fullHashModules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = nonCodeGeneratedModules.has(module, chunk.runtime)
? chunkGraph.getModuleHash(module, chunk.runtime)
: compilation.codeGenerationResults.getHash(
module,
chunk.runtime
);
: codeGenerationResults.getHash(module, chunk.runtime);
if (records.chunkModuleHashes[key] !== hash) {
updatedModules.add(module, chunk);
}
@@ -527,8 +527,7 @@ class HotModuleReplacementPlugin {
forEachRuntime(allOldRuntime, (runtime) => {
const { path: filename, info: assetInfo } =
compilation.getPathWithInfo(
/** @type {NonNullable<OutputNormalized["hotUpdateMainFilename"]>} */
(compilation.outputOptions.hotUpdateMainFilename),
compilation.outputOptions.hotUpdateMainFilename,
{
hash: records.hash,
runtime
@@ -548,7 +547,7 @@ class HotModuleReplacementPlugin {
if (hotUpdateMainContentByRuntime.size === 0) return;
// Create a list of all active modules to verify which modules are removed completely
/** @type {Map<number | string, Module>} */
/** @type {Map<ModuleId, Module>} */
const allModules = new Map();
for (const module of compilation.modules) {
const id =
@@ -558,7 +557,7 @@ class HotModuleReplacementPlugin {
}
// List of completely removed modules
/** @type {Set<string | number>} */
/** @type {Set<ModuleId>} */
const completelyRemovedModules = new Set();
for (const key of Object.keys(records.chunkHashes)) {
@@ -646,10 +645,7 @@ class HotModuleReplacementPlugin {
// Module is still in the same runtime combination
const hash = nonCodeGeneratedModules.has(module, newRuntime)
? chunkGraph.getModuleHash(module, newRuntime)
: compilation.codeGenerationResults.getHash(
module,
newRuntime
);
: codeGenerationResults.getHash(module, newRuntime);
if (hash !== oldHash) {
if (module.type === WEBPACK_MODULE_TYPE_RUNTIME) {
newRuntimeModules = newRuntimeModules || [];
@@ -733,7 +729,9 @@ class HotModuleReplacementPlugin {
outputOptions: compilation.outputOptions,
moduleTemplates: compilation.moduleTemplates,
dependencyTemplates: compilation.dependencyTemplates,
codeGenerationResults: compilation.codeGenerationResults,
codeGenerationResults: /** @type {CodeGenerationResults} */ (
compilation.codeGenerationResults
),
runtimeTemplate: compilation.runtimeTemplate,
moduleGraph: compilation.moduleGraph,
chunkGraph

View File

@@ -7,9 +7,6 @@
const Chunk = require("./Chunk");
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./util/Hash")} Hash */
class HotUpdateChunk extends Chunk {
constructor() {
super();

View File

@@ -12,6 +12,7 @@ const createSchemaValidation = require("./util/create-schema-validation");
/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./NormalModuleFactory").ResolveData} ResolveData */
/** @typedef {import("./ContextModuleFactory").BeforeContextResolveData} BeforeContextResolveData */
const validate = createSchemaValidation(
require("../schemas/plugins/IgnorePlugin.check"),
@@ -22,6 +23,8 @@ const validate = createSchemaValidation(
}
);
/** @typedef {(resource: string, context: string) => boolean} CheckResourceFn */
const PLUGIN_NAME = "IgnorePlugin";
class IgnorePlugin {
@@ -36,8 +39,8 @@ class IgnorePlugin {
/**
* Note that if "contextRegExp" is given, both the "resourceRegExp" and "contextRegExp" have to match.
* @param {ResolveData} resolveData resolve data
* @returns {false|undefined} returns false when the request should be ignored, otherwise undefined
* @param {ResolveData | BeforeContextResolveData} resolveData resolve data
* @returns {false | undefined} returns false when the request should be ignored, otherwise undefined
*/
checkIgnore(resolveData) {
if (

View File

@@ -13,18 +13,32 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {string} InitFragmentKey */
/**
* @template GenerateContext
* @typedef {object} MaybeMergeableInitFragment
* @property {InitFragmentKey=} key
* @property {number} stage
* @property {number} position
* @property {(context: GenerateContext) => string | Source | undefined} getContent
* @property {(context: GenerateContext) => string | Source | undefined} getEndContent
* @property {(fragments: MaybeMergeableInitFragment<GenerateContext>) => MaybeMergeableInitFragment<GenerateContext>=} merge
* @property {(fragments: MaybeMergeableInitFragment<GenerateContext>[]) => MaybeMergeableInitFragment<GenerateContext>[]=} mergeAll
*/
/**
* @template T
* @param {InitFragment<T>} fragment the init fragment
* @param {T} fragment the init fragment
* @param {number} index index
* @returns {[InitFragment<T>, number]} tuple with both
* @returns {[T, number]} tuple with both
*/
const extractFragmentIndex = (fragment, index) => [fragment, index];
/**
* @template T
* @param {[InitFragment<T>, number]} a first pair
* @param {[InitFragment<T>, number]} b second pair
* @param {[MaybeMergeableInitFragment<T>, number]} a first pair
* @param {[MaybeMergeableInitFragment<T>, number]} b second pair
* @returns {number} sort value
*/
const sortFragmentWithIndex = ([a, i], [b, j]) => {
@@ -37,13 +51,14 @@ const sortFragmentWithIndex = ([a, i], [b, j]) => {
/**
* @template GenerateContext
* @implements {MaybeMergeableInitFragment<GenerateContext>}
*/
class InitFragment {
/**
* @param {string | Source | undefined} content the source code that will be included as initialization code
* @param {number} stage category of initialization code (contribute to order)
* @param {number} position position in the category (contribute to order)
* @param {string=} key unique key to avoid emitting the same initialization code twice
* @param {InitFragmentKey=} key unique key to avoid emitting the same initialization code twice
* @param {string | Source=} endContent the source code that will be included at the end of the module
*/
constructor(content, stage, position, key, endContent) {
@@ -64,7 +79,7 @@ class InitFragment {
/**
* @param {GenerateContext} context context
* @returns {string | Source=} the source code that will be included at the end of the module
* @returns {string | Source | undefined} the source code that will be included at the end of the module
*/
getEndContent(context) {
return this.endContent;
@@ -72,9 +87,8 @@ class InitFragment {
/**
* @template Context
* @template T
* @param {Source} source sources
* @param {InitFragment<T>[]} initFragments init fragments
* @param {MaybeMergeableInitFragment<Context>[]} initFragments init fragments
* @param {Context} context context
* @returns {Source} source
*/
@@ -87,14 +101,10 @@ class InitFragment {
.sort(sortFragmentWithIndex);
// Deduplicate fragments. If a fragment has no key, it is always included.
/** @type {Map<InitFragmentKey | symbol, MaybeMergeableInitFragment<Context> | MaybeMergeableInitFragment<Context>[]>} */
const keyedFragments = new Map();
for (const [fragment] of sortedFragments) {
if (
typeof (
/** @type {InitFragment<T> & { mergeAll?: (fragments: InitFragment<Context>[]) => InitFragment<Context>[] }} */
(fragment).mergeAll
) === "function"
) {
if (typeof fragment.mergeAll === "function") {
if (!fragment.key) {
throw new Error(
`InitFragment with mergeAll function must have a valid key: ${fragment.constructor.name}`
@@ -110,9 +120,12 @@ class InitFragment {
}
continue;
} else if (typeof fragment.merge === "function") {
const oldValue = keyedFragments.get(fragment.key);
const key = /** @type {InitFragmentKey} */ (fragment.key);
const oldValue =
/** @type {MaybeMergeableInitFragment<Context>} */
(keyedFragments.get(key));
if (oldValue !== undefined) {
keyedFragments.set(fragment.key, fragment.merge(oldValue));
keyedFragments.set(key, fragment.merge(oldValue));
continue;
}
}
@@ -123,10 +136,19 @@ class InitFragment {
const endContents = [];
for (let fragment of keyedFragments.values()) {
if (Array.isArray(fragment)) {
fragment = fragment[0].mergeAll(fragment);
fragment =
/** @type {[MaybeMergeableInitFragment<Context> & { mergeAll: (fragments: MaybeMergeableInitFragment<Context>[]) => MaybeMergeableInitFragment<Context>[] }, ...MaybeMergeableInitFragment<Context>[]]} */
(fragment)[0].mergeAll(fragment);
}
concatSource.add(fragment.getContent(context));
const endContent = fragment.getEndContent(context);
const content =
/** @type {MaybeMergeableInitFragment<Context>} */
(fragment).getContent(context);
if (content) {
concatSource.add(content);
}
const endContent =
/** @type {MaybeMergeableInitFragment<Context>} */
(fragment).getEndContent(context);
if (endContent) {
endContents.push(endContent);
}
@@ -170,16 +192,6 @@ class InitFragment {
makeSerializable(InitFragment, "webpack/lib/InitFragment");
InitFragment.prototype.merge =
/** @type {TODO} */
(undefined);
InitFragment.prototype.getImported =
/** @type {TODO} */
(undefined);
InitFragment.prototype.setImported =
/** @type {TODO} */
(undefined);
InitFragment.STAGE_CONSTANTS = 10;
InitFragment.STAGE_ASYNC_BOUNDARY = 20;
InitFragment.STAGE_HARMONY_EXPORTS = 30;

View File

@@ -8,7 +8,6 @@
const WebpackError = require("./WebpackError");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Module")} Module */
class InvalidDependenciesModuleWarning extends WebpackError {

View File

@@ -15,12 +15,13 @@ const { dirname, mkdirp } = require("./util/fs");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Compiler").IntermediateFileSystem} IntermediateFileSystem */
/** @typedef {import("./Module").BuildMeta} BuildMeta */
/** @typedef {import("./ExportsInfo").ExportInfoName} ExportInfoName */
/**
* @typedef {object} ManifestModuleData
* @property {string | number} id
* @property {ModuleId} id
* @property {BuildMeta=} buildMeta
* @property {boolean | string[]=} exports
* @property {ExportInfoName[]=} exports
*/
/**
@@ -92,10 +93,7 @@ class LibManifestPlugin {
continue;
}
const ident = module.libIdent({
context:
this.options.context ||
/** @type {string} */
(compiler.options.context),
context: this.options.context || compiler.context,
associatedObjectForCache: compiler.root
});
if (ident) {

View File

@@ -11,7 +11,6 @@ const createSchemaValidation = require("./util/create-schema-validation");
/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./ModuleFilenameHelpers").Matcher} Matcher */
/** @typedef {import("./ModuleFilenameHelpers").MatchObject} MatchObject */
/**
@@ -39,15 +38,7 @@ class LoaderOptionsPlugin {
// If no options are set then generate empty options object
if (typeof options !== "object") options = {};
if (!options.test) {
/** @type {Partial<RegExp>} */
const defaultTrueMockRegExp = {
test: () => true
};
/** @type {RegExp} */
options.test =
/** @type {RegExp} */
(defaultTrueMockRegExp);
options.test = () => true;
}
this.options = options;
}

View File

@@ -11,7 +11,6 @@ const RuntimeGlobals = require("./RuntimeGlobals");
const memoize = require("./util/memoize");
/** @typedef {import("tapable").Tap} Tap */
/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */
/** @typedef {import("./ModuleTemplate")} ModuleTemplate */
@@ -19,19 +18,13 @@ const memoize = require("./util/memoize");
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").AssetInfo} AssetInfo */
/** @typedef {import("./Compilation").InterpolatedPathAndAssetInfo} InterpolatedPathAndAssetInfo */
/** @typedef {import("./Module")} Module} */
/** @typedef {import("./util/Hash")} Hash} */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates} */
/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext} */
/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderBootstrapContext} RenderBootstrapContext} */
/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkHashContext} ChunkHashContext} */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate} */
/** @typedef {import("./ModuleGraph")} ModuleGraph} */
/** @typedef {import("./ChunkGraph")} ChunkGraph} */
/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions} */
/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry} */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath} */
/** @typedef {import("./TemplatedPathPlugin").PathData} PathData} */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderBootstrapContext} RenderBootstrapContext */
/** @typedef {import("./Template").RenderManifestOptions} RenderManifestOptions */
/** @typedef {import("./Template").RenderManifestEntry} RenderManifestEntry */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
/** @typedef {import("./TemplatedPathPlugin").PathData} PathData */
/**
* @template T
* @typedef {import("tapable").IfSet<T>} IfSet
@@ -324,11 +317,7 @@ class MainTemplate {
* @param {PathData} options context data
* @returns {string} interpolated path
*/ (options) =>
compilation.getAssetPath(
/** @type {string} */
(compilation.outputOptions.publicPath),
options
),
compilation.getAssetPath(compilation.outputOptions.publicPath, options),
"MainTemplate.getPublicPath is deprecated (use Compilation.getAssetPath(compilation.outputOptions.publicPath, options) instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_GET_PUBLIC_PATH"
);

52
node_modules/webpack/lib/Module.js generated vendored
View File

@@ -17,7 +17,7 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
@@ -30,15 +30,19 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplate").CssData} CssData */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./ExportsInfo").UsageStateType} UsageStateType */
/** @typedef {import("./FileSystemInfo")} FileSystemInfo */
/** @typedef {import("./FileSystemInfo").Snapshot} Snapshot */
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
/** @typedef {import("./ModuleTypeConstants").ModuleTypes} ModuleTypes */
/** @typedef {import("./ModuleGraph").OptimizationBailouts} OptimizationBailouts */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/**
* @template T
* @typedef {import("./InitFragment")<T>} InitFragment
*/
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./json/JsonData")} JsonData */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
@@ -54,11 +58,6 @@ const makeSerializable = require("./util/makeSerializable");
* @typedef {import("./util/LazySet")<T>} LazySet<T>
*/
/**
* @template T
* @typedef {import("./util/SortableSet")<T>} SortableSet<T>
*/
/**
* @typedef {object} SourceContext
* @property {DependencyTemplates} dependencyTemplates the dependency templates
@@ -94,10 +93,16 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {Set<string>} RuntimeRequirements */
/** @typedef {ReadonlySet<string>} ReadOnlyRuntimeRequirements */
/** @typedef {Map<"topLevelDeclarations", Set<string>> & Map<"chunkInitFragments", InitFragment<EXPECTED_ANY>[]>} KnownCodeGenerationResultDataForJavascriptModules */
/** @typedef {Map<"url", { ["css-url"]: string }>} KnownCodeGenerationResultDataForCssModules */
/** @typedef {Map<"filename", string> & Map<"assetInfo", AssetInfo> & Map<"fullContentHash", string>} KnownCodeGenerationResultDataForAssetModules */
/** @typedef {Map<"share-init", [{ shareScope: string, initStage: number, init: string }]>} KnownCodeGenerationResultForSharing */
/** @typedef {KnownCodeGenerationResultDataForJavascriptModules & KnownCodeGenerationResultDataForCssModules & KnownCodeGenerationResultDataForAssetModules & KnownCodeGenerationResultForSharing & Map<string, EXPECTED_ANY>} CodeGenerationResultData */
/**
* @typedef {object} CodeGenerationResult
* @property {Map<string, Source>} sources the resulting sources for all source types
* @property {Map<string, TODO>=} data the resulting data for all source types
* @property {CodeGenerationResultData=} data the resulting data for all source types
* @property {ReadOnlyRuntimeRequirements | null} runtimeRequirements the runtime requirements
* @property {string=} hash a hash of the code generation result (will be automatically calculated from sources and runtimeRequirements if not provided)
*/
@@ -113,6 +118,7 @@ const makeSerializable = require("./util/makeSerializable");
* @property {("default" | "namespace" | "flagged" | "dynamic")=} exportsType
* @property {(false | "redirect" | "redirect-warn")=} defaultObject
* @property {boolean=} strictHarmonyModule
* @property {boolean=} treatAsCommonJs
* @property {boolean=} async
* @property {boolean=} sideEffectFree
* @property {boolean=} isCSSModule
@@ -121,6 +127,8 @@ const makeSerializable = require("./util/makeSerializable");
* @property {string=} factoryExportsBinding
*/
/** @typedef {LazySet<string>} FileSystemDependencies */
/**
* @typedef {object} KnownBuildInfo
* @property {boolean=} cacheable
@@ -131,10 +139,10 @@ const makeSerializable = require("./util/makeSerializable");
* @property {string=} moduleConcatenationBailout using in CommonJs
* @property {boolean=} needCreateRequire using in APIPlugin
* @property {string=} resourceIntegrity using in HttpUriPlugin
* @property {LazySet<string>=} fileDependencies using in NormalModule
* @property {LazySet<string>=} contextDependencies using in NormalModule
* @property {LazySet<string>=} missingDependencies using in NormalModule
* @property {LazySet<string>=} buildDependencies using in NormalModule
* @property {FileSystemDependencies=} fileDependencies using in NormalModule
* @property {FileSystemDependencies=} contextDependencies using in NormalModule
* @property {FileSystemDependencies=} missingDependencies using in NormalModule
* @property {FileSystemDependencies=} buildDependencies using in NormalModule
* @property {ValueCacheVersions=} valueDependencies using in NormalModule
* @property {Record<string, Source>=} assets using in NormalModule
* @property {Map<string, AssetInfo | undefined>=} assetsInfo using in NormalModule
@@ -151,7 +159,8 @@ const makeSerializable = require("./util/makeSerializable");
* @property {Set<string>=} topLevelDeclarations top level declaration names
*/
/** @typedef {Map<string, string | Set<string>>} ValueCacheVersions */
/** @typedef {string | Set<string>} ValueCacheVersion */
/** @typedef {Map<string, ValueCacheVersion>} ValueCacheVersions */
/**
* @typedef {object} NeedBuildContext
@@ -193,6 +202,9 @@ const deprecatedNeedRebuild = util.deprecate(
"DEP_WEBPACK_MODULE_NEED_REBUILD"
);
/** @typedef {string} LibIdent */
/** @typedef {string} NameForCondition */
/** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */
class Module extends DependenciesBlock {
@@ -412,7 +424,7 @@ class Module extends DependenciesBlock {
/**
* @deprecated
* @returns {(string | OptimizationBailoutFunction)[]} list
* @returns {OptimizationBailouts} list
*/
get optimizationBailout() {
return ModuleGraph.getModuleGraphForModule(
@@ -967,14 +979,14 @@ class Module extends DependenciesBlock {
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
* @returns {LibIdent | null} an identifier for library inclusion
*/
libIdent(options) {
return null;
}
/**
* @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
* @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path)
*/
nameForCondition() {
return null;
@@ -1091,10 +1103,10 @@ class Module extends DependenciesBlock {
}
/**
* @param {LazySet<string>} fileDependencies set where file dependencies are added to
* @param {LazySet<string>} contextDependencies set where context dependencies are added to
* @param {LazySet<string>} missingDependencies set where missing dependencies are added to
* @param {LazySet<string>} buildDependencies set where build dependencies are added to
* @param {FileSystemDependencies} fileDependencies set where file dependencies are added to
* @param {FileSystemDependencies} contextDependencies set where context dependencies are added to
* @param {FileSystemDependencies} missingDependencies set where missing dependencies are added to
* @param {FileSystemDependencies} buildDependencies set where build dependencies are added to
*/
addCacheDependencies(
fileDependencies,

View File

@@ -23,7 +23,7 @@
/**
* @typedef {object} ModuleFactoryCreateDataContextInfo
* @property {string} issuer
* @property {IssuerLayer=} issuerLayer
* @property {IssuerLayer} issuerLayer
* @property {string=} compiler
*/

View File

@@ -10,13 +10,12 @@ const { DEFAULTS } = require("./config/defaults");
const createHash = require("./util/createHash");
const memoize = require("./util/memoize");
/** @typedef {import("../declarations/WebpackOptions").DevtoolModuleFilenameTemplate} DevtoolModuleFilenameTemplate */
/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {string | RegExp | (string | RegExp)[]} Matcher */
/** @typedef {string | RegExp | ((str: string) => boolean) | (string | RegExp | ((str: string) => boolean))[]} Matcher */
/** @typedef {{ test?: Matcher, include?: Matcher, exclude?: Matcher }} MatchObject */
const ModuleFilenameHelpers = module.exports;
@@ -85,7 +84,7 @@ const getHash =
() => {
const hash = createHash(hashFunction);
hash.update(strFn());
const digest = /** @type {string} */ (hash.digest("hex"));
const digest = hash.digest("hex");
return digest.slice(0, 4);
};
@@ -94,10 +93,10 @@ const getHash =
* Returns a lazy object. The object is lazy in the sense that the properties are
* only evaluated when they are accessed. This is only obtained by setting a function as the value for each key.
* @param {Record<string, () => T>} obj the object to convert to a lazy access object
* @returns {T} the lazy access object
* @returns {Record<string, T>} the lazy access object
*/
const lazyObject = (obj) => {
const newObj = /** @type {T} */ ({});
const newObj = /** @type {Record<string, T>} */ ({});
for (const key of Object.keys(obj)) {
const fn = obj[key];
Object.defineProperty(newObj, key, {
@@ -117,8 +116,21 @@ const lazyObject = (obj) => {
};
const SQUARE_BRACKET_TAG_REGEXP = /\[\\*([\w-]+)\\*\]/gi;
/** @typedef {((context: TODO) => string)} ModuleFilenameTemplateFunction */
/**
* @typedef {object} ModuleFilenameTemplateContext
* @property {string} identifier the identifier of the module
* @property {string} shortIdentifier the shortened identifier of the module
* @property {string} resource the resource of the module request
* @property {string} resourcePath the resource path of the module request
* @property {string} absoluteResourcePath the absolute resource path of the module request
* @property {string} loaders the loaders of the module request
* @property {string} allLoaders the all loaders of the module request
* @property {string} query the query of the module identifier
* @property {string} moduleId the module id of the module
* @property {string} hash the hash of the module identifier
* @property {string} namespace the module namespace
*/
/** @typedef {((context: ModuleFilenameTemplateContext) => string)} ModuleFilenameTemplateFunction */
/** @typedef {string | ModuleFilenameTemplateFunction} ModuleFilenameTemplate */
/**
@@ -190,19 +202,22 @@ ModuleFilenameHelpers.createFilename = (
};
if (typeof opts.moduleFilenameTemplate === "function") {
return opts.moduleFilenameTemplate(
lazyObject({
identifier,
shortIdentifier,
resource,
resourcePath: memoize(resourcePath),
absoluteResourcePath: memoize(absoluteResourcePath),
loaders: memoize(loaders),
allLoaders: memoize(allLoaders),
query: memoize(query),
moduleId: memoize(moduleId),
hash: memoize(hash),
namespace: () => opts.namespace
})
/** @type {ModuleFilenameTemplateContext} */
(
lazyObject({
identifier,
shortIdentifier,
resource,
resourcePath: memoize(resourcePath),
absoluteResourcePath: memoize(absoluteResourcePath),
loaders: memoize(loaders),
allLoaders: memoize(allLoaders),
query: memoize(query),
moduleId: memoize(moduleId),
hash: memoize(hash),
namespace: () => opts.namespace
})
)
);
}
@@ -319,13 +334,15 @@ ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => {
*/
const matchPart = (str, test) => {
if (!test) return true;
if (Array.isArray(test)) {
return test.some((test) => matchPart(str, test));
}
if (typeof test === "string") {
if (test instanceof RegExp) {
return test.test(str);
} else if (typeof test === "string") {
return str.startsWith(test);
} else if (typeof test === "function") {
return test(str);
}
return test.test(str);
return test.some((test) => matchPart(str, test));
};
ModuleFilenameHelpers.matchPart = matchPart;

View File

@@ -17,6 +17,7 @@ const { sortWithSourceOrder } = require("./util/comparators");
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./ExportsInfo").ExportInfo} ExportInfo */
/** @typedef {import("./ExportsInfo").ExportInfoName} ExportInfoName */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleProfile")} ModuleProfile */
/** @typedef {import("./RequestShortener")} RequestShortener */
@@ -37,7 +38,7 @@ const EMPTY_SET = new Set();
* @template {Module | null | undefined} T
* @param {SortableSet<ModuleGraphConnection>} set input
* @param {(connection: ModuleGraphConnection) => T} getKey function to extract key from connection
* @returns {readonly Map<T, readonly ModuleGraphConnection[]>} mapped by key
* @returns {ReadonlyMap<T, ReadonlyArray<ModuleGraphConnection>>} mapped by key
*/
const getConnectionsByKey = (set, getKey) => {
const map = new Map();
@@ -68,20 +69,22 @@ const getConnectionsByKey = (set, getKey) => {
/**
* @param {SortableSet<ModuleGraphConnection>} set input
* @returns {readonly Map<Module | undefined | null, readonly ModuleGraphConnection[]>} mapped by origin module
* @returns {ReadonlyMap<Module | undefined | null, ReadonlyArray<ModuleGraphConnection>>} mapped by origin module
*/
const getConnectionsByOriginModule = (set) =>
getConnectionsByKey(set, (connection) => connection.originModule);
/**
* @param {SortableSet<ModuleGraphConnection>} set input
* @returns {readonly Map<Module | undefined, readonly ModuleGraphConnection[]>} mapped by module
* @returns {ReadonlyMap<Module | undefined, ReadonlyArray<ModuleGraphConnection>>} mapped by module
*/
const getConnectionsByModule = (set) =>
getConnectionsByKey(set, (connection) => connection.module);
/** @typedef {SortableSet<ModuleGraphConnection>} IncomingConnections */
/** @typedef {SortableSet<ModuleGraphConnection>} OutgoingConnections */
/** @typedef {Module | null | undefined} Issuer */
/** @typedef {(string | OptimizationBailoutFunction)[]} OptimizationBailouts */
class ModuleGraphModule {
constructor() {
@@ -89,9 +92,9 @@ class ModuleGraphModule {
this.incomingConnections = new SortableSet();
/** @type {OutgoingConnections | undefined} */
this.outgoingConnections = undefined;
/** @type {Module | null | undefined} */
/** @type {Issuer} */
this.issuer = undefined;
/** @type {(string | OptimizationBailoutFunction)[]} */
/** @type {OptimizationBailouts} */
this.optimizationBailout = [];
/** @type {ExportsInfo} */
this.exports = new ExportsInfo();
@@ -113,7 +116,18 @@ class ModuleGraphModule {
/** @typedef {(moduleGraphConnection: ModuleGraphConnection) => boolean} FilterConnection */
/** @typedef {EXPECTED_OBJECT} MetaKey */
/** @typedef {TODO} Meta */
/** @typedef {import("./dependencies/CommonJsExportRequireDependency").idsSymbol} CommonJsExportRequireDependencyIDsSymbol */
/** @typedef {import("./dependencies/HarmonyImportSpecifierDependency").idsSymbol} HarmonyImportSpecifierDependencyIDsSymbol */
/** @typedef {import("./dependencies/HarmonyExportImportedSpecifierDependency").idsSymbol} HarmonyExportImportedSpecifierDependencyIDsSymbol */
/**
* @typedef {object} KnownMeta
* @property {Map<Module, string>=} importVarMap
* @property {Map<Module, string>=} deferredImportVarMap
*/
/** @typedef {KnownMeta & Record<CommonJsExportRequireDependencyIDsSymbol | HarmonyImportSpecifierDependencyIDsSymbol | HarmonyExportImportedSpecifierDependencyIDsSymbol, string[]> & Record<string, EXPECTED_ANY>} Meta */
class ModuleGraph {
constructor() {
@@ -567,7 +581,7 @@ class ModuleGraph {
/**
* @param {Module} module the module
* @returns {readonly Map<Module | undefined | null, readonly ModuleGraphConnection[]>} reasons why a module is included, in a map by source module
* @returns {ReadonlyMap<Module | undefined | null, ReadonlyArray<ModuleGraphConnection>>} reasons why a module is included, in a map by source module
*/
getIncomingConnectionsByOriginModule(module) {
const connections = this._getModuleGraphModule(module).incomingConnections;
@@ -576,7 +590,7 @@ class ModuleGraph {
/**
* @param {Module} module the module
* @returns {readonly Map<Module | undefined, readonly ModuleGraphConnection[]> | undefined} connections to modules, in a map by module
* @returns {ReadonlyMap<Module | undefined, ReadonlyArray<ModuleGraphConnection>> | undefined} connections to modules, in a map by module
*/
getOutgoingConnectionsByModule(module) {
const connections = this._getModuleGraphModule(module).outgoingConnections;
@@ -606,7 +620,7 @@ class ModuleGraph {
/**
* @param {Module} module the module
* @returns {Module | null | undefined} the issuer module
* @returns {Issuer} the issuer module
*/
getIssuer(module) {
const mgm = this._getModuleGraphModule(module);
@@ -635,7 +649,7 @@ class ModuleGraph {
/**
* @param {Module} module the module
* @returns {(string | OptimizationBailoutFunction)[]} optimization bailouts
* @returns {OptimizationBailouts} optimization bailouts
*/
getOptimizationBailout(module) {
const mgm = this._getModuleGraphModule(module);
@@ -644,7 +658,7 @@ class ModuleGraph {
/**
* @param {Module} module the module
* @returns {true | string[] | null} the provided exports
* @returns {null | true | ExportInfoName[]} the provided exports
*/
getProvidedExports(module) {
const mgm = this._getModuleGraphModule(module);
@@ -653,7 +667,7 @@ class ModuleGraph {
/**
* @param {Module} module the module
* @param {string | string[]} exportName a name of an export
* @param {ExportInfoName | ExportInfoName[]} exportName a name of an export
* @returns {boolean | null} true, if the export is provided by the module.
* null, if it's unknown.
* false, if it's not provided.
@@ -851,7 +865,7 @@ class ModuleGraph {
getMeta(thing) {
let meta = this._metaMap.get(thing);
if (meta === undefined) {
meta = Object.create(null);
meta = /** @type {Meta} */ (Object.create(null));
this._metaMap.set(thing, meta);
}
return meta;
@@ -879,10 +893,10 @@ class ModuleGraph {
}
/**
* @template T
* @template {EXPECTED_ANY[]} T
* @template R
* @param {(moduleGraph: ModuleGraph, ...args: T[]) => R} fn computer
* @param {...T} args arguments
* @param {(moduleGraph: ModuleGraph, ...args: T) => R} fn computer
* @param {T} args arguments
* @returns {R} computed value or cached
*/
cached(fn, ...args) {

View File

@@ -18,7 +18,6 @@ const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").BuildMeta} BuildMeta */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleTemplate")} ModuleTemplate */
/** @typedef {import("./RequestShortener")} RequestShortener */
/**

View File

@@ -11,11 +11,9 @@ const memoize = require("./util/memoize");
/** @typedef {import("tapable").Tap} Tap */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./javascript/JavascriptModulesPlugin").ChunkRenderContext} ChunkRenderContext */
/** @typedef {import("./javascript/JavascriptModulesPlugin").ModuleRenderContext} ModuleRenderContext */

View File

@@ -89,6 +89,12 @@ const ASSET_MODULE_TYPE_RESOURCE = "asset/resource";
*/
const ASSET_MODULE_TYPE_SOURCE = "asset/source";
/**
* @type {Readonly<"asset/bytes">}
* This is the module type used for assets that are imported as Uint8Array.
*/
const ASSET_MODULE_TYPE_BYTES = "asset/bytes";
/**
* @type {Readonly<"asset/raw-data-url">}
* TODO: Document what this asset type is for. See css-loader tests for its usage.
@@ -137,17 +143,19 @@ const WEBPACK_MODULE_TYPE_LAZY_COMPILATION_PROXY = "lazy-compilation-proxy";
/** @typedef {"javascript/auto" | "javascript/dynamic" | "javascript/esm"} JavaScriptModuleTypes */
/** @typedef {"json"} JSONModuleType */
/** @typedef {"webassembly/async" | "webassembly/sync"} WebAssemblyModuleTypes */
/** @typedef {"css" | "css/global" | "css/module"} CSSModuleTypes */
/** @typedef {"css" | "css/global" | "css/module" | "css/auto"} CSSModuleTypes */
/** @typedef {"asset" | "asset/inline" | "asset/resource" | "asset/source" | "asset/raw-data-url"} AssetModuleTypes */
/** @typedef {"runtime" | "fallback-module" | "remote-module" | "provide-module" | "consume-shared-module" | "lazy-compilation-proxy"} WebpackModuleTypes */
/** @typedef {string} UnknownModuleTypes */
/** @typedef {JavaScriptModuleTypes | JSONModuleType | WebAssemblyModuleTypes | CSSModuleTypes | AssetModuleTypes | WebpackModuleTypes | UnknownModuleTypes} ModuleTypes */
module.exports.ASSET_MODULE_TYPE = ASSET_MODULE_TYPE;
module.exports.ASSET_MODULE_TYPE_BYTES = ASSET_MODULE_TYPE_BYTES;
module.exports.ASSET_MODULE_TYPE_INLINE = ASSET_MODULE_TYPE_INLINE;
module.exports.ASSET_MODULE_TYPE_RAW_DATA_URL = ASSET_MODULE_TYPE_RAW_DATA_URL;
module.exports.ASSET_MODULE_TYPE_RESOURCE = ASSET_MODULE_TYPE_RESOURCE;
module.exports.ASSET_MODULE_TYPE_SOURCE = ASSET_MODULE_TYPE_SOURCE;
/** @type {CSSModuleTypes[]} */
module.exports.CSS_MODULES = [
CSS_MODULE_TYPE,
CSS_MODULE_TYPE_GLOBAL,
@@ -158,6 +166,7 @@ module.exports.CSS_MODULE_TYPE = CSS_MODULE_TYPE;
module.exports.CSS_MODULE_TYPE_AUTO = CSS_MODULE_TYPE_AUTO;
module.exports.CSS_MODULE_TYPE_GLOBAL = CSS_MODULE_TYPE_GLOBAL;
module.exports.CSS_MODULE_TYPE_MODULE = CSS_MODULE_TYPE_MODULE;
/** @type {JavaScriptModuleTypes[]} */
module.exports.JAVASCRIPT_MODULES = [
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
@@ -167,6 +176,7 @@ module.exports.JAVASCRIPT_MODULE_TYPE_AUTO = JAVASCRIPT_MODULE_TYPE_AUTO;
module.exports.JAVASCRIPT_MODULE_TYPE_DYNAMIC = JAVASCRIPT_MODULE_TYPE_DYNAMIC;
module.exports.JAVASCRIPT_MODULE_TYPE_ESM = JAVASCRIPT_MODULE_TYPE_ESM;
module.exports.JSON_MODULE_TYPE = JSON_MODULE_TYPE;
/** @type {WebAssemblyModuleTypes[]} */
module.exports.WEBASSEMBLY_MODULES = [
WEBASSEMBLY_MODULE_TYPE_SYNC,
WEBASSEMBLY_MODULE_TYPE_SYNC

View File

@@ -14,30 +14,36 @@ const MultiWatching = require("./MultiWatching");
const WebpackError = require("./WebpackError");
const ArrayQueue = require("./util/ArrayQueue");
/** @template T @typedef {import("tapable").AsyncSeriesHook<T>} AsyncSeriesHook<T> */
/** @template T @template R @typedef {import("tapable").SyncBailHook<T, R>} SyncBailHook<T, R> */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
/**
* @template T
* @typedef {import("tapable").AsyncSeriesHook<T>} AsyncSeriesHook<T>
*/
/**
* @template T
* @template R
* @typedef {import("tapable").SyncBailHook<T, R>} SyncBailHook<T, R>
*/
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */
/** @typedef {import("./Compiler")} Compiler */
/**
* @template T
* @template [R=void]
* @typedef {import("./webpack").Callback<T, R>} Callback
*/
/** @typedef {import("./webpack").ErrorCallback} ErrorCallback */
/** @typedef {import("./Stats")} Stats */
/** @typedef {import("./Watching")} Watching */
/** @typedef {import("./logging/Logger").Logger} Logger */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */
/** @typedef {import("./util/fs").OutputFileSystem} OutputFileSystem */
/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */
/**
* @template T
* @callback Callback
* @param {Error | null} err
* @param {T=} result
*/
/**
* @callback RunWithDependenciesHandler
* @param {Compiler} compiler
* @param {Callback<MultiStats>} callback
* @returns {void}
*/
/**
@@ -581,11 +587,12 @@ module.exports = class MultiCompiler {
/**
* @param {WatchOptions | WatchOptions[]} watchOptions the watcher's options
* @param {Callback<MultiStats>} handler signals when the call finishes
* @returns {MultiWatching} a compiler watcher
* @returns {MultiWatching | undefined} a compiler watcher
*/
watch(watchOptions, handler) {
if (this.running) {
return handler(new ConcurrentCompilationError());
handler(new ConcurrentCompilationError());
return;
}
this.running = true;
@@ -621,7 +628,8 @@ module.exports = class MultiCompiler {
*/
run(callback) {
if (this.running) {
return callback(new ConcurrentCompilationError());
callback(new ConcurrentCompilationError());
return;
}
this.running = true;
@@ -649,7 +657,7 @@ module.exports = class MultiCompiler {
}
/**
* @param {Callback<void>} callback signals when the compiler closes
* @param {ErrorCallback} callback signals when the compiler closes
* @returns {void}
*/
close(callback) {

View File

@@ -9,13 +9,7 @@ const asyncLib = require("neo-async");
/** @typedef {import("./MultiCompiler")} MultiCompiler */
/** @typedef {import("./Watching")} Watching */
/**
* @template T
* @callback Callback
* @param {(Error | null)=} err
* @param {T=} result
*/
/** @typedef {import("./webpack").ErrorCallback} ErrorCallback */
class MultiWatching {
/**
@@ -28,7 +22,7 @@ class MultiWatching {
}
/**
* @param {Callback<void>=} callback signals when the build has completed again
* @param {ErrorCallback=} callback signals when the build has completed again
* @returns {void}
*/
invalidate(callback) {
@@ -36,7 +30,9 @@ class MultiWatching {
asyncLib.each(
this.watchings,
(watching, callback) => watching.invalidate(callback),
callback
(err) => {
callback(err);
}
);
} else {
for (const watching of this.watchings) {
@@ -58,7 +54,7 @@ class MultiWatching {
}
/**
* @param {Callback<void>} callback signals when the watcher is closed
* @param {ErrorCallback} callback signals when the watcher is closed
* @returns {void}
*/
close(callback) {

View File

@@ -21,15 +21,11 @@ const {
const { relative } = require("./util/fs");
const { parseResource } = require("./util/identifier");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
/** @typedef {import("../declarations/WebpackOptions").NodeOptions} NodeOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
@@ -188,9 +184,7 @@ class NodeStuffPlugin {
);
break;
case "node-module": {
const importMetaName =
/** @type {string} */
(compilation.outputOptions.importMetaName);
const importMetaName = compilation.outputOptions.importMetaName;
setUrlModuleConstant(
"__filename",
@@ -230,9 +224,7 @@ class NodeStuffPlugin {
);
break;
case "node-module": {
const importMetaName =
/** @type {string} */
(compilation.outputOptions.importMetaName);
const importMetaName = compilation.outputOptions.importMetaName;
setUrlModuleConstant(
"__dirname",

View File

@@ -54,54 +54,49 @@ const {
const makeSerializable = require("./util/makeSerializable");
const memoize = require("./util/memoize");
/** @typedef {import("enhanced-resolve").ResolveContext} ResolveContext */
/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("webpack-sources").RawSourceMap} RawSourceMap */
/** @typedef {import("../declarations/WebpackOptions").Mode} Mode */
/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("../declarations/WebpackOptions").NoParse} NoParse */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Generator")} Generator */
/** @typedef {import("./Generator").GenerateErrorFn} GenerateErrorFn */
/** @typedef {import("./Generator").GenerateContextData} GenerateContextData */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./Module").FileSystemDependencies} FileSystemDependencies */
/** @typedef {import("./Module").BuildMeta} BuildMeta */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").CodeGenerationResultData} CodeGenerationResultData */
/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("./Module").KnownBuildInfo} KnownBuildInfo */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").LibIdent} LibIdent */
/** @typedef {import("./Module").NameForCondition} NameForCondition */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").BuildCallback} BuildCallback */
/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").UnsafeCacheData} UnsafeCacheData */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
/** @typedef {import("./ModuleTypeConstants").ModuleTypes} ModuleTypes */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/** @typedef {import("./NormalModuleFactory").ResourceDataWithData} ResourceDataWithData */
/** @typedef {import("./NormalModuleFactory").NormalModuleTypes} NormalModuleTypes */
/** @typedef {import("./NormalModuleFactory").ResourceSchemeData} ResourceSchemeData */
/** @typedef {import("./Parser")} Parser */
/** @typedef {import("./Parser").PreparsedAst} PreparsedAst */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolveContext} ResolveContext */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./ResolverFactory").ResolveRequest} ResolveRequest */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./logging/Logger").Logger} WebpackLogger */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
/** @typedef {import("./dependencies/HarmonyImportSideEffectDependency")} HarmonyImportSideEffectDependency */
/** @typedef {import("./dependencies/HarmonyImportSpecifierDependency")} HarmonyImportSpecifierDependency */
/** @typedef {import("../declarations/WebpackOptions").RuleSetRule["extractSourceMap"]} ExtractSourceMapOptions */
/**
* @template T
* @typedef {import("./util/deprecation").FakeHook<T>} FakeHook
@@ -123,6 +118,9 @@ const memoize = require("./util/memoize");
const getInvalidDependenciesModuleWarning = memoize(() =>
require("./InvalidDependenciesModuleWarning")
);
const getExtractSourceMap = memoize(() => require("./util/extractSourceMap"));
const getValidate = memoize(() => require("schema-utils").validate);
const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/;
@@ -131,8 +129,8 @@ const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/;
* @typedef {object} LoaderItem
* @property {string} loader
* @property {string | null | undefined | Record<string, EXPECTED_ANY>} options
* @property {string?} ident
* @property {string?} type
* @property {string | null=} ident
* @property {string | null=} type
*/
/**
@@ -226,14 +224,16 @@ makeSerializable(
/** @typedef {[string | Buffer, string | RawSourceMap | undefined, PreparsedAst | undefined]} Result */
/** @typedef {LoaderContext<EXPECTED_ANY>} AnyLoaderContext */
/**
* @typedef {object} NormalModuleCompilationHooks
* @property {SyncHook<[LoaderContext<EXPECTED_ANY>, NormalModule]>} loader
* @property {SyncHook<[LoaderItem[], NormalModule, LoaderContext<EXPECTED_ANY>]>} beforeLoaders
* @property {SyncHook<[AnyLoaderContext, NormalModule]>} loader
* @property {SyncHook<[LoaderItem[], NormalModule, AnyLoaderContext]>} beforeLoaders
* @property {SyncHook<[NormalModule]>} beforeParse
* @property {SyncHook<[NormalModule]>} beforeSnapshot
* @property {HookMap<FakeHook<AsyncSeriesBailHook<[string, NormalModule], string | Buffer | null>>>} readResourceForScheme
* @property {HookMap<AsyncSeriesBailHook<[LoaderContext<EXPECTED_ANY>], string | Buffer | null>>} readResource
* @property {HookMap<AsyncSeriesBailHook<[AnyLoaderContext], string | Buffer | null>>} readResource
* @property {SyncWaterfallHook<[Result, NormalModule]>} processResult
* @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild
*/
@@ -241,7 +241,7 @@ makeSerializable(
/**
* @typedef {object} NormalModuleCreateData
* @property {string=} layer an optional layer in which the module is
* @property {ModuleTypes | ""} type module type. When deserializing, this is set to an empty string "".
* @property {NormalModuleTypes | ""} type module type. When deserializing, this is set to an empty string "".
* @property {string} request request string
* @property {string} userRequest request intended by user (without loaders from config)
* @property {string} rawRequest request without resolving
@@ -255,6 +255,11 @@ makeSerializable(
* @property {Generator} generator the generator used
* @property {GeneratorOptions=} generatorOptions the options of the generator used
* @property {ResolveOptions=} resolveOptions options used for resolving requests from this module
* @property {boolean=} extractSourceMap enable/disable extracting source map
*/
/**
* @typedef {(resourcePath: string, getLoaderContext: (resourcePath: string) => AnyLoaderContext) => Promise<string | Buffer<ArrayBufferLike>>} ReadResource
*/
/** @type {WeakMap<Compilation, NormalModuleCompilationHooks>} */
@@ -342,7 +347,8 @@ class NormalModule extends Module {
parserOptions,
generator,
generatorOptions,
resolveOptions
resolveOptions,
extractSourceMap
}) {
super(type, context || getContext(resource), layer);
@@ -374,6 +380,8 @@ class NormalModule extends Module {
// already declared in super class
this.resolveOptions = resolveOptions;
}
/** @type {ExtractSourceMapOptions} */
this.extractSourceMap = extractSourceMap;
// Info from Build
/** @type {WebpackError | null} */
@@ -400,7 +408,7 @@ class NormalModule extends Module {
this._isEvaluatingSideEffects = false;
/** @type {WeakSet<ModuleGraph> | undefined} */
this._addedSideEffectsBailout = undefined;
/** @type {GenerateContextData} */
/** @type {CodeGenerationResultData} */
this._codeGeneratorData = new Map();
}
@@ -425,9 +433,16 @@ class NormalModule extends Module {
return /** @type {string} */ (requestShortener.shorten(this.userRequest));
}
/**
* @returns {string | null} return the resource path
*/
getResource() {
return this.matchResource || this.resource;
}
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
* @returns {LibIdent | null} an identifier for library inclusion
*/
libIdent(options) {
let ident = contextify(
@@ -440,10 +455,10 @@ class NormalModule extends Module {
}
/**
* @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
* @returns {NameForCondition | null} absolute path which should be used for condition matching (usually the resource path)
*/
nameForCondition() {
const resource = this.matchResource || this.resource;
const resource = /** @type {string} */ (this.getResource());
const idx = resource.indexOf("?");
if (idx >= 0) return resource.slice(0, idx);
return resource;
@@ -589,7 +604,8 @@ class NormalModule extends Module {
const { requestShortener } = compilation.runtimeTemplate;
const getCurrentLoaderName = () => {
const currentLoader = this.getCurrentLoader(
/** @type {LoaderContext<EXPECTED_ANY>} */ (loaderContext)
/** @type {AnyLoaderContext} */
(loaderContext)
);
if (!currentLoader) return "(not in loader scope)";
return requestShortener.shorten(currentLoader.loader);
@@ -600,21 +616,18 @@ class NormalModule extends Module {
const getResolveContext = () => ({
fileDependencies: {
add: (d) =>
/** @type {LoaderContext<EXPECTED_ANY>} */ (
loaderContext
).addDependency(d)
/** @type {AnyLoaderContext} */
(loaderContext).addDependency(d)
},
contextDependencies: {
add: (d) =>
/** @type {LoaderContext<EXPECTED_ANY>} */ (
loaderContext
).addContextDependency(d)
/** @type {AnyLoaderContext} */
(loaderContext).addContextDependency(d)
},
missingDependencies: {
add: (d) =>
/** @type {LoaderContext<EXPECTED_ANY>} */ (
loaderContext
).addMissingDependency(d)
/** @type {AnyLoaderContext} */
(loaderContext).addMissingDependency(d)
}
});
const getAbsolutify = memoize(() =>
@@ -661,13 +674,9 @@ class NormalModule extends Module {
* @returns {Hash} hash
*/
createHash: (type) =>
createHash(
type ||
/** @type {HashFunction} */
(compilation.outputOptions.hashFunction)
)
createHash(type || compilation.outputOptions.hashFunction)
};
/** @type {import("../declarations/LoaderContext").NormalModuleLoaderContext<T>} */
/** @type {NormalModuleLoaderContext<T>} */
const loaderContext = {
version: 2,
/**
@@ -676,7 +685,8 @@ class NormalModule extends Module {
*/
getOptions: (schema) => {
const loader = this.getCurrentLoader(
/** @type {LoaderContext<EXPECTED_ANY>} */ (loaderContext)
/** @type {AnyLoaderContext} */
(loaderContext)
);
let { options } = /** @type {LoaderItem} */ (loader);
@@ -738,7 +748,8 @@ class NormalModule extends Module {
},
getLogger: (name) => {
const currentLoader = this.getCurrentLoader(
/** @type {LoaderContext<EXPECTED_ANY>} */ (loaderContext)
/** @type {AnyLoaderContext} */
(loaderContext)
);
return compilation.getLogger(() =>
[currentLoader && currentLoader.loader, name, this.identifier()]
@@ -794,7 +805,7 @@ class NormalModule extends Module {
(buildInfo.assetsInfo);
assets[name] = this.createSourceForAsset(
/** @type {string} */ (options.context),
options.context,
name,
content,
sourceMap,
@@ -811,14 +822,14 @@ class NormalModule extends Module {
buildInfo.buildDependencies.add(dep);
},
utils,
rootContext: /** @type {string} */ (options.context),
rootContext: options.context,
webpack: true,
sourceMap: Boolean(this.useSourceMap),
mode: options.mode || "production",
hashFunction: /** @type {string} */ (options.output.hashFunction),
hashDigest: /** @type {string} */ (options.output.hashDigest),
hashDigestLength: /** @type {number} */ (options.output.hashDigestLength),
hashSalt: /** @type {string} */ (options.output.hashSalt),
hashFunction: options.output.hashFunction,
hashDigest: options.output.hashDigest,
hashDigestLength: options.output.hashDigestLength,
hashSalt: options.output.hashSalt,
_module: this,
_compilation: compilation,
_compiler: compilation.compiler,
@@ -827,19 +838,18 @@ class NormalModule extends Module {
Object.assign(loaderContext, options.loader);
// After `hooks.loader.call` is called, the loaderContext is typed as LoaderContext<EXPECTED_ANY>
hooks.loader.call(
/** @type {LoaderContext<EXPECTED_ANY>} */
/** @type {AnyLoaderContext} */
(loaderContext),
this
);
return /** @type {LoaderContext<EXPECTED_ANY>} */ (loaderContext);
return /** @type {AnyLoaderContext} */ (loaderContext);
}
// TODO remove `loaderContext` in webpack@6
/**
* @param {LoaderContext<EXPECTED_ANY>} loaderContext loader context
* @param {AnyLoaderContext} loaderContext loader context
* @param {number} index index
* @returns {LoaderItem | null} loader
*/
@@ -962,7 +972,7 @@ class NormalModule extends Module {
: this.binary;
this._source = this.createSource(
/** @type {string} */ (options.context),
options.context,
isBinaryModule ? asBuffer(source) : asString(source),
sourceMap,
compilation.compiler.root
@@ -988,7 +998,7 @@ class NormalModule extends Module {
hooks.beforeLoaders.call(
this.loaders,
this,
/** @type {LoaderContext<EXPECTED_ANY>} */
/** @type {AnyLoaderContext} */
(loaderContext)
);
} catch (err) {
@@ -1007,28 +1017,80 @@ class NormalModule extends Module {
loaders: this.loaders,
context: loaderContext,
/**
* @param {LoaderContext<EXPECTED_ANY>} loaderContext the loader context
* @param {AnyLoaderContext} loaderContext the loader context
* @param {string} resourcePath the resource Path
* @param {(err: Error | null, result?: string | Buffer) => void} callback callback
* @param {(err: Error | null, result?: string | Buffer, sourceMap?: Result[1]) => void} callback callback
* @returns {Promise<void>}
*/
processResource: (loaderContext, resourcePath, callback) => {
const resource = loaderContext.resource;
const scheme = getScheme(resource);
hooks.readResource
.for(scheme)
.callAsync(loaderContext, (err, result) => {
if (err) return callback(err);
if (typeof result !== "string" && !result) {
return callback(
new UnhandledSchemeError(
/** @type {string} */
(scheme),
resource
)
);
}
return callback(null, result);
processResource: async (loaderContext, resourcePath, callback) => {
/** @type {ReadResource} */
const readResource = (resourcePath, getLoaderContext) => {
const scheme = getScheme(resourcePath);
return new Promise((resolve, reject) => {
hooks.readResource
.for(scheme)
.callAsync(getLoaderContext(resourcePath), (err, result) => {
if (err) {
reject(err);
} else {
if (typeof result !== "string" && !result) {
return reject(
new UnhandledSchemeError(
/** @type {string} */
(scheme),
resourcePath
)
);
}
resolve(result);
}
});
});
};
try {
const result = await readResource(
resourcePath,
() => loaderContext
);
if (
this.extractSourceMap &&
(this.useSourceMap || this.useSimpleSourceMap)
) {
try {
const { source, sourceMap } = await getExtractSourceMap()(
result,
resourcePath,
/** @type {ReadResource} */
(resourcePath) =>
readResource(
resourcePath,
(resourcePath) =>
/** @type {AnyLoaderContext} */
({
addDependency(dependency) {
loaderContext.addDependency(dependency);
},
fs: loaderContext.fs,
_module: undefined,
resourcePath,
resource: resourcePath
})
).catch((err) => {
throw new Error(
`Failed to parse source map. ${/** @type {Error} */ (err).message}`
);
})
);
return callback(null, source, sourceMap);
} catch (err) {
this.addWarning(new ModuleWarning(/** @type {Error} */ (err)));
return callback(null, result);
}
}
return callback(null, result);
} catch (error) {
return callback(/** @type {Error} */ (error));
}
}
},
(err, result) => {
@@ -1141,10 +1203,7 @@ class NormalModule extends Module {
* @private
*/
_initBuildHash(compilation) {
const hash = createHash(
/** @type {HashFunction} */
(compilation.outputOptions.hashFunction)
);
const hash = createHash(compilation.outputOptions.hashFunction);
if (this._source) {
hash.update("source");
this._source.updateHash(hash);
@@ -1152,7 +1211,7 @@ class NormalModule extends Module {
hash.update("meta");
hash.update(JSON.stringify(this.buildMeta));
/** @type {BuildInfo} */
(this.buildInfo).hash = /** @type {string} */ (hash.digest("hex"));
(this.buildInfo).hash = hash.digest("hex");
}
/**
@@ -1205,11 +1264,7 @@ class NormalModule extends Module {
const handleParseError = (e) => {
const source = /** @type {Source} */ (this._source).source();
const loaders = this.loaders.map((item) =>
contextify(
/** @type {string} */ (options.context),
item.loader,
compilation.compiler.root
)
contextify(options.context, item.loader, compilation.compiler.root)
);
const error = new ModuleParseError(source, e, loaders, this.type);
this.markModuleAsErrored(error);
@@ -1446,7 +1501,7 @@ class NormalModule extends Module {
codeGenerationResults,
sourceTypes
}) {
/** @type {Set<string>} */
/** @type {RuntimeRequirements} */
const runtimeRequirements = new Set();
const { parsed } = /** @type {BuildInfo} */ (this.buildInfo);
@@ -1604,10 +1659,10 @@ class NormalModule extends Module {
}
/**
* @param {LazySet<string>} fileDependencies set where file dependencies are added to
* @param {LazySet<string>} contextDependencies set where context dependencies are added to
* @param {LazySet<string>} missingDependencies set where missing dependencies are added to
* @param {LazySet<string>} buildDependencies set where build dependencies are added to
* @param {FileSystemDependencies} fileDependencies set where file dependencies are added to
* @param {FileSystemDependencies} contextDependencies set where context dependencies are added to
* @param {FileSystemDependencies} missingDependencies set where missing dependencies are added to
* @param {FileSystemDependencies} buildDependencies set where build dependencies are added to
*/
addCacheDependencies(
fileDependencies,
@@ -1666,6 +1721,7 @@ class NormalModule extends Module {
write(this._lastSuccessfulBuildMeta);
write(this._forceBuild);
write(this._codeGeneratorData);
write(this.extractSourceMap);
super.serialize(context);
}
@@ -1706,6 +1762,7 @@ class NormalModule extends Module {
this._lastSuccessfulBuildMeta = read();
this._forceBuild = read();
this._codeGeneratorData = read();
this.extractSourceMap = read();
super.deserialize(context);
}
}

View File

@@ -34,6 +34,8 @@ const {
parseResourceWithoutFragment
} = require("./util/identifier");
/** @typedef {import("enhanced-resolve").ResolveContext} ResolveContext */
/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
/** @typedef {import("../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */
/** @typedef {import("../declarations/WebpackOptions").RuleSetRule} RuleSetRule */
/** @typedef {import("./Generator")} Generator */
@@ -47,8 +49,6 @@ const {
/** @typedef {import("./NormalModule").ParserOptions} ParserOptions */
/** @typedef {import("./Parser")} Parser */
/** @typedef {import("./ResolverFactory")} ResolverFactory */
/** @typedef {import("./ResolverFactory").ResolveContext} ResolveContext */
/** @typedef {import("./ResolverFactory").ResolveRequest} ResolveRequest */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */
/** @typedef {import("./javascript/JavascriptParser").ImportAttributes} ImportAttributes */
@@ -56,7 +56,12 @@ const {
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
/** @typedef {Pick<RuleSetRule, 'type' | 'sideEffects' | 'parser' | 'generator' | 'resolve' | 'layer'>} ModuleSettings */
/**
* @template T
* @typedef {import("./Compiler").Callback<T>} Callback
*/
/** @typedef {Pick<RuleSetRule, 'type' | 'sideEffects' | 'parser' | 'generator' | 'resolve' | 'layer' | 'extractSourceMap'>} ModuleSettings */
/** @typedef {Partial<NormalModuleCreateData & { settings: ModuleSettings }>} CreateData */
/**
@@ -65,7 +70,7 @@ const {
* @property {ModuleFactoryCreateData["resolveOptions"]} resolveOptions
* @property {string} context
* @property {string} request
* @property {ImportAttributes | undefined} assertions
* @property {ImportAttributes | undefined} attributes
* @property {ModuleDependency[]} dependencies
* @property {string} dependencyType
* @property {CreateData} createData
@@ -101,13 +106,24 @@ const {
* @property {string|undefined} options options
*/
/**
* @template T
* @callback Callback
* @param {(Error | null)=} err
* @param {T=} stats
* @returns {void}
*/
/** @typedef {import("./ModuleTypeConstants").JAVASCRIPT_MODULE_TYPE_AUTO} JAVASCRIPT_MODULE_TYPE_AUTO */
/** @typedef {import("./ModuleTypeConstants").JAVASCRIPT_MODULE_TYPE_DYNAMIC} JAVASCRIPT_MODULE_TYPE_DYNAMIC */
/** @typedef {import("./ModuleTypeConstants").JAVASCRIPT_MODULE_TYPE_ESM} JAVASCRIPT_MODULE_TYPE_ESM */
/** @typedef {import("./ModuleTypeConstants").JSON_MODULE_TYPE} JSON_MODULE_TYPE */
/** @typedef {import("./ModuleTypeConstants").ASSET_MODULE_TYPE} ASSET_MODULE_TYPE */
/** @typedef {import("./ModuleTypeConstants").ASSET_MODULE_TYPE_INLINE} ASSET_MODULE_TYPE_INLINE */
/** @typedef {import("./ModuleTypeConstants").ASSET_MODULE_TYPE_RESOURCE} ASSET_MODULE_TYPE_RESOURCE */
/** @typedef {import("./ModuleTypeConstants").ASSET_MODULE_TYPE_SOURCE} ASSET_MODULE_TYPE_SOURCE */
/** @typedef {import("./ModuleTypeConstants").ASSET_MODULE_TYPE_BYTES} ASSET_MODULE_TYPE_BYTES */
/** @typedef {import("./ModuleTypeConstants").WEBASSEMBLY_MODULE_TYPE_ASYNC} WEBASSEMBLY_MODULE_TYPE_ASYNC */
/** @typedef {import("./ModuleTypeConstants").WEBASSEMBLY_MODULE_TYPE_SYNC} WEBASSEMBLY_MODULE_TYPE_SYNC */
/** @typedef {import("./ModuleTypeConstants").CSS_MODULE_TYPE} CSS_MODULE_TYPE */
/** @typedef {import("./ModuleTypeConstants").CSS_MODULE_TYPE_GLOBAL} CSS_MODULE_TYPE_GLOBAL */
/** @typedef {import("./ModuleTypeConstants").CSS_MODULE_TYPE_MODULE} CSS_MODULE_TYPE_MODULE */
/** @typedef {import("./ModuleTypeConstants").CSS_MODULE_TYPE_AUTO} CSS_MODULE_TYPE_AUTO */
/** @typedef {JAVASCRIPT_MODULE_TYPE_AUTO | JAVASCRIPT_MODULE_TYPE_DYNAMIC | JAVASCRIPT_MODULE_TYPE_ESM | JSON_MODULE_TYPE | ASSET_MODULE_TYPE | ASSET_MODULE_TYPE_INLINE | ASSET_MODULE_TYPE_RESOURCE | ASSET_MODULE_TYPE_SOURCE | WEBASSEMBLY_MODULE_TYPE_ASYNC | WEBASSEMBLY_MODULE_TYPE_SYNC | CSS_MODULE_TYPE | CSS_MODULE_TYPE_GLOBAL | CSS_MODULE_TYPE_MODULE | CSS_MODULE_TYPE_AUTO} KnownNormalModuleTypes */
/** @typedef {KnownNormalModuleTypes | string} NormalModuleTypes */
const EMPTY_RESOLVE_OPTIONS = {};
/** @type {ParserOptions} */
@@ -227,7 +243,7 @@ const ruleSetCompiler = new RuleSetCompiler([
new BasicMatcherRulePlugin("issuer"),
new BasicMatcherRulePlugin("compiler"),
new BasicMatcherRulePlugin("issuerLayer"),
new ObjectMatcherRulePlugin("assert", "assertions", (value) => {
new ObjectMatcherRulePlugin("assert", "attributes", (value) => {
if (value) {
return (
/** @type {ImportAttributes} */ (value)._isLegacyAssert !== undefined
@@ -236,7 +252,7 @@ const ruleSetCompiler = new RuleSetCompiler([
return false;
}),
new ObjectMatcherRulePlugin("with", "assertions", (value) => {
new ObjectMatcherRulePlugin("with", "attributes", (value) => {
if (value) {
return !(/** @type {ImportAttributes} */ (value)._isLegacyAssert);
}
@@ -249,9 +265,80 @@ const ruleSetCompiler = new RuleSetCompiler([
new BasicEffectRulePlugin("resolve"),
new BasicEffectRulePlugin("generator"),
new BasicEffectRulePlugin("layer"),
new BasicEffectRulePlugin("extractSourceMap"),
new UseEffectRulePlugin()
]);
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
/** @typedef {import("./javascript/JavascriptGenerator")} JavascriptGenerator */
/** @typedef {import("../declarations/WebpackOptions").EmptyGeneratorOptions} EmptyGeneratorOptions */
/** @typedef {import("./json/JsonParser")} JsonParser */
/** @typedef {import("../declarations/WebpackOptions").JsonParserOptions} JsonParserOptions */
/** @typedef {import("./json/JsonGenerator")} JsonGenerator */
/** @typedef {import("../declarations/WebpackOptions").JsonGeneratorOptions} JsonGeneratorOptions */
/** @typedef {import("./asset/AssetParser")} AssetParser */
/** @typedef {import("./asset/AssetSourceParser")} AssetSourceParser */
/** @typedef {import("./asset/AssetBytesParser")} AssetBytesParser */
/** @typedef {import("../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */
/** @typedef {import("../declarations/WebpackOptions").EmptyParserOptions} EmptyParserOptions */
/** @typedef {import("./asset/AssetGenerator")} AssetGenerator */
/** @typedef {import("../declarations/WebpackOptions").AssetGeneratorOptions} AssetGeneratorOptions */
/** @typedef {import("../declarations/WebpackOptions").AssetInlineGeneratorOptions} AssetInlineGeneratorOptions */
/** @typedef {import("../declarations/WebpackOptions").AssetResourceGeneratorOptions} AssetResourceGeneratorOptions */
/** @typedef {import("./asset/AssetSourceGenerator")} AssetSourceGenerator */
/** @typedef {import("./asset/AssetBytesGenerator")} AssetBytesGenerator */
/** @typedef {import("./wasm-async/AsyncWebAssemblyParser")} AsyncWebAssemblyParser */
/** @typedef {import("./wasm-sync/WebAssemblyParser")} WebAssemblyParser */
/** @typedef {import("./css/CssParser")} CssParser */
/** @typedef {import("../declarations/WebpackOptions").CssParserOptions} CssParserOptions */
/** @typedef {import("../declarations/WebpackOptions").CssAutoParserOptions} CssAutoParserOptions */
/** @typedef {import("../declarations/WebpackOptions").CssGlobalParserOptions} CssGlobalParserOptions */
/** @typedef {import("../declarations/WebpackOptions").CssModuleParserOptions} CssModuleParserOptions */
/** @typedef {import("./css/CssGenerator")} CssGenerator */
/** @typedef {import("../declarations/WebpackOptions").CssGeneratorOptions} CssGeneratorOptions */
/** @typedef {import("../declarations/WebpackOptions").CssGlobalGeneratorOptions} CssGlobalGeneratorOptions */
/** @typedef {import("../declarations/WebpackOptions").CssModuleGeneratorOptions} CssModuleGeneratorOptions */
/** @typedef {import("../declarations/WebpackOptions").CssAutoGeneratorOptions} CssAutoGeneratorOptions */
/**
* @typedef {[
* [JAVASCRIPT_MODULE_TYPE_AUTO, JavascriptParser, JavascriptParserOptions, JavascriptGenerator, EmptyGeneratorOptions],
* [JAVASCRIPT_MODULE_TYPE_DYNAMIC, JavascriptParser, JavascriptParserOptions, JavascriptGenerator, EmptyGeneratorOptions],
* [JAVASCRIPT_MODULE_TYPE_ESM, JavascriptParser, JavascriptParserOptions, JavascriptGenerator, EmptyGeneratorOptions],
* [JSON_MODULE_TYPE, JsonParser, JsonParserOptions, JsonGenerator, JsonGeneratorOptions],
* [ASSET_MODULE_TYPE, AssetParser, AssetParserOptions, AssetGenerator, AssetGeneratorOptions],
* [ASSET_MODULE_TYPE_INLINE, AssetParser, EmptyParserOptions, AssetGenerator, AssetGeneratorOptions],
* [ASSET_MODULE_TYPE_RESOURCE, AssetParser, EmptyParserOptions, AssetGenerator, AssetGeneratorOptions],
* [ASSET_MODULE_TYPE_SOURCE, AssetSourceParser, EmptyParserOptions, AssetSourceGenerator, EmptyGeneratorOptions],
* [ASSET_MODULE_TYPE_BYTES, AssetBytesParser, EmptyParserOptions, AssetBytesGenerator, EmptyGeneratorOptions],
* [WEBASSEMBLY_MODULE_TYPE_ASYNC, AsyncWebAssemblyParser, EmptyParserOptions, Generator, EmptyParserOptions],
* [WEBASSEMBLY_MODULE_TYPE_SYNC, WebAssemblyParser, EmptyParserOptions, Generator, EmptyParserOptions],
* [CSS_MODULE_TYPE, CssParser, CssParserOptions, CssGenerator, CssGeneratorOptions],
* [CSS_MODULE_TYPE_AUTO, CssParser, CssAutoParserOptions, CssGenerator, CssAutoGeneratorOptions],
* [CSS_MODULE_TYPE_MODULE, CssParser, CssModuleParserOptions, CssGenerator, CssModuleGeneratorOptions],
* [CSS_MODULE_TYPE_GLOBAL, CssParser, CssGlobalParserOptions, CssGenerator, CssGlobalGeneratorOptions],
* [string, Parser, ParserOptions, Generator, GeneratorOptions],
* ]} ParsersAndGeneratorsByTypes
*/
/**
* @template {unknown[]} T
* @template {number[]} I
* @typedef {{ [K in keyof I]: K extends keyof I ? I[K] extends keyof T ? T[I[K]] : never : never }} ExtractTupleElements
*/
/**
* @template {unknown[]} T
* @template {number[]} A
* @template [R=void]
* @typedef {T extends [infer Head extends [string, ...unknown[]], ...infer Tail extends [string, ...unknown[]][]] ? Record<Head[0], SyncBailHook<ExtractTupleElements<Head, A>, R extends number ? Head[R] : R>> & RecordFactoryFromTuple<Tail, A, R> : unknown } RecordFactoryFromTuple
*/
class NormalModuleFactory extends ModuleFactory {
/**
* @param {object} param params
@@ -260,15 +347,13 @@ class NormalModuleFactory extends ModuleFactory {
* @param {ResolverFactory} param.resolverFactory resolverFactory
* @param {ModuleOptions} param.options options
* @param {AssociatedObjectForCache} param.associatedObjectForCache an object to which the cache will be attached
* @param {boolean=} param.layers enable layers
*/
constructor({
context,
fs,
resolverFactory,
options,
associatedObjectForCache,
layers = false
associatedObjectForCache
}) {
super();
this.hooks = Object.freeze({
@@ -292,15 +377,15 @@ class NormalModuleFactory extends ModuleFactory {
createModule: new AsyncSeriesBailHook(["createData", "resolveData"]),
/** @type {SyncWaterfallHook<[Module, CreateData, ResolveData]>} */
module: new SyncWaterfallHook(["module", "createData", "resolveData"]),
/** @type {HookMap<SyncBailHook<[ParserOptions], Parser | void>>} */
/** @type {import("tapable").TypedHookMap<RecordFactoryFromTuple<ParsersAndGeneratorsByTypes, [2], 1>>} */
createParser: new HookMap(() => new SyncBailHook(["parserOptions"])),
/** @type {HookMap<SyncBailHook<[TODO, ParserOptions], void>>} */
/** @type {import("tapable").TypedHookMap<RecordFactoryFromTuple<ParsersAndGeneratorsByTypes, [1, 2]>>} */
parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])),
/** @type {HookMap<SyncBailHook<[GeneratorOptions], Generator | void>>} */
/** @type {import("tapable").TypedHookMap<RecordFactoryFromTuple<ParsersAndGeneratorsByTypes, [4], 3>>} */
createGenerator: new HookMap(
() => new SyncBailHook(["generatorOptions"])
),
/** @type {HookMap<SyncBailHook<[TODO, GeneratorOptions], void>>} */
/** @type {import("tapable").TypedHookMap<RecordFactoryFromTuple<ParsersAndGeneratorsByTypes, [3, 4]>>} */
generator: new HookMap(
() => new SyncHook(["generator", "generatorOptions"])
),
@@ -430,7 +515,7 @@ class NormalModuleFactory extends ModuleFactory {
dependencies,
dependencyType,
request,
assertions,
attributes,
resolveOptions,
fileDependencies,
missingDependencies,
@@ -601,7 +686,7 @@ class NormalModuleFactory extends ModuleFactory {
resourceQuery: resourceDataForRules.query,
resourceFragment: resourceDataForRules.fragment,
scheme,
assertions,
attributes,
mimetype: matchResourceData
? ""
: resourceData.data.mimetype || "",
@@ -683,16 +768,10 @@ class NormalModuleFactory extends ModuleFactory {
for (const loader of /** @type {LoaderItem[]} */ (preLoaders)) {
allLoaders.push(loader);
}
const type = /** @type {string} */ (settings.type);
const type = /** @type {NormalModuleTypes} */ (settings.type);
const resolveOptions = settings.resolve;
const layer = settings.layer;
if (layer !== undefined && !layers) {
return callback(
new Error(
"'Rule.layer' is only allowed when 'experiments.layers' is enabled"
)
);
}
try {
Object.assign(data.createData, {
layer:
@@ -717,7 +796,8 @@ class NormalModuleFactory extends ModuleFactory {
parserOptions: settings.parser,
generator: this.getGenerator(type, settings.generator),
generatorOptions: settings.generator,
resolveOptions
resolveOptions,
extractSourceMap: settings.extractSourceMap || false
});
} catch (createDataErr) {
return callback(/** @type {Error} */ (createDataErr));
@@ -887,7 +967,9 @@ class NormalModuleFactory extends ModuleFactory {
const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS;
const dependency = dependencies[0];
const request = dependency.request;
const assertions = dependency.assertions;
const attributes =
/** @type {ModuleDependency & { attributes: ImportAttributes }} */
(dependency).attributes;
const dependencyType = dependency.category || "";
const contextInfo = data.contextInfo;
const fileDependencies = new LazySet();
@@ -899,7 +981,7 @@ class NormalModuleFactory extends ModuleFactory {
resolveOptions,
context,
request,
assertions,
attributes,
dependencies,
dependencyType,
fileDependencies,
@@ -1186,6 +1268,10 @@ If changing the source code is not an option there is also a resolve options cal
if (array.length === 0) return callback(null, array);
asyncLib.map(
array,
/**
* @param {LoaderItem} item item
* @param {Callback<LoaderItem>} callback callback
*/
(item, callback) => {
resolver.resolve(
contextInfo,
@@ -1218,7 +1304,8 @@ If changing the source code is not an option there is also a resolve options cal
if (err) return callback(err);
const parsedResult = this._parseResourceWithoutFragment(
/** @type {string} */ (result)
/** @type {string} */
(result)
);
const type = /\.mjs$/i.test(parsedResult.path)
@@ -1228,8 +1315,12 @@ If changing the source code is not an option there is also a resolve options cal
: /** @type {ResolveRequest} */
(resolveRequest).descriptionFileData === undefined
? undefined
: /** @type {ResolveRequest} */
(resolveRequest).descriptionFileData.type;
: /** @type {string} */
(
/** @type {ResolveRequest} */
(resolveRequest).descriptionFileData.type
);
/** @type {LoaderItem} */
const resolved = {
loader: parsedResult.path,
type,
@@ -1239,17 +1330,16 @@ If changing the source code is not an option there is also a resolve options cal
? parsedResult.query.slice(1)
: undefined
: item.options,
ident:
item.options === undefined
? undefined
: /** @type {string} */ (item.ident)
ident: item.options === undefined ? undefined : item.ident
};
return callback(null, /** @type {LoaderItem} */ (resolved));
return callback(null, resolved);
}
);
},
/** @type {Callback<(LoaderItem | undefined)[]>} */ (callback)
(err, value) => {
callback(err, /** @type {(LoaderItem)[]} */ (value));
}
);
}

View File

@@ -5,7 +5,7 @@
"use strict";
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Compiler")} Compiler */
class OptionsApply {

2
node_modules/webpack/lib/Parser.js generated vendored
View File

@@ -5,7 +5,7 @@
"use strict";
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./NormalModule")} NormalModule */

View File

@@ -16,9 +16,7 @@ const { contextify } = require("./util/identifier");
* @template T, R, AdditionalOptions
* @typedef {import("tapable").Hook<T, R, AdditionalOptions>} Hook
*/
/** @typedef {import("../declarations/plugins/ProgressPlugin").HandlerFunction} HandlerFunction */
/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */
/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */
/** @typedef {import("./Compilation").FactorizeModuleOptions} FactorizeModuleOptions */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
@@ -54,20 +52,18 @@ const validate = createSchemaValidation(
*/
const median3 = (a, b, c) => a + b + c - Math.max(a, b, c) - Math.min(a, b, c);
/** @typedef {(percentage: number, msg: string, ...args: string[]) => void} HandlerFn */
/**
* @param {boolean | null | undefined} profile need profile
* @param {Logger} logger logger
* @returns {defaultHandler} default handler
* @returns {HandlerFn} default handler
*/
const createDefaultHandler = (profile, logger) => {
/** @type {{ value: string | undefined, time: number }[]} */
const lastStateInfo = [];
/**
* @param {number} percentage percentage
* @param {string} msg message
* @param {...string} args additional arguments
*/
/** @type {HandlerFn} */
const defaultHandler = (percentage, msg, ...args) => {
if (profile) {
if (percentage === 0) {
@@ -199,7 +195,7 @@ class ProgressPlugin {
/**
* @param {MultiCompiler} compiler webpack multi-compiler
* @param {HandlerFunction} handler function that executes for every progress step
* @param {HandlerFn} handler function that executes for every progress step
* @returns {void}
*/
_applyOnMultiCompiler(compiler, handler) {
@@ -218,7 +214,7 @@ class ProgressPlugin {
/**
* @param {Compiler} compiler webpack compiler
* @param {HandlerFunction} handler function that executes for every progress step
* @param {HandlerFn} handler function that executes for every progress step
* @returns {void}
*/
_applyOnCompiler(compiler, handler) {

View File

@@ -59,13 +59,11 @@ class ProvidePlugin {
*/
const handler = (parser, parserOptions) => {
for (const name of Object.keys(definitions)) {
const request =
/** @type {string[]} */
([
...(Array.isArray(definitions[name])
? definitions[name]
: [definitions[name]])
]);
const request = [
...(Array.isArray(definitions[name])
? definitions[name]
: [definitions[name]])
];
const splittedName = name.split(".");
if (splittedName.length > 0) {
for (const [i, _] of splittedName.slice(1).entries()) {

View File

@@ -11,12 +11,9 @@ const { JS_TYPES } = require("./ModuleSourceTypesConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./Module").BuildCallback} BuildCallback */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
@@ -28,8 +25,6 @@ const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./util/Hash")} Hash */

View File

@@ -36,6 +36,8 @@ const identifierUtils = require("./util/identifier");
* @property {boolean=} portableIds true, when ids need to be portable
*/
/** @typedef {Set<number>} UsedIds */
const PLUGIN_NAME = "RecordIdsPlugin";
class RecordIdsPlugin {
@@ -75,7 +77,7 @@ class RecordIdsPlugin {
const chunkGraph = compilation.chunkGraph;
if (!records.modules) records.modules = {};
if (!records.modules.byIdentifier) records.modules.byIdentifier = {};
/** @type {Set<number>} */
/** @type {UsedIds} */
const usedIds = new Set();
for (const module of modules) {
const moduleId = chunkGraph.getModuleId(module);
@@ -90,7 +92,7 @@ class RecordIdsPlugin {
if (!records.modules) return;
if (records.modules.byIdentifier) {
const chunkGraph = compilation.chunkGraph;
/** @type {Set<number>} */
/** @type {UsedIds} */
const usedIds = new Set();
for (const module of modules) {
const moduleId = chunkGraph.getModuleId(module);
@@ -108,12 +110,14 @@ class RecordIdsPlugin {
}
});
/** @typedef {string[]} ChunkSources */
/**
* @param {Chunk} chunk the chunk
* @returns {string[]} sources of the chunk
* @returns {ChunkSources} sources of the chunk
*/
const getChunkSources = (chunk) => {
/** @type {string[]} */
/** @type {ChunkSources} */
const sources = [];
for (const chunkGroup of chunk.groupsIterable) {
const index = chunkGroup.chunks.indexOf(chunk);
@@ -156,7 +160,7 @@ class RecordIdsPlugin {
if (!records.chunks) records.chunks = {};
if (!records.chunks.byName) records.chunks.byName = {};
if (!records.chunks.bySource) records.chunks.bySource = {};
/** @type {Set<number>} */
/** @type {UsedIds} */
const usedIds = new Set();
for (const chunk of chunks) {
if (typeof chunk.id !== "number") continue;
@@ -172,7 +176,7 @@ class RecordIdsPlugin {
});
compilation.hooks.reviveChunks.tap(PLUGIN_NAME, (chunks, records) => {
if (!records.chunks) return;
/** @type {Set<number>} */
/** @type {UsedIds} */
const usedIds = new Set();
if (records.chunks.byName) {
for (const chunk of chunks) {

View File

@@ -13,9 +13,7 @@ const {
resolveByProperty
} = require("./util/cleverMerge");
/** @typedef {import("enhanced-resolve").ResolveContext} ResolveContext */
/** @typedef {import("enhanced-resolve").ResolveOptions} ResolveOptions */
/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
/** @typedef {import("enhanced-resolve").Resolver} Resolver */
/** @typedef {import("../declarations/WebpackOptions").ResolveOptions} WebpackResolveOptions */
/** @typedef {import("../declarations/WebpackOptions").ResolvePluginInstance} ResolvePluginInstance */

View File

@@ -416,6 +416,11 @@ module.exports.systemContext = "__webpack_require__.y";
*/
module.exports.thisAsExports = "top-level-this-exports";
/**
* to binary helper, convert base64 to Uint8Array
*/
module.exports.toBinary = "__webpack_require__.tb";
/**
* the uncaught error handler for the webpack runtime
*/

View File

@@ -11,8 +11,7 @@ const Module = require("./Module");
const { RUNTIME_TYPES } = require("./ModuleSourceTypesConstants");
const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Compilation")} Compilation */
@@ -25,7 +24,6 @@ const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants");
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */

View File

@@ -6,7 +6,6 @@
"use strict";
const RuntimeGlobals = require("./RuntimeGlobals");
const { getChunkFilenameTemplate } = require("./css/CssModulesPlugin");
const RuntimeRequirementsDependency = require("./dependencies/RuntimeRequirementsDependency");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
const AsyncModuleRuntimeModule = require("./runtime/AsyncModuleRuntimeModule");
@@ -33,16 +32,14 @@ const PublicPathRuntimeModule = require("./runtime/PublicPathRuntimeModule");
const RelativeUrlRuntimeModule = require("./runtime/RelativeUrlRuntimeModule");
const RuntimeIdRuntimeModule = require("./runtime/RuntimeIdRuntimeModule");
const SystemContextRuntimeModule = require("./runtime/SystemContextRuntimeModule");
const ToBinaryRuntimeModule = require("./runtime/ToBinaryRuntimeModule");
const ShareRuntimeModule = require("./sharing/ShareRuntimeModule");
const StringXor = require("./util/StringXor");
const memoize = require("./util/memoize");
/** @typedef {import("../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputNormalized */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./TemplatedPathPlugin").TemplatePath} TemplatePath */
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
@@ -310,12 +307,10 @@ class RuntimePlugin {
RuntimeGlobals.getChunkScriptFilename,
(chunk) =>
getJavascriptModulesPlugin().chunkHasJs(chunk, chunkGraph) &&
/** @type {TemplatePath} */ (
chunk.filenameTemplate ||
(chunk.canBeInitial()
? compilation.outputOptions.filename
: compilation.outputOptions.chunkFilename)
),
(chunk.filenameTemplate ||
(chunk.canBeInitial()
? compilation.outputOptions.filename
: compilation.outputOptions.chunkFilename)),
set.has(RuntimeGlobals.hmrDownloadUpdateHandlers)
)
);
@@ -338,9 +333,17 @@ class RuntimePlugin {
"css",
"css",
RuntimeGlobals.getChunkCssFilename,
(chunk) =>
getCssModulesPlugin().chunkHasCss(chunk, chunkGraph) &&
getChunkFilenameTemplate(chunk, compilation.outputOptions),
(chunk) => {
const cssModulePlugin = getCssModulesPlugin();
return (
cssModulePlugin.chunkHasCss(chunk, chunkGraph) &&
cssModulePlugin.getChunkFilenameTemplate(
chunk,
compilation.outputOptions
)
);
},
set.has(RuntimeGlobals.hmrDownloadUpdateHandlers)
)
);
@@ -351,8 +354,7 @@ class RuntimePlugin {
.tap(PLUGIN_NAME, (chunk, set) => {
if (
/\[(full)?hash(:\d+)?\]/.test(
/** @type {NonNullable<OutputNormalized["hotUpdateChunkFilename"]>} */
(compilation.outputOptions.hotUpdateChunkFilename)
compilation.outputOptions.hotUpdateChunkFilename
)
) {
set.add(RuntimeGlobals.getFullHash);
@@ -363,9 +365,7 @@ class RuntimePlugin {
"javascript",
"javascript update",
RuntimeGlobals.getChunkUpdateScriptFilename,
(_chunk) =>
/** @type {NonNullable<OutputNormalized["hotUpdateChunkFilename"]>} */
(compilation.outputOptions.hotUpdateChunkFilename),
(_chunk) => compilation.outputOptions.hotUpdateChunkFilename,
true
)
);
@@ -376,8 +376,7 @@ class RuntimePlugin {
.tap(PLUGIN_NAME, (chunk, set) => {
if (
/\[(full)?hash(:\d+)?\]/.test(
/** @type {NonNullable<OutputNormalized["hotUpdateMainFilename"]>} */
(compilation.outputOptions.hotUpdateMainFilename)
compilation.outputOptions.hotUpdateMainFilename
)
) {
set.add(RuntimeGlobals.getFullHash);
@@ -387,8 +386,7 @@ class RuntimePlugin {
new GetMainFilenameRuntimeModule(
"update manifest",
RuntimeGlobals.getUpdateManifestFilename,
/** @type {NonNullable<OutputNormalized["hotUpdateMainFilename"]>} */
(compilation.outputOptions.hotUpdateMainFilename)
compilation.outputOptions.hotUpdateMainFilename
)
);
return true;
@@ -492,6 +490,12 @@ class RuntimePlugin {
compilation.addRuntimeModule(chunk, new NonceRuntimeModule());
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.toBinary)
.tap(PLUGIN_NAME, (chunk) => {
compilation.addRuntimeModule(chunk, new ToBinaryRuntimeModule());
return true;
});
// TODO webpack 6: remove CompatRuntimeModule
compilation.hooks.additionalTreeRuntimeRequirements.tap(
PLUGIN_NAME,

View File

@@ -20,13 +20,10 @@ const compileBooleanMatcher = require("./util/compileBooleanMatcher");
const propertyAccess = require("./util/propertyAccess");
const { forEachRuntime, subtractRuntime } = require("./util/runtime");
/** @typedef {import("../declarations/WebpackOptions").Environment} Environment */
/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */
/** @typedef {import("./config/defaults").OutputNormalizedWithDefaults} OutputOptions */
/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("./CodeGenerationResults").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Module")} Module */
@@ -97,10 +94,7 @@ class RuntimeTemplate {
this.globalObject =
/** @type {string} */
(getGlobalObject(outputOptions.globalObject));
this.contentHashReplacement = "X".repeat(
/** @type {NonNullable<OutputOptions["hashDigestLength"]>} */
(outputOptions.hashDigestLength)
);
this.contentHashReplacement = "X".repeat(outputOptions.hashDigestLength);
}
isIIFE() {
@@ -113,7 +107,7 @@ class RuntimeTemplate {
isNeutralPlatform() {
return (
!this.outputOptions.environment.document &&
!this.compilation.compiler.platform.web &&
!this.compilation.compiler.platform.node
);
}
@@ -172,6 +166,13 @@ class RuntimeTemplate {
: `"${mod}"`;
}
/**
* @returns {"const" | "var"} return `const` when it is supported, otherwise `var`
*/
renderConst() {
return this.supportsConst() ? "const" : "var";
}
/**
* @param {string} returnValue return value
* @param {string} args arguments
@@ -195,7 +196,7 @@ class RuntimeTemplate {
}
/**
* @param {Array<string|{expr: string}>} args args
* @param {(string | { expr: string })[]} args args
* @returns {string} result expression
*/
concatenation(...args) {
@@ -244,7 +245,7 @@ class RuntimeTemplate {
}
/**
* @param {Array<string|{expr: string}>} args args (len >= 2)
* @param {(string | { expr: string })[]} args args (len >= 2)
* @returns {string} result expression
* @private
*/
@@ -948,7 +949,16 @@ class RuntimeTemplate {
// when the defaultInterop is used (when a ESM imports a CJS module),
if (exportName.length > 0 && exportName[0] === "default") {
if (isDeferred && exportsType !== "namespace") {
const access = `${importVar}.a${propertyAccess(exportName, 1)}`;
const exportsInfo = moduleGraph.getExportsInfo(module);
const name = exportName.slice(1);
const used = exportsInfo.getUsedName(name, runtime);
if (!used) {
const comment = Template.toNormalComment(
`unused export ${propertyAccess(exportName)}`
);
return `${comment} undefined`;
}
const access = `${importVar}.a${propertyAccess(used)}`;
if (isCall || asiSafe === undefined) {
return access;
}

View File

@@ -14,9 +14,9 @@ const PLUGIN_NAME = "SourceMapDevToolModuleOptionsPlugin";
class SourceMapDevToolModuleOptionsPlugin {
/**
* @param {SourceMapDevToolPluginOptions} options options
* @param {SourceMapDevToolPluginOptions=} options options
*/
constructor(options) {
constructor(options = {}) {
this.options = options;
}

View File

@@ -19,9 +19,7 @@ const { makePathsAbsolute } = require("./util/identifier");
/** @typedef {import("webpack-sources").MapOptions} MapOptions */
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").HashFunction} HashFunction */
/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */
/** @typedef {import("./Cache").Etag} Etag */
/** @typedef {import("./CacheFacade").ItemCacheFacade} ItemCacheFacade */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compilation").Asset} Asset */
@@ -109,7 +107,7 @@ const getTaskForFile = (
source = asset.source();
}
if (!sourceMap || typeof source !== "string") return;
const context = /** @type {string} */ (compilation.options.context);
const context = compilation.options.context;
const root = compilation.compiler.root;
const cachedAbsolutify = makePathsAbsolute.bindContextCache(context, root);
const modules = sourceMap.sources.map((source) => {
@@ -162,9 +160,9 @@ class SourceMapDevToolPlugin {
* @returns {void}
*/
apply(compiler) {
const outputFs = /** @type {OutputFileSystem} */ (
compiler.outputFileSystem
);
const outputFs =
/** @type {OutputFileSystem} */
(compiler.outputFileSystem);
const sourceMapFilename = this.sourceMapFilename;
const sourceMappingURLComment = this.sourceMappingURLComment;
const moduleFilenameTemplate = this.moduleFilenameTemplate;
@@ -361,7 +359,7 @@ class SourceMapDevToolPlugin {
/**
* all modules in defined order (longest identifier first)
* @type {Array<string | Module>}
* @type {(string | Module)[]}
*/
const allModules = [...moduleToSourceNameMapping.keys()].sort(
(a, b) => {
@@ -484,17 +482,12 @@ class SourceMapDevToolPlugin {
const sourceMapString = JSON.stringify(sourceMap);
if (sourceMapFilename) {
const filename = file;
const sourceMapContentHash =
/** @type {string} */
(
usesContentHash &&
createHash(
/** @type {HashFunction} */
(compilation.outputOptions.hashFunction)
)
.update(sourceMapString)
.digest("hex")
);
const sourceMapContentHash = usesContentHash
? createHash(compilation.outputOptions.hashFunction)
.update(sourceMapString)
.digest("hex")
: undefined;
const pathParams = {
chunk,
filename: options.fileContext

1
node_modules/webpack/lib/Stats.js generated vendored
View File

@@ -7,7 +7,6 @@
/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").NormalizedStatsOptions} NormalizedStatsOptions */
/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */
class Stats {

17
node_modules/webpack/lib/Template.js generated vendored
View File

@@ -10,7 +10,7 @@ const { WEBPACK_MODULE_TYPE_RUNTIME } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */
/** @typedef {import("./config/defaults").OutputNormalizedWithDefaults} OutputOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
@@ -49,7 +49,7 @@ const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;
* @property {string} fullHash
* @property {OutputOptions} outputOptions
* @property {CodeGenerationResults} codeGenerationResults
* @property {{javascript: ModuleTemplate}} moduleTemplates
* @property {{ javascript: ModuleTemplate }} moduleTemplates
* @property {DependencyTemplates} dependencyTemplates
* @property {RuntimeTemplate} runtimeTemplate
* @property {ModuleGraph} moduleGraph
@@ -79,11 +79,6 @@ const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g;
* @property {boolean=} auxiliary
*/
/**
* @typedef {object} HasId
* @property {number | string} id
*/
/**
* @typedef {(module: Module) => boolean} ModuleFilterPredicate
*/
@@ -226,7 +221,7 @@ class Template {
}
/**
* @param {string|string[]} s string to create prefix for
* @param {string | string[]} s string to create prefix for
* @param {string} prefix prefix to compose
* @returns {string} returns new prefix string
*/
@@ -238,7 +233,7 @@ class Template {
}
/**
* @param {string|string[]} str string or string collection
* @param {string | string[]} str string or string collection
* @returns {string} returns a single string from array
*/
static asString(str) {
@@ -295,7 +290,7 @@ class Template {
if (modules.length === 0) {
return null;
}
/** @type {{id: string|number, source: Source|string}[]} */
/** @type {{ id: ModuleId, source: Source | "false" }[]} */
const allModules = modules.map((module) => ({
id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)),
source: renderModule(module) || "false"
@@ -309,7 +304,7 @@ class Template {
source.add(`Array(${minId}).concat(`);
}
source.add("[\n");
/** @type {Map<string|number, {id: string|number, source: Source|string}>} */
/** @type {Map<ModuleId, { id: ModuleId, source: Source | "false" }>} */
const modules = new Map();
for (const module of allModules) {
modules.set(module.id, module);

View File

@@ -133,7 +133,8 @@ const deprecated = (fn, message, code) => {
);
};
/** @typedef {string | ((pathData: PathData, assetInfo?: AssetInfo) => string)} TemplatePath */
/** @typedef {(pathData: PathData, assetInfo?: AssetInfo) => string} TemplatePathFn */
/** @typedef {string | TemplatePathFn} TemplatePath */
/**
* @param {TemplatePath} path the raw path

View File

@@ -9,7 +9,6 @@ const { groupBy } = require("./util/ArrayHelpers");
const createSchemaValidation = require("./util/create-schema-validation");
/** @typedef {import("../declarations/plugins/WatchIgnorePlugin").WatchIgnorePluginOptions} WatchIgnorePluginOptions */
/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./util/fs").TimeInfoEntries} TimeInfoEntries */
/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */
@@ -51,12 +50,12 @@ class IgnoringWatchFileSystem {
);
const [ignoredFiles, notIgnoredFiles] = groupBy(
/** @type {Array<string>} */
/** @type {string[]} */
(files),
ignored
);
const [ignoredDirs, notIgnoredDirs] = groupBy(
/** @type {Array<string>} */
/** @type {string[]} */
(dirs),
ignored
);

30
node_modules/webpack/lib/Watching.js generated vendored
View File

@@ -10,20 +10,20 @@ const Stats = require("./Stats");
/** @typedef {import("../declarations/WebpackOptions").WatchOptions} WatchOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./FileSystemInfo").FileSystemInfoEntry} FileSystemInfoEntry */
/** @typedef {import("./Compiler").ErrorCallback} ErrorCallback */
/** @typedef {import("./WebpackError")} WebpackError */
/** @typedef {import("./logging/Logger").Logger} Logger */
/** @typedef {import("./util/fs").TimeInfoEntries} TimeInfoEntries */
/** @typedef {import("./util/fs").WatchFileSystem} WatchFileSystem */
/** @typedef {import("./util/fs").Watcher} Watcher */
/**
* @template T
* @callback Callback
* @param {Error | null} err
* @param {T=} result
* @template [R=void]
* @typedef {import("./webpack").Callback<T, R>} Callback
*/
/** @typedef {Set<string>} CollectedFiles */
class Watching {
/**
* @param {Compiler} compiler the compiler
@@ -34,9 +34,9 @@ class Watching {
this.startTime = null;
this.invalid = false;
this.handler = handler;
/** @type {Callback<void>[]} */
/** @type {ErrorCallback[]} */
this.callbacks = [];
/** @type {Callback<void>[] | undefined} */
/** @type {ErrorCallback[] | undefined} */
this._closeCallbacks = undefined;
this.closed = false;
this.suspended = false;
@@ -66,9 +66,9 @@ class Watching {
this._needRecords = true;
this.watcher = undefined;
this.pausedWatcher = undefined;
/** @type {Set<string> | undefined} */
/** @type {CollectedFiles | undefined} */
this._collectedChangedFiles = undefined;
/** @type {Set<string> | undefined} */
/** @type {CollectedFiles | undefined} */
this._collectedRemovedFiles = undefined;
this._done = this._done.bind(this);
process.nextTick(() => {
@@ -88,12 +88,12 @@ class Watching {
} else {
for (const file of changedFiles) {
this._collectedChangedFiles.add(file);
/** @type {Set<string>} */
/** @type {CollectedFiles} */
(this._collectedRemovedFiles).delete(file);
}
for (const file of /** @type {ReadonlySet<string>} */ (removedFiles)) {
this._collectedChangedFiles.delete(file);
/** @type {Set<string>} */
/** @type {CollectedFiles} */
(this._collectedRemovedFiles).add(file);
}
}
@@ -262,7 +262,7 @@ class Watching {
/**
* @param {Error} err error
* @param {Callback<void>[]=} cbs callbacks
* @param {ErrorCallback[]=} cbs callbacks
*/
const handleError = (err, cbs) => {
this.compiler.hooks.failed.call(err);
@@ -393,7 +393,7 @@ class Watching {
}
/**
* @param {Callback<void>=} callback signals when the build has completed again
* @param {ErrorCallback=} callback signals when the build has completed again
* @returns {void}
*/
invalidate(callback) {
@@ -451,7 +451,7 @@ class Watching {
}
/**
* @param {Callback<void>} callback signals when the watcher is closed
* @param {ErrorCallback} callback signals when the watcher is closed
* @returns {void}
*/
close(callback) {
@@ -481,7 +481,7 @@ class Watching {
const shutdown = (err) => {
this.compiler.hooks.watchClose.call();
const closeCallbacks =
/** @type {Callback<void>[]} */
/** @type {ErrorCallback[]} */
(this._closeCallbacks);
this._closeCallbacks = undefined;
for (const cb of closeCallbacks) cb(err);

View File

@@ -16,10 +16,8 @@ const {
toConstantDependency
} = require("./javascript/JavascriptParserHelpers");
/** @typedef {import("enhanced-resolve").Resolver} Resolver */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */

View File

@@ -73,9 +73,8 @@ const DefaultStatsPrinterPlugin = require("./stats/DefaultStatsPrinterPlugin");
const { cleverMerge } = require("./util/cleverMerge");
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("../declarations/WebpackOptions").WebpackPluginFunction} WebpackPluginFunction */
/** @typedef {import("../declarations/WebpackOptions").WebpackPluginInstance} WebpackPluginInstance */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/fs").IntermediateFileSystem} IntermediateFileSystem */
@@ -93,7 +92,7 @@ class WebpackOptionsApply extends OptionsApply {
* @returns {WebpackOptions} options object
*/
process(options, compiler) {
compiler.outputPath = /** @type {string} */ (options.output.path);
compiler.outputPath = options.output.path;
compiler.recordsInputPath = options.recordsInputPath || null;
compiler.recordsOutputPath = options.recordsOutputPath || null;
compiler.name = options.name;
@@ -111,35 +110,86 @@ class WebpackOptionsApply extends OptionsApply {
const NodeTargetPlugin = require("./node/NodeTargetPlugin");
new NodeTargetPlugin().apply(compiler);
}
if (options.externalsPresets.electronMain) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
new ElectronTargetPlugin("main").apply(compiler);
}
if (options.externalsPresets.electronPreload) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
// Handle external CSS `@import` and `url()`
if (options.experiments.css) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ExternalsPlugin = require("./ExternalsPlugin");
new ElectronTargetPlugin("preload").apply(compiler);
}
if (options.externalsPresets.electronRenderer) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
new ExternalsPlugin(
"module",
({ request, dependencyType, contextInfo }, callback) => {
if (
/\.css(\?|$)/.test(contextInfo.issuer) &&
/^(\/\/|https?:\/\/|#)/.test(request)
) {
if (dependencyType === "url") {
return callback(null, `asset ${request}`);
} else if (
dependencyType === "css-import" &&
options.experiments.css
) {
return callback(null, `css-import ${request}`);
}
}
new ElectronTargetPlugin("renderer").apply(compiler);
callback();
}
).apply(compiler);
}
}
if (
options.externalsPresets.electron &&
!options.externalsPresets.electronMain &&
!options.externalsPresets.electronPreload &&
!options.externalsPresets.electronRenderer
) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
if (options.externalsPresets.webAsync || options.externalsPresets.web) {
const type = options.externalsPresets.webAsync ? "import" : "module";
new ElectronTargetPlugin().apply(compiler);
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ExternalsPlugin = require("./ExternalsPlugin");
new ExternalsPlugin(type, ({ request, dependencyType }, callback) => {
if (/^(\/\/|https?:\/\/|#|std:|jsr:|npm:)/.test(request)) {
if (dependencyType === "url") {
return callback(null, `asset ${request}`);
} else if (
dependencyType === "css-import" &&
options.experiments.css
) {
return callback(null, `css-import ${request}`);
} else if (/^(\/\/|https?:\/\/|std:|jsr:|npm:)/.test(request)) {
return callback(null, `${type} ${request}`);
}
}
callback();
}).apply(compiler);
}
if (options.externalsPresets.electron) {
if (options.externalsPresets.electronMain) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
new ElectronTargetPlugin("main").apply(compiler);
}
if (options.externalsPresets.electronPreload) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
new ElectronTargetPlugin("preload").apply(compiler);
}
if (options.externalsPresets.electronRenderer) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
new ElectronTargetPlugin("renderer").apply(compiler);
}
if (
!options.externalsPresets.electronMain &&
!options.externalsPresets.electronPreload &&
!options.externalsPresets.electronRenderer
) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
new ElectronTargetPlugin().apply(compiler);
}
}
if (options.externalsPresets.nwjs) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
@@ -147,80 +197,6 @@ class WebpackOptionsApply extends OptionsApply {
new ExternalsPlugin("node-commonjs", "nw.gui").apply(compiler);
}
if (options.externalsPresets.webAsync) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ExternalsPlugin = require("./ExternalsPlugin");
new ExternalsPlugin("import", ({ request, dependencyType }, callback) => {
if (dependencyType === "url") {
if (/^(\/\/|https?:\/\/|#)/.test(/** @type {string} */ (request))) {
return callback(null, `asset ${request}`);
}
} else if (options.experiments.css && dependencyType === "css-import") {
if (/^(\/\/|https?:\/\/|#)/.test(/** @type {string} */ (request))) {
return callback(null, `css-import ${request}`);
}
} else if (
options.experiments.css &&
/^(\/\/|https?:\/\/|std:)/.test(/** @type {string} */ (request))
) {
if (/^\.css(\?|$)/.test(/** @type {string} */ (request))) {
return callback(null, `css-import ${request}`);
}
return callback(null, `import ${request}`);
}
callback();
}).apply(compiler);
} else if (options.externalsPresets.web) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ExternalsPlugin = require("./ExternalsPlugin");
new ExternalsPlugin("module", ({ request, dependencyType }, callback) => {
if (dependencyType === "url") {
if (/^(\/\/|https?:\/\/|#)/.test(/** @type {string} */ (request))) {
return callback(null, `asset ${request}`);
}
} else if (options.experiments.css && dependencyType === "css-import") {
if (/^(\/\/|https?:\/\/|#)/.test(/** @type {string} */ (request))) {
return callback(null, `css-import ${request}`);
}
} else if (
/^(\/\/|https?:\/\/|std:)/.test(/** @type {string} */ (request))
) {
if (
options.experiments.css &&
/^\.css((\?)|$)/.test(/** @type {string} */ (request))
) {
return callback(null, `css-import ${request}`);
}
return callback(null, `module ${request}`);
}
callback();
}).apply(compiler);
} else if (options.externalsPresets.node && options.experiments.css) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ExternalsPlugin = require("./ExternalsPlugin");
new ExternalsPlugin("module", ({ request, dependencyType }, callback) => {
if (dependencyType === "url") {
if (/^(\/\/|https?:\/\/|#)/.test(/** @type {string} */ (request))) {
return callback(null, `asset ${request}`);
}
} else if (dependencyType === "css-import") {
if (/^(\/\/|https?:\/\/|#)/.test(/** @type {string} */ (request))) {
return callback(null, `css-import ${request}`);
}
} else if (
/^(\/\/|https?:\/\/|std:)/.test(/** @type {string} */ (request))
) {
if (/^\.css(\?|$)/.test(/** @type {string} */ (request))) {
return callback(null, `css-import ${request}`);
}
return callback(null, `module ${request}`);
}
callback();
}).apply(compiler);
}
new ChunkPrefetchPreloadPlugin().apply(compiler);
@@ -446,11 +422,7 @@ class WebpackOptionsApply extends OptionsApply {
}
new EntryOptionPlugin().apply(compiler);
compiler.hooks.entryOption.call(
/** @type {string} */
(options.context),
options.entry
);
compiler.hooks.entryOption.call(options.context, options.entry);
new RuntimePlugin().apply(compiler);
@@ -461,7 +433,6 @@ class WebpackOptionsApply extends OptionsApply {
new CompatibilityPlugin().apply(compiler);
new HarmonyModulesPlugin({
topLevelAwait: options.experiments.topLevelAwait,
deferImport: options.experiments.deferImport
}).apply(compiler);
if (options.amd !== false) {
@@ -478,9 +449,7 @@ class WebpackOptionsApply extends OptionsApply {
new NodeStuffPlugin(options.node).apply(compiler);
}
new APIPlugin({
module: options.output.module
}).apply(compiler);
new APIPlugin().apply(compiler);
new ExportsInfoApiPlugin().apply(compiler);
new WebpackIsIncludedPlugin().apply(compiler);
new ConstPlugin().apply(compiler);
@@ -703,9 +672,7 @@ class WebpackOptionsApply extends OptionsApply {
}).apply(compiler);
}
if (options.optimization.minimize) {
for (const minimizer of /** @type {(WebpackPluginInstance | WebpackPluginFunction | "...")[]} */ (
options.optimization.minimizer
)) {
for (const minimizer of options.optimization.minimizer) {
if (typeof minimizer === "function") {
/** @type {WebpackPluginFunction} */
(minimizer).call(compiler, compiler);
@@ -810,7 +777,7 @@ class WebpackOptionsApply extends OptionsApply {
fs:
/** @type {IntermediateFileSystem} */
(compiler.intermediateFileSystem),
context: /** @type {string} */ (options.context),
context: options.context,
cacheLocation:
/** @type {string} */
(cacheOptions.cacheLocation),

167
node_modules/webpack/lib/asset/AssetBytesGenerator.js generated vendored Executable file
View File

@@ -0,0 +1,167 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Alexander Akait @alexander-akait
*/
"use strict";
const { RawSource } = require("webpack-sources");
const ConcatenationScope = require("../ConcatenationScope");
const Generator = require("../Generator");
const {
CSS_URL_TYPES,
JS_AND_CSS_URL_TYPES,
JS_TYPES,
NO_TYPES
} = require("../ModuleSourceTypesConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../NormalModule")} NormalModule */
class AssetSourceGenerator extends Generator {
/**
* @param {ModuleGraph} moduleGraph the module graph
*/
constructor(moduleGraph) {
super();
this._moduleGraph = moduleGraph;
}
/**
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source | null} generated code
*/
generate(
module,
{ type, concatenationScope, getData, runtimeTemplate, runtimeRequirements }
) {
const originalSource = module.originalSource();
const data = getData ? getData() : undefined;
switch (type) {
case "javascript": {
if (!originalSource) {
return new RawSource("");
}
const encodedSource = originalSource.buffer().toString("base64");
runtimeRequirements.add(RuntimeGlobals.requireScope);
runtimeRequirements.add(RuntimeGlobals.toBinary);
let sourceContent;
if (concatenationScope) {
concatenationScope.registerNamespaceExport(
ConcatenationScope.NAMESPACE_OBJECT_EXPORT
);
sourceContent = `${runtimeTemplate.renderConst()} ${
ConcatenationScope.NAMESPACE_OBJECT_EXPORT
} = ${RuntimeGlobals.toBinary}(${JSON.stringify(encodedSource)});`;
} else {
runtimeRequirements.add(RuntimeGlobals.module);
sourceContent = `${RuntimeGlobals.module}.exports = ${RuntimeGlobals.toBinary}(${JSON.stringify(
encodedSource
)});`;
}
return new RawSource(sourceContent);
}
case "css-url": {
if (!originalSource) {
return null;
}
const encodedSource = originalSource.buffer().toString("base64");
if (data) {
data.set("url", {
[type]: `data:application/octet-stream;base64,${encodedSource}`
});
}
return null;
}
default:
return null;
}
}
/**
* @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 "javascript": {
return new RawSource(
`throw new Error(${JSON.stringify(error.message)});`
);
}
default:
return null;
}
}
/**
* @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;
}
/**
* @param {NormalModule} module fresh module
* @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) {
if (!connection.originModule) {
continue;
}
sourceTypes.add(connection.originModule.type.split("/")[0]);
}
if (sourceTypes.size > 0) {
if (sourceTypes.has("javascript") && sourceTypes.has("css")) {
return JS_AND_CSS_URL_TYPES;
} else if (sourceTypes.has("css")) {
return CSS_URL_TYPES;
}
return JS_TYPES;
}
return NO_TYPES;
}
/**
* @param {NormalModule} module the module
* @param {string=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {
const originalSource = module.originalSource();
if (!originalSource) {
return 0;
}
// Example: m.exports="abcd"
return originalSource.size() + 12;
}
}
module.exports = AssetSourceGenerator;

37
node_modules/webpack/lib/asset/AssetBytesParser.js generated vendored Executable file
View File

@@ -0,0 +1,37 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Alexander Akait @alexander-akait
*/
"use strict";
const Parser = require("../Parser");
/** @typedef {import("../Module").BuildInfo} BuildInfo */
/** @typedef {import("../Module").BuildMeta} BuildMeta */
/** @typedef {import("../Parser").ParserState} ParserState */
/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
class AssetBytesParser extends Parser {
/**
* @param {string | Buffer | PreparsedAst} source the source to parse
* @param {ParserState} state the parser state
* @returns {ParserState} the parser state
*/
parse(source, state) {
if (typeof source === "object" && !Buffer.isBuffer(source)) {
throw new Error("AssetBytesParser doesn't accept preparsed AST");
}
const { module } = state;
/** @type {BuildInfo} */
(module.buildInfo).strict = true;
/** @type {BuildMeta} */
(module.buildMeta).exportsType = "default";
/** @type {BuildMeta} */
(state.module.buildMeta).defaultObject = false;
return state;
}
}
module.exports = AssetBytesParser;

View File

@@ -6,7 +6,6 @@
"use strict";
const path = require("path");
const mimeTypes = require("mime-types");
const { RawSource } = require("webpack-sources");
const ConcatenationScope = require("../ConcatenationScope");
const Generator = require("../Generator");
@@ -25,41 +24,38 @@ const RuntimeGlobals = require("../RuntimeGlobals");
const CssUrlDependency = require("../dependencies/CssUrlDependency");
const createHash = require("../util/createHash");
const { makePathsRelative } = require("../util/identifier");
const memoize = require("../util/memoize");
const nonNumericOnlyHash = require("../util/nonNumericOnlyHash");
const getMimeTypes = memoize(() => require("mime-types"));
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").AssetGeneratorDataUrlOptions} AssetGeneratorDataUrlOptions */
/** @typedef {import("../../declarations/WebpackOptions").AssetGeneratorOptions} AssetGeneratorOptions */
/** @typedef {import("../../declarations/WebpackOptions").AssetModuleFilename} AssetModuleFilename */
/** @typedef {import("../../declarations/WebpackOptions").AssetModuleOutputPath} AssetModuleOutputPath */
/** @typedef {import("../../declarations/WebpackOptions").AssetResourceGeneratorOptions} AssetResourceGeneratorOptions */
/** @typedef {import("../../declarations/WebpackOptions").HashFunction} HashFunction */
/** @typedef {import("../../declarations/WebpackOptions").RawPublicPath} RawPublicPath */
/** @typedef {import("../ChunkGraph")} ChunkGraph */
/** @typedef {import("../Compilation")} Compilation */
/** @typedef {import("../Compilation").AssetInfo} AssetInfo */
/** @typedef {import("../Compilation").InterpolatedPathAndAssetInfo} InterpolatedPathAndAssetInfo */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../Module")} Module */
/** @typedef {import("../Module").NameForCondition} NameForCondition */
/** @typedef {import("../Module").BuildInfo} BuildInfo */
/** @typedef {import("../Module").BuildMeta} BuildMeta */
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../NormalModule")} NormalModule */
/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("../TemplatedPathPlugin").TemplatePath} TemplatePath */
/** @typedef {import("../util/Hash")} Hash */
/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
/**
* @template T
* @template U
* @param {null | string | Array<T> | Set<T> | undefined} a a
* @param {null | string | Array<U> | Set<U> | undefined} b b
* @returns {Array<T> & Array<U>} array
* @param {null | string | T[] | Set<T> | undefined} a a
* @param {null | string | U[] | Set<U> | undefined} b b
* @returns {T[] & U[]} array
*/
const mergeMaybeArrays = (a, b) => {
const set = new Set();
@@ -220,7 +216,8 @@ class AssetGenerator extends Generator {
static getSourceFileName(module, runtimeTemplate) {
return makePathsRelative(
runtimeTemplate.compilation.compiler.context,
module.matchResource || module.resource,
/** @type {string} */
(module.getResource()),
runtimeTemplate.compilation.compiler.root
).replace(/^\.\//, "");
}
@@ -231,10 +228,7 @@ class AssetGenerator extends Generator {
* @returns {[string, string]} return full hash and non-numeric full hash
*/
static getFullContentHash(module, runtimeTemplate) {
const hash = createHash(
/** @type {HashFunction} */
(runtimeTemplate.outputOptions.hashFunction)
);
const hash = createHash(runtimeTemplate.outputOptions.hashFunction);
if (runtimeTemplate.outputOptions.hashSalt) {
hash.update(runtimeTemplate.outputOptions.hashSalt);
@@ -250,15 +244,13 @@ class AssetGenerator extends Generator {
hash.update(module.error.toString());
}
const fullContentHash = /** @type {string} */ (
hash.digest(runtimeTemplate.outputOptions.hashDigest)
const fullContentHash = hash.digest(
runtimeTemplate.outputOptions.hashDigest
);
/** @type {string} */
const contentHash = nonNumericOnlyHash(
fullContentHash,
/** @type {number} */
(runtimeTemplate.outputOptions.hashDigestLength)
runtimeTemplate.outputOptions.hashDigestLength
);
return [fullContentHash, contentHash];
@@ -279,8 +271,7 @@ class AssetGenerator extends Generator {
) {
const assetModuleFilename =
generatorOptions.filename ||
/** @type {AssetModuleFilename} */
(runtimeTemplate.outputOptions.assetModuleFilename);
runtimeTemplate.outputOptions.assetModuleFilename;
const sourceFilename = AssetGenerator.getSourceFileName(
module,
@@ -381,13 +372,9 @@ class AssetGenerator extends Generator {
const path =
compilation.outputOptions.publicPath === "auto"
? CssUrlDependency.PUBLIC_PATH_AUTO
: compilation.getAssetPath(
/** @type {TemplatePath} */
(compilation.outputOptions.publicPath),
{
hash: compilation.hash
}
);
: compilation.getAssetPath(compilation.outputOptions.publicPath, {
hash: compilation.hash
});
assetPath = path + filename;
}
@@ -425,7 +412,7 @@ class AssetGenerator extends Generator {
(this.dataUrlOptions).mimetype;
if (mimeType === undefined) {
const ext = path.extname(
/** @type {string} */
/** @type {NameForCondition} */
(module.nameForCondition())
);
if (
@@ -436,7 +423,7 @@ class AssetGenerator extends Generator {
module.resourceResolveData.mimetype +
module.resourceResolveData.parameters;
} else if (ext) {
mimeType = mimeTypes.lookup(ext);
mimeType = getMimeTypes().lookup(ext);
if (typeof mimeType !== "string") {
throw new Error(
@@ -471,7 +458,7 @@ class AssetGenerator extends Generator {
if (typeof this.dataUrlOptions === "function") {
encodedSource = this.dataUrlOptions.call(null, source.source(), {
filename: module.matchResource || module.resource,
filename: /** @type {string} */ (module.getResource()),
module
});
} else {
@@ -619,7 +606,7 @@ class AssetGenerator extends Generator {
);
return new RawSource(
`${runtimeTemplate.supportsConst() ? "const" : "var"} ${
`${runtimeTemplate.renderConst()} ${
ConcatenationScope.NAMESPACE_OBJECT_EXPORT
} = ${content};`
);
@@ -794,9 +781,7 @@ class AssetGenerator extends Generator {
}
const assetModuleFilename =
this.filename ||
/** @type {AssetModuleFilename} */
(runtimeTemplate.outputOptions.assetModuleFilename);
this.filename || runtimeTemplate.outputOptions.assetModuleFilename;
const { path: filename, info } =
runtimeTemplate.compilation.getAssetPathWithInfo(
assetModuleFilename,

View File

@@ -7,22 +7,19 @@
const {
ASSET_MODULE_TYPE,
ASSET_MODULE_TYPE_BYTES,
ASSET_MODULE_TYPE_INLINE,
ASSET_MODULE_TYPE_RESOURCE,
ASSET_MODULE_TYPE_SOURCE
} = require("../ModuleTypeConstants");
const { cleverMerge } = require("../util/cleverMerge");
const { compareModulesByIdOrIdentifier } = require("../util/comparators");
const createSchemaValidation = require("../util/create-schema-validation");
const memoize = require("../util/memoize");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").AssetParserOptions} AssetParserOptions */
/** @typedef {import("schema-utils").Schema} Schema */
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Compilation").AssetInfo} AssetInfo */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */
/** @typedef {import("../Module").BuildInfo} BuildInfo */
/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("../NormalModule")} NormalModule */
@@ -74,9 +71,11 @@ const validateParserOptions = createSchemaValidation(
const getAssetGenerator = memoize(() => require("./AssetGenerator"));
const getAssetParser = memoize(() => require("./AssetParser"));
const getAssetSourceParser = memoize(() => require("./AssetSourceParser"));
const getAssetBytesParser = memoize(() => require("./AssetBytesParser"));
const getAssetSourceGenerator = memoize(() =>
require("./AssetSourceGenerator")
);
const getAssetBytesGenerator = memoize(() => require("./AssetBytesGenerator"));
const type = ASSET_MODULE_TYPE;
const PLUGIN_NAME = "AssetModulesPlugin";
@@ -95,11 +94,6 @@ class AssetModulesPlugin {
.for(ASSET_MODULE_TYPE)
.tap(PLUGIN_NAME, (parserOptions) => {
validateParserOptions(parserOptions);
parserOptions = cleverMerge(
/** @type {AssetParserOptions} */
(compiler.options.module.parser.asset),
parserOptions
);
let dataUrlCondition = parserOptions.dataUrlCondition;
if (!dataUrlCondition || typeof dataUrlCondition === "object") {
@@ -134,6 +128,13 @@ class AssetModulesPlugin {
return new AssetSourceParser();
});
normalModuleFactory.hooks.createParser
.for(ASSET_MODULE_TYPE_BYTES)
.tap(PLUGIN_NAME, (_parserOptions) => {
const AssetBytesParser = getAssetBytesParser();
return new AssetBytesParser();
});
for (const type of [
ASSET_MODULE_TYPE,
@@ -186,6 +187,14 @@ class AssetModulesPlugin {
return new AssetSourceGenerator(compilation.moduleGraph);
});
normalModuleFactory.hooks.createGenerator
.for(ASSET_MODULE_TYPE_BYTES)
.tap(PLUGIN_NAME, () => {
const AssetBytesGenerator = getAssetBytesGenerator();
return new AssetBytesGenerator(compilation.moduleGraph);
});
compilation.hooks.renderManifest.tap(PLUGIN_NAME, (result, options) => {
const { chunkGraph } = compilation;
const { chunk, codeGenerationResults, runtimeTemplate } = options;
@@ -245,10 +254,15 @@ class AssetModulesPlugin {
entryInfo = assetInfo;
entryHash = fullContentHash;
} else {
entryFilename = buildInfo.filename || data.get("filename");
entryInfo = buildInfo.assetInfo || data.get("assetInfo");
entryFilename =
/** @type {string} */
(buildInfo.filename || data.get("filename"));
entryInfo =
/** @type {AssetInfo} */
(buildInfo.assetInfo || data.get("assetInfo"));
entryHash =
buildInfo.fullContentHash || data.get("fullContentHash");
/** @type {string} */
(buildInfo.fullContentHash || data.get("fullContentHash"));
}
result.push({
@@ -280,10 +294,14 @@ class AssetModulesPlugin {
const data =
/** @type {NonNullable<CodeGenerationResult["data"]>} */
(codeGenerationResult.data);
context.assets.set(data.get("filename"), {
source,
info: data.get("assetInfo")
});
context.assets.set(
/** @type {string} */
(data.get("filename")),
{
source,
info: data.get("assetInfo")
}
);
}
);
}

View File

@@ -33,15 +33,19 @@ class AssetParser extends Parser {
throw new Error("AssetParser doesn't accept preparsed AST");
}
const buildInfo = /** @type {BuildInfo} */ (state.module.buildInfo);
const buildInfo =
/** @type {BuildInfo} */
(state.module.buildInfo);
buildInfo.strict = true;
const buildMeta = /** @type {BuildMeta} */ (state.module.buildMeta);
const buildMeta =
/** @type {BuildMeta} */
(state.module.buildMeta);
buildMeta.exportsType = "default";
buildMeta.defaultObject = false;
if (typeof this.dataUrlCondition === "function") {
buildInfo.dataUrl = this.dataUrlCondition(source, {
filename: state.module.matchResource || state.module.resource,
filename: /** @type {string} */ (state.module.getResource()),
module: state.module
});
} else if (typeof this.dataUrlCondition === "boolean") {

Some files were not shown because too many files have changed in this diff Show More