Deployed the page to Github Pages.

This commit is contained in:
Batuhan Berk Başoğlu 2024-11-03 21:30:09 -05:00
parent 1d79754e93
commit 2c89899458
Signed by: batuhan-basoglu
SSH key fingerprint: SHA256:kEsnuHX+qbwhxSAXPUQ4ox535wFHu/hIRaa53FzxRpo
62797 changed files with 6551425 additions and 15279 deletions

20
node_modules/webpack/LICENSE generated vendored Normal file
View file

@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

727
node_modules/webpack/README.md generated vendored Normal file
View file

@ -0,0 +1,727 @@
<div align="center">
<a href="https://github.com/webpack/webpack">
<img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg">
</a>
<br>
<br>
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![builds1][builds1]][builds1-url]
[![builds2][builds2]][builds2-url]
[![dependency-review][dependency-review]][dependency-review-url]
[![coverage][cover]][cover-url]
[![PR's welcome][prs]][prs-url]
<br>
<a href="https://docs.github.com/en/code-security/dependabot/dependabot-security-updates/about-dependabot-security-updates#about-compatibility-scores">
<img src="https://api.dependabot.com/badges/compatibility_score?dependency-name=webpack&package-manager=npm_and_yarn&previous-version=5.72.1&new-version=5.73.0">
</a>
<a href="https://npmcharts.com/compare/webpack?minimal=true">
<img src="https://img.shields.io/npm/dm/webpack.svg">
</a>
<a href="https://packagephobia.com/result?p=webpack">
<img src="https://packagephobia.com/badge?p=webpack" alt="install size">
</a>
<a href="https://opencollective.com/webpack#backer">
<img src="https://opencollective.com/webpack/backers/badge.svg">
</a>
<a href="https://opencollective.com/webpack#sponsors">
<img src="https://opencollective.com/webpack/sponsors/badge.svg">
</a>
<a href="https://github.com/webpack/webpack/graphs/contributors">
<img src="https://img.shields.io/github/contributors/webpack/webpack.svg">
</a>
<a href="https://github.com/webpack/webpack/discussions">
<img src="https://img.shields.io/github/discussions/webpack/webpack">
</a>
<a href="https://twitter.com/Webpack">
<img src="https://img.shields.io/twitter/follow/Webpack?style=social">
</a>
<a href="https://discord.gg/Tt5cKVwx">
<img src="https://img.shields.io/discord/1180618526436888586?label=discord&logo=discord&logoColor=white&style=flat">
</a>
<h1>webpack</h1>
<p>
Webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.
</p>
</div>
## Table of Contents
1. [Install](#install)
2. [Introduction](#introduction)
3. [Concepts](#concepts)
4. [Contributing](#contributing)
5. [Support](#support)
6. [Core Team](#core-team)
7. [Sponsoring](#sponsoring)
8. [Premium Partners](#premium-partners)
9. [Other Backers and Sponsors](#other-backers-and-sponsors)
10. [Gold Sponsors](#gold-sponsors)
11. [Silver Sponsors](#silver-sponsors)
12. [Bronze Sponsors](#bronze-sponsors)
13. [Backers](#backers)
14. [Special Thanks](#special-thanks-to)
<h2 align="center">Install</h2>
Install with npm:
```bash
npm install --save-dev webpack
```
Install with yarn:
```bash
yarn add webpack --dev
```
<h2 align="center">Introduction</h2>
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,
or packaging just about any resource or asset.
**TL;DR**
- Bundles [ES Modules](https://www.2ality.com/2014/09/es6-modules-final.html), [CommonJS](http://wiki.commonjs.org/), and [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) modules (even combined).
- Can create a single bundle or multiple chunks that are asynchronously loaded at runtime (to reduce initial loading time).
- Dependencies are resolved during compilation, reducing the runtime size.
- Loaders can preprocess files while compiling, e.g. TypeScript to JavaScript, Handlebars strings to compiled functions, images to Base64, etc.
- Highly modular plugin system to do whatever else your application requires.
### Get Started
Check out webpack's quick [**Get Started**](https://webpack.js.org/guides/getting-started) guide and the [other guides](https://webpack.js.org/guides/).
### Browser Compatibility
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 align="center">Concepts</h2>
### [Plugins](https://webpack.js.org/plugins/)
Webpack has a [rich plugin
interface](https://webpack.js.org/plugins/). Most of the features
within webpack itself use this plugin interface. This makes webpack very
**flexible**.
| Name | Status | Install Size | Description |
| :---------------------------------------: | :----------------: | :-----------------: | :-------------------------------------------------------------------------------------- |
| [mini-css-extract-plugin][mini-css] | ![mini-css-npm] | ![mini-css-size] | Extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. |
| [compression-webpack-plugin][compression] | ![compression-npm] | ![compression-size] | Prepares compressed versions of assets to serve them with Content-Encoding |
| [html-webpack-plugin][html-plugin] | ![html-plugin-npm] | ![html-plugin-size] | Simplifies creation of HTML files (`index.html`) to serve your bundles |
| [pug-plugin][pug-plugin] | ![pug-plugin-npm] | ![pug-plugin-size] | Renders Pug files to HTML, extracts JS and CSS from sources specified directly in Pug. |
[common-npm]: https://img.shields.io/npm/v/webpack.svg
[mini-css]: https://github.com/webpack-contrib/mini-css-extract-plugin
[mini-css-npm]: https://img.shields.io/npm/v/mini-css-extract-plugin.svg
[mini-css-size]: https://packagephobia.com/badge?p=mini-css-extract-plugin
[component]: https://github.com/webpack-contrib/component-webpack-plugin
[component-npm]: https://img.shields.io/npm/v/component-webpack-plugin.svg
[component-size]: https://packagephobia.com/badge?p=component-webpack-plugin
[compression]: https://github.com/webpack-contrib/compression-webpack-plugin
[compression-npm]: https://img.shields.io/npm/v/compression-webpack-plugin.svg
[compression-size]: https://packagephobia.com/badge?p=compression-webpack-plugin
[html-plugin]: https://github.com/jantimon/html-webpack-plugin
[html-plugin-npm]: https://img.shields.io/npm/v/html-webpack-plugin.svg
[html-plugin-size]: https://packagephobia.com/badge?p=html-webpack-plugin
[pug-plugin]: https://github.com/webdiscus/pug-plugin
[pug-plugin-npm]: https://img.shields.io/npm/v/pug-plugin.svg
[pug-plugin-size]: https://packagephobia.com/badge?p=pug-plugin
### [Loaders](https://webpack.js.org/loaders/)
Webpack enables the use of loaders to preprocess files. This allows you to bundle
**any static resource** way beyond JavaScript. You can easily [write your own
loaders](https://webpack.js.org/api/loaders/) using Node.js.
Loaders are activated by using `loadername!` prefixes in `require()` statements,
or are automatically applied via regex from your webpack configuration.
#### Files
| Name | Status | Install Size | Description |
| :---------------: | :--------: | :----------: | :------------------------------------------------------- |
| [val-loader][val] | ![val-npm] | ![val-size] | Executes code as module and considers exports as JS code |
[val]: https://github.com/webpack-contrib/val-loader
[val-npm]: https://img.shields.io/npm/v/val-loader.svg
[val-size]: https://packagephobia.com/badge?p=val-loader
#### JSON
| Name | Status | Install Size | Description |
| :---------------------------------------------------------------------------------------------------------------------------------------: | :---------: | :----------: | :------------------------------: |
| <a href="https://github.com/awnist/cson-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a> | ![cson-npm] | ![cson-size] | Loads and transpiles a CSON file |
[cson-npm]: https://img.shields.io/npm/v/cson-loader.svg
[cson-size]: https://packagephobia.com/badge?p=cson-loader
#### Transpiling
| Name | Status | Install Size | Description |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-----------: | :------------: | :------------------------------------------------------------------------------------------------ |
| <a href="https://github.com/babel/babel-loader"><img width="48" height="48" title="babel-loader" src="https://worldvectorlogo.com/logos/babel-10.svg"></a> | ![babel-npm] | ![babel-size] | Loads ES2015+ code and transpiles to ES5 using <a href="https://github.com/babel/babel">Babel</a> |
| <a href="https://github.com/TypeStrong/ts-loader"><img width="48" height="48" src="https://raw.githubusercontent.com/microsoft/TypeScript-Website/f407e1ae19e5e990d9901ac8064a32a8cc60edf0/packages/typescriptlang-org/static/branding/ts-logo-128.svg"></a> | ![type-npm] | ![type-size] | Loads TypeScript like JavaScript |
| <a href="https://github.com/webpack-contrib/coffee-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a> | ![coffee-npm] | ![coffee-size] | Loads CoffeeScript like JavaScript |
[babel-npm]: https://img.shields.io/npm/v/babel-loader.svg
[babel-size]: https://packagephobia.com/badge?p=babel-loader
[coffee-npm]: https://img.shields.io/npm/v/coffee-loader.svg
[coffee-size]: https://packagephobia.com/badge?p=coffee-loader
[type-npm]: https://img.shields.io/npm/v/ts-loader.svg
[type-size]: https://packagephobia.com/badge?p=ts-loader
#### Templating
| Name | Status | Install Size | Description |
| :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------: | :--------------: | :-------------------------------------------------------------------------------------- |
| <a href="https://github.com/webpack-contrib/html-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/html5-2.svg"></a> | ![html-npm] | ![html-size] | Exports HTML as string, requires references to static resources |
| <a href="https://github.com/pugjs/pug-loader"><img width="48" height="48" src="https://cdn.rawgit.com/pugjs/pug-logo/master/SVG/pug-final-logo-_-colour-128.svg"></a> | ![pug-npm] | ![pug-size] | Loads Pug templates and returns a function |
| <a href="https://github.com/webdiscus/pug-loader"><img width="48" height="48" src="https://cdn.rawgit.com/pugjs/pug-logo/master/SVG/pug-final-logo-_-colour-128.svg"></a> | ![pug3-npm] | ![pug3-size] | Compiles Pug to a function or HTML string, useful for use with Vue, React, Angular |
| <a href="https://github.com/peerigon/markdown-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/markdown.svg"></a> | ![md-npm] | ![md-size] | Compiles Markdown to HTML |
| <a href="https://github.com/posthtml/posthtml-loader"><img width="48" height="48" src="https://posthtml.github.io/posthtml/logo.svg"></a> | ![posthtml-npm] | ![posthtml-size] | Loads and transforms a HTML file using [PostHTML](https://github.com/posthtml/posthtml) |
| <a href="https://github.com/pcardune/handlebars-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/handlebars-1.svg"></a> | ![hbs-npm] | ![hbs-size] | Compiles Handlebars to HTML |
[html-npm]: https://img.shields.io/npm/v/html-loader.svg
[html-size]: https://packagephobia.com/badge?p=html-loader
[pug-npm]: https://img.shields.io/npm/v/pug-loader.svg
[pug-size]: https://packagephobia.com/badge?p=pug-loader
[pug3-npm]: https://img.shields.io/npm/v/@webdiscus/pug-loader.svg
[pug3-size]: https://packagephobia.com/badge?p=@webdiscus/pug-loader
[jade-npm]: https://img.shields.io/npm/v/jade-loader.svg
[jade-size]: https://packagephobia.com/badge?p=jade-loader
[md-npm]: https://img.shields.io/npm/v/markdown-loader.svg
[md-size]: https://packagephobia.com/badge?p=markdown-loader
[posthtml-npm]: https://img.shields.io/npm/v/posthtml-loader.svg
[posthtml-size]: https://packagephobia.com/badge?p=posthtml-loader
[hbs-npm]: https://img.shields.io/npm/v/handlebars-loader.svg
[hbs-size]: https://packagephobia.com/badge?p=handlebars-loader
#### Styling
| Name | Status | Install Size | Description |
| :-------------------------------------------------------------------------------------------------------------------------------------------: | :------------: | :-------------: | :----------------------------------------------------------------------- |
| <a href="https://github.com/webpack-contrib/style-loader">`<style>`</a> | ![style-npm] | ![style-size] | Add exports of a module as style to DOM |
| <a href="https://github.com/webpack-contrib/css-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/css-3.svg"></a> | ![css-npm] | ![css-size] | Loads CSS file with resolved imports and returns CSS code |
| <a href="https://github.com/webpack-contrib/less-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/less-63.svg"></a> | ![less-npm] | ![less-size] | Loads and compiles a LESS file |
| <a href="https://github.com/webpack-contrib/sass-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/sass-1.svg"></a> | ![sass-npm] | ![sass-size] | Loads and compiles a Sass/SCSS file |
| <a href="https://github.com/shama/stylus-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/stylus.svg"></a> | ![stylus-npm] | ![stylus-size] | Loads and compiles a Stylus file |
| <a href="https://github.com/postcss/postcss-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/postcss.svg"></a> | ![postcss-npm] | ![postcss-size] | Loads and transforms a CSS/SSS file using [PostCSS](https://postcss.org) |
[style-npm]: https://img.shields.io/npm/v/style-loader.svg
[style-size]: https://packagephobia.com/badge?p=style-loader
[css-npm]: https://img.shields.io/npm/v/css-loader.svg
[css-size]: https://packagephobia.com/badge?p=css-loader
[less-npm]: https://img.shields.io/npm/v/less-loader.svg
[less-size]: https://packagephobia.com/badge?p=less-loader
[sass-npm]: https://img.shields.io/npm/v/sass-loader.svg
[sass-size]: https://packagephobia.com/badge?p=sass-loader
[stylus-npm]: https://img.shields.io/npm/v/stylus-loader.svg
[stylus-size]: https://packagephobia.com/badge?p=stylus-loader
[postcss-npm]: https://img.shields.io/npm/v/postcss-loader.svg
[postcss-size]: https://packagephobia.com/badge?p=postcss-loader
#### Frameworks
| Name | Status | Install Size | Description |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------: | :------------: | :-------------: | :----------------------------------------------------------------------------------------------------- |
| <a href="https://github.com/vuejs/vue-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/vue-9.svg"></a> | ![vue-npm] | ![vue-size] | Loads and compiles Vue Components |
| <a href="https://github.com/webpack-contrib/polymer-webpack-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/polymer.svg"></a> | ![polymer-npm] | ![polymer-size] | Process HTML & CSS with preprocessor of choice and `require()` Web Components like first-class modules |
| <a href="https://github.com/TheLarkInn/angular2-template-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/angular-icon-1.svg"></a> | ![angular-npm] | ![angular-size] | Loads and compiles Angular 2 Components |
| <a href="https://github.com/riot/webpack-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/riot.svg"></a> | ![riot-npm] | ![riot-size] | Riot official webpack loader |
| <a href="https://github.com/sveltejs/svelte-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/svelte-1.svg"></a> | ![svelte-npm] | ![svelte-size] | Official Svelte loader |
[vue-npm]: https://img.shields.io/npm/v/vue-loader.svg
[vue-size]: https://packagephobia.com/badge?p=vue-loader
[polymer-npm]: https://img.shields.io/npm/v/polymer-webpack-loader.svg
[polymer-size]: https://packagephobia.com/badge?p=polymer-webpack-loader
[angular-npm]: https://img.shields.io/npm/v/angular2-template-loader.svg
[angular-size]: https://packagephobia.com/badge?p=angular2-template-loader
[riot-npm]: https://img.shields.io/npm/v/riot-tag-loader.svg
[riot-size]: https://packagephobia.com/badge?p=riot-tag-loader
[svelte-npm]: https://img.shields.io/npm/v/svelte-loader.svg
[svelte-size]: https://packagephobia.com/badge?p=svelte-loader
### Performance
Webpack uses async I/O and has multiple caching levels. This makes webpack fast
and incredibly **fast** on incremental compilations.
### Module Formats
Webpack supports ES2015+, CommonJS and AMD modules **out of the box**. It performs clever static
analysis on the AST of your code. It even has an evaluation engine to evaluate
simple expressions. This allows you to **support most existing libraries** out of the box.
### [Code Splitting](https://webpack.js.org/guides/code-splitting/)
Webpack allows you to split your codebase into multiple chunks. Chunks are
loaded asynchronously at runtime. This reduces the initial loading time.
### [Optimizations](https://webpack.js.org/guides/production-build/)
Webpack can do many optimizations to **reduce the output size of your
JavaScript** by deduplicating frequently used modules, minifying, and giving
you full control of what is loaded initially and what is loaded at runtime
through code splitting. It can also make your code chunks **cache
friendly** by using hashes.
<h2 align="center">Contributing</h2>
**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.
Contributions go far beyond pull requests and commits. Although we love giving you the opportunity to put your stamp on webpack, we also are thrilled to receive a variety of other contributions including:
- [Documentation](https://github.com/webpack/webpack.js.org) updates, enhancements, designs, or bugfixes
- Spelling or grammar fixes
- README.md corrections or redesigns
- Adding unit, or functional tests
- Triaging GitHub issues -- especially determining whether an issue still persists or is reproducible.
- [Searching #webpack on twitter](https://twitter.com/search?q=webpack) and helping someone else who needs help
- Teaching others how to contribute to one of the many webpack's repos!
- [Blogging, speaking about, or creating tutorials](https://github.com/webpack-contrib/awesome-webpack) about one of webpack's many features.
- Helping others in our webpack [gitter channel](https://gitter.im/webpack/webpack).
To get started have a look at our [documentation on contributing](https://github.com/webpack/webpack/blob/main/CONTRIBUTING.md).
If you are worried or don't know where to start, you can **always** reach out to [Sean Larkin (@TheLarkInn) on Twitter](https://twitter.com/thelarkinn) or simply submit an issue and a maintainer can help give you guidance!
We have also started a series on our [Medium Publication](https://medium.com/webpack) called [The Contributor's Guide to webpack](https://medium.com/webpack/contributors-guide/home). We welcome you to read it and post any questions or responses if you still need help.
_Looking to speak about webpack?_ We'd **love** to review your talk abstract/CFP! You can email it to webpack [at] opencollective [dot] com and we can give pointers or tips!!!
<h3 align="center">Creating your own plugins and loaders</h3>
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 align="center">Support</h2>
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!
If you're just getting started, take a look at [our new docs and concepts page](https://webpack.js.org/concepts/). This has a high level overview that is great for beginners!!
Looking for webpack 1 docs? Please check out the old [wiki](https://github.com/webpack/docs/wiki/contents), but note that this deprecated version is no longer supported.
If you want to discuss something or just need help, [here is our Gitter room](https://gitter.im/webpack/webpack) where there are always individuals looking to help out!
If you are still having difficulty, we would love for you to post
a question to [StackOverflow with the webpack tag](https://stackoverflow.com/tags/webpack). It is much easier to answer questions that include your webpack.config.js and relevant files! So if you can provide them, we'd be extremely grateful (and more likely to help you find the answer!)
If you are twitter savvy you can tweet #webpack with your question and someone should be able to reach out and help also.
If you have discovered a 🐜 or have a feature suggestion, feel free to create an issue on GitHub.
### License
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack?ref=badge_large)
<h2 align="center">Core Team</h2>
<table>
<tbody>
<tr>
<td align="center" valign="top">
<img width="150" height="150" src="https://github.com/sokra.png?s=150">
<br>
<a href="https://github.com/sokra">Tobias Koppers</a>
<p>Core</p>
<br>
<p>Founder of webpack</p>
</td>
<td align="center" valign="top">
<img width="150" height="150" src="https://github.com/jhnns.png?s=150">
<br>
<a href="https://github.com/jhnns">Johannes Ewald</a>
<p>Loaders &amp; Plugins</p>
<br>
<p>Early adopter of webpack</p>
</td>
<td align="center" width="20%" valign="top">
<img width="150" height="150" src="https://github.com/TheLarkInn.png?s=150">
<br>
<a href="https://github.com/TheLarkInn">Sean T. Larkin</a>
<p>Public Relations</p>
<br>
<p>Founder of the core team</p>
</td>
<td align="center" valign="top">
<img width="150" height="150" src="https://github.com/spacek33z.png?s=150">
<br>
<a href="https://github.com/spacek33z">Kees Kluskens</a>
<p>Development</p>
<br>
<p>Sponsor</p>
<a href="https://codeyellow.nl/">
<img height="15px" src="https://cloud.githubusercontent.com/assets/1365881/20286583/ad62eb04-aac7-11e6-9c14-a0fef35b9b56.png">
</a>
<br>
</td>
</tr>
</tbody>
</table>
<h2 align="center">Sponsoring</h2>
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.
This is how we use the donations:
- Allow the core team to work on webpack
- Thank contributors if they invested a large amount of time in contributing
- Support projects in the ecosystem that are of great value for users
- Support projects that are voted most (work in progress)
- Infrastructure cost
- Fees for money handling
<h2 align="center">Premium Partners</h2>
<div align="center">
<a href="https://www.ag-grid.com/?utm_source=webpack&utm_medium=banner&utm_campaign=sponsorship" target="_blank"><img align="center" src="https://raw.githubusercontent.com/webpack/media/2b399d58/horiz-banner-ad-ag-grid.png">
</a>
</div>
<h2 align="center">Other Backers and Sponsors</h2>
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.
<div align="center">
<a href="https://angular.io/" target="_blank" title="JS framework"><img
src="https://cdn.worldvectorlogo.com/logos/angular-icon-1.svg" height="30" alt="Angular"></a>
<a href="https://moonmail.io" target="_blank" title="Email Marketing Software"><img
src="https://static.moonmail.io/moonmail-logo.svg" height="30" alt="MoonMail"></a>
<a href="https://monei.net" target="_blank" title="Best payment gateway rates"><img
src="https://static.monei.net/monei-logo.svg" height="30" alt="MONEI"></a>
</div>
<h2 align="center">Gold Sponsors</h2>
[Become a gold sponsor](https://opencollective.com/webpack#sponsor) and get your logo on our README on GitHub with a link to your site.
<div align="center">
<a href="https://opencollective.com/webpack/goldsponsor/0/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/0/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/1/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/1/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/2/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/2/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/3/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/3/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/4/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/4/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/5/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/5/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/6/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/6/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/7/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/7/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/8/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/8/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/9/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/9/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/10/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/10/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/11/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/11/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/12/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/12/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/13/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/13/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/14/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/14/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/15/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/15/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/16/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/16/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/17/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/17/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/18/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/18/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/19/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/19/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/20/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/20/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/21/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/21/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/22/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/22/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/23/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/23/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/24/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/24/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/25/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/25/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/26/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/26/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/27/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/27/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/28/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/28/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/goldsponsor/29/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/29/avatar.svg?requireActive=false"></a>
</div>
<h2 align="center">Silver Sponsors</h2>
[Become a silver sponsor](https://opencollective.com/webpack#sponsor) and get your logo on our README on GitHub with a link to your site.
<div align="center">
<a href="https://opencollective.com/webpack/silversponsor/0/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/0/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/1/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/1/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/2/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/2/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/3/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/3/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/4/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/4/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/5/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/5/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/6/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/6/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/7/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/7/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/8/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/8/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/9/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/9/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/10/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/10/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/11/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/11/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/12/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/12/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/13/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/13/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/14/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/14/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/15/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/15/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/16/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/16/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/17/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/17/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/18/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/18/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/19/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/19/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/20/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/20/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/21/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/21/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/22/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/22/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/23/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/23/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/24/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/24/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/25/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/25/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/26/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/26/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/27/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/27/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/28/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/28/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/silversponsor/29/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/29/avatar.svg?requireActive=false"></a>
</div>
<h2 align="center">Bronze Sponsors</h2>
[Become a bronze sponsor](https://opencollective.com/webpack#sponsor) and get your logo on our README on GitHub with a link to your site.
<div align="center">
<a href="https://opencollective.com/webpack/sponsor/0/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/0/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/1/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/1/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/2/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/2/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/3/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/3/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/4/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/4/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/5/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/5/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/6/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/6/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/7/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/7/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/8/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/8/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/9/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/9/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/10/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/10/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/11/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/11/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/12/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/12/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/13/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/13/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/14/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/14/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/15/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/15/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/16/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/16/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/17/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/17/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/18/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/18/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/19/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/19/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/20/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/20/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/21/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/21/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/22/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/22/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/23/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/23/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/24/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/24/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/25/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/25/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/26/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/26/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/27/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/27/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/28/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/28/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/29/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/29/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/30/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/30/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/31/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/31/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/32/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/32/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/33/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/33/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/34/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/34/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/35/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/35/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/36/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/36/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/37/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/37/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/38/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/38/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/39/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/39/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/40/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/40/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/41/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/41/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/42/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/42/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/43/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/43/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/44/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/44/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/45/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/45/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/46/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/46/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/47/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/47/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/48/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/48/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/49/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/49/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/50/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/50/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/51/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/51/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/52/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/52/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/53/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/53/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/54/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/54/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/55/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/55/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/56/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/56/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/57/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/57/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/58/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/58/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/59/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/59/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/60/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/60/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/61/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/61/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/62/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/62/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/63/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/63/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/64/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/64/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/65/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/65/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/66/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/66/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/67/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/67/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/68/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/68/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/69/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/69/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/70/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/70/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/71/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/71/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/72/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/72/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/73/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/73/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/74/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/74/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/75/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/75/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/76/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/76/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/77/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/77/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/78/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/78/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/79/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/79/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/80/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/80/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/81/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/81/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/82/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/82/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/83/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/83/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/84/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/84/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/85/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/85/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/86/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/86/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/87/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/87/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/88/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/88/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/89/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/89/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/90/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/90/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/91/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/91/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/92/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/92/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/93/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/93/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/94/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/94/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/95/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/95/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/96/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/96/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/97/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/97/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/98/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/98/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/99/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/99/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/sponsor/100/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/100/avatar.svg?requireActive=false"></a>
</div>
<h2 align="center">Backers</h2>
[Become a backer](https://opencollective.com/webpack#backer) and get your image on our README on GitHub with a link to your site.
<a href="https://opencollective.com/webpack/backer/0/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/0/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/1/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/1/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/2/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/2/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/3/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/3/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/4/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/4/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/5/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/5/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/6/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/6/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/7/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/7/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/8/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/8/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/9/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/9/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/10/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/10/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/11/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/11/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/12/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/12/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/13/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/13/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/14/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/14/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/15/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/15/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/16/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/16/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/17/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/17/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/18/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/18/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/19/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/19/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/20/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/20/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/21/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/21/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/22/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/22/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/23/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/23/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/24/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/24/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/25/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/25/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/26/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/26/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/27/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/27/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/28/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/28/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/29/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/29/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/30/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/30/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/31/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/31/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/32/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/32/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/33/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/33/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/34/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/34/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/35/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/35/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/36/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/36/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/37/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/37/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/38/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/38/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/39/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/39/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/40/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/40/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/41/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/41/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/42/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/42/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/43/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/43/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/44/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/44/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/45/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/45/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/46/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/46/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/47/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/47/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/48/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/48/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/49/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/49/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/50/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/50/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/51/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/51/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/52/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/52/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/53/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/53/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/54/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/54/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/55/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/55/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/56/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/56/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/57/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/57/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/58/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/58/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/59/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/59/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/60/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/60/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/61/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/61/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/62/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/62/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/63/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/63/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/64/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/64/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/65/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/65/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/66/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/66/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/67/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/67/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/68/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/68/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/69/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/69/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/70/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/70/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/71/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/71/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/72/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/72/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/73/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/73/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/74/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/74/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/75/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/75/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/76/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/76/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/77/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/77/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/78/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/78/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/79/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/79/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/80/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/80/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/81/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/81/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/82/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/82/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/83/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/83/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/84/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/84/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/85/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/85/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/86/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/86/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/87/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/87/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/88/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/88/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/89/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/89/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/90/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/90/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/91/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/91/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/92/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/92/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/93/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/93/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/94/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/94/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/95/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/95/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/96/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/96/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/97/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/97/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/98/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/98/avatar.svg?requireActive=false"></a>
<a href="https://opencollective.com/webpack/backer/99/website?requireActive=false" target="_blank"><img 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 src="https://opencollective.com/webpack/backer/100/avatar.svg?requireActive=false"></a>
<h2 align="center">Special Thanks to</h2>
<p align="center">(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.
- [@medikoo](https://github.com/medikoo) for [modules-webmake](https://github.com/medikoo/modules-webmake), which is a similar project. webpack was born because I wanted Code Splitting for modules-webmake. Interestingly the [Code Splitting issue is still open](https://github.com/medikoo/modules-webmake/issues/7) (thanks also to @Phoscur for the discussion).
- [@substack](https://github.com/substack) for [browserify](https://browserify.org/), which is a similar project and source for many ideas.
- [@jrburke](https://github.com/jrburke) for [require.js](https://requirejs.org/), which is a similar project and source for many ideas.
- [@defunctzombie](https://github.com/defunctzombie) for the [browser-field spec](https://github.com/defunctzombie/package-browser-field-spec), which makes modules available for node.js, browserify and webpack.
- Every early webpack user, which contributed to webpack by writing issues or PRs. You influenced the direction...
- [@shama](https://github.com/shama), [@jhnns](https://github.com/jhnns) and [@sokra](https://github.com/sokra) for maintaining this project
- Everyone who has written a loader for webpack. You are the ecosystem...
- Everyone I forgot to mention here, but also influenced webpack.
[npm]: https://img.shields.io/npm/v/webpack.svg
[npm-url]: https://npmjs.com/package/webpack
[node]: https://img.shields.io/node/v/webpack.svg
[node-url]: https://nodejs.org
[prs]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg
[prs-url]: https://webpack.js.org/contribute/
[builds1]: https://github.com/webpack/webpack/actions/workflows/test.yml/badge.svg
[builds1-url]: https://github.com/webpack/webpack/actions/workflows/test.yml
[builds2]: https://dev.azure.com/webpack/webpack/_apis/build/status%2Fwebpack.webpack?branchName=main
[builds2-url]: https://dev.azure.com/webpack/webpack/_build/latest?definitionId=3&branchName=main
[dependency-review-url]: https://github.com/webpack/webpack/actions/workflows/dependency-review.yml
[dependency-review]: https://github.com/webpack/webpack/actions/workflows/dependency-review.yml/badge.svg
[cover]: https://codecov.io/gh/webpack/webpack/branch/master/graph/badge.svg?token=mDP3mQJNnn
[cover-url]: https://codecov.io/gh/webpack/webpack

9
node_modules/webpack/SECURITY.md generated vendored Normal file
View file

@ -0,0 +1,9 @@
# 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.

187
node_modules/webpack/bin/webpack.js generated vendored Executable file
View file

@ -0,0 +1,187 @@
#!/usr/bin/env node
/**
* @param {string} command process to run
* @param {string[]} args command line arguments
* @returns {Promise<void>} promise
*/
const runCommand = (command, args) => {
const cp = require("child_process");
return new Promise((resolve, reject) => {
const executedCommand = cp.spawn(command, args, {
stdio: "inherit",
shell: true
});
executedCommand.on("error", error => {
reject(error);
});
executedCommand.on("exit", code => {
if (code === 0) {
resolve();
} else {
reject();
}
});
});
};
/**
* @param {string} packageName name of the package
* @returns {boolean} is the package installed?
*/
const isInstalled = packageName => {
if (process.versions.pnp) {
return true;
}
const path = require("path");
const fs = require("graceful-fs");
let dir = __dirname;
do {
try {
if (
fs.statSync(path.join(dir, "node_modules", packageName)).isDirectory()
) {
return true;
}
} catch (_error) {
// Nothing
}
} while (dir !== (dir = path.dirname(dir)));
// https://github.com/nodejs/node/blob/v18.9.1/lib/internal/modules/cjs/loader.js#L1274
// eslint-disable-next-line no-warning-comments
// @ts-ignore
for (const internalPath of require("module").globalPaths) {
try {
if (fs.statSync(path.join(internalPath, packageName)).isDirectory()) {
return true;
}
} catch (_error) {
// Nothing
}
}
return false;
};
/**
* @param {CliOption} cli options
* @returns {void}
*/
const runCli = cli => {
const path = require("path");
const pkgPath = require.resolve(`${cli.package}/package.json`);
const pkg = require(pkgPath);
if (pkg.type === "module" || /\.mjs/i.test(pkg.bin[cli.binName])) {
import(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName])).catch(
err => {
console.error(err);
process.exitCode = 1;
}
);
} else {
require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
}
};
/**
* @typedef {object} CliOption
* @property {string} name display name
* @property {string} package npm package name
* @property {string} binName name of the executable file
* @property {boolean} installed currently installed?
* @property {string} url homepage
*/
/** @type {CliOption} */
const cli = {
name: "webpack-cli",
package: "webpack-cli",
binName: "webpack-cli",
installed: isInstalled("webpack-cli"),
url: "https://github.com/webpack/webpack-cli"
};
if (!cli.installed) {
const path = require("path");
const fs = require("graceful-fs");
const readLine = require("readline");
const notify = `CLI for webpack must be installed.\n ${cli.name} (${cli.url})\n`;
console.error(notify);
/** @type {string | undefined} */
let packageManager;
if (fs.existsSync(path.resolve(process.cwd(), "yarn.lock"))) {
packageManager = "yarn";
} else if (fs.existsSync(path.resolve(process.cwd(), "pnpm-lock.yaml"))) {
packageManager = "pnpm";
} else {
packageManager = "npm";
}
const installOptions = [packageManager === "yarn" ? "add" : "install", "-D"];
console.error(
`We will use "${packageManager}" to install the CLI via "${packageManager} ${installOptions.join(
" "
)} ${cli.package}".`
);
const question = "Do you want to install 'webpack-cli' (yes/no): ";
const questionInterface = readLine.createInterface({
input: process.stdin,
output: process.stderr
});
// In certain scenarios (e.g. when STDIN is not in terminal mode), the callback function will not be
// executed. Setting the exit code here to ensure the script exits correctly in those cases. The callback
// function is responsible for clearing the exit code if the user wishes to install webpack-cli.
process.exitCode = 1;
questionInterface.question(question, answer => {
questionInterface.close();
const normalizedAnswer = answer.toLowerCase().startsWith("y");
if (!normalizedAnswer) {
console.error(
"You need to install 'webpack-cli' to use webpack via CLI.\n" +
"You can also install the CLI manually."
);
return;
}
process.exitCode = 0;
console.log(
`Installing '${
cli.package
}' (running '${packageManager} ${installOptions.join(" ")} ${
cli.package
}')...`
);
runCommand(
/** @type {string} */ (packageManager),
installOptions.concat(cli.package)
)
.then(() => {
runCli(cli);
})
.catch(err => {
console.error(err);
process.exitCode = 1;
});
});
} else {
runCli(cli);
}

75
node_modules/webpack/hot/dev-server.js generated vendored Normal file
View file

@ -0,0 +1,75 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
/* globals __webpack_hash__ */
if (module.hot) {
/** @type {undefined|string} */
var lastHash;
var upToDate = function upToDate() {
return /** @type {string} */ (lastHash).indexOf(__webpack_hash__) >= 0;
};
var log = require("./log");
var check = function check() {
module.hot
.check(true)
.then(function (updatedModules) {
if (!updatedModules) {
log(
"warning",
"[HMR] Cannot find update. " +
(typeof window !== "undefined"
? "Need to do a full reload!"
: "Please reload manually!")
);
log(
"warning",
"[HMR] (Probably because of restarting the webpack-dev-server)"
);
if (typeof window !== "undefined") {
window.location.reload();
}
return;
}
if (!upToDate()) {
check();
}
require("./log-apply-result")(updatedModules, updatedModules);
if (upToDate()) {
log("info", "[HMR] App is up to date.");
}
})
.catch(function (err) {
var status = module.hot.status();
if (["abort", "fail"].indexOf(status) >= 0) {
log(
"warning",
"[HMR] Cannot apply update. " +
(typeof window !== "undefined"
? "Need to do a full reload!"
: "Please reload manually!")
);
log("warning", "[HMR] " + log.formatError(err));
if (typeof window !== "undefined") {
window.location.reload();
}
} else {
log("warning", "[HMR] Update failed: " + log.formatError(err));
}
});
};
var hotEmitter = require("./emitter");
hotEmitter.on("webpackHotUpdate", function (currentHash) {
lastHash = currentHash;
if (!upToDate() && module.hot.status() === "idle") {
log("info", "[HMR] Checking for updates on the server...");
check();
}
});
log("info", "[HMR] Waiting for update signal from WDS...");
} else {
throw new Error("[HMR] Hot Module Replacement is disabled.");
}

2
node_modules/webpack/hot/emitter.js generated vendored Normal file
View file

@ -0,0 +1,2 @@
var EventEmitter = require("events");
module.exports = new EventEmitter();

49
node_modules/webpack/hot/log-apply-result.js generated vendored Normal file
View file

@ -0,0 +1,49 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
/**
* @param {(string | number)[]} updatedModules updated modules
* @param {(string | number)[] | null} renewedModules renewed modules
*/
module.exports = function (updatedModules, renewedModules) {
var unacceptedModules = updatedModules.filter(function (moduleId) {
return renewedModules && renewedModules.indexOf(moduleId) < 0;
});
var log = require("./log");
if (unacceptedModules.length > 0) {
log(
"warning",
"[HMR] The following modules couldn't be hot updated: (They would need a full reload!)"
);
unacceptedModules.forEach(function (moduleId) {
log("warning", "[HMR] - " + moduleId);
});
}
if (!renewedModules || renewedModules.length === 0) {
log("info", "[HMR] Nothing hot updated.");
} else {
log("info", "[HMR] Updated modules:");
renewedModules.forEach(function (moduleId) {
if (typeof moduleId === "string" && moduleId.indexOf("!") !== -1) {
var parts = moduleId.split("!");
log.groupCollapsed("info", "[HMR] - " + parts.pop());
log("info", "[HMR] - " + moduleId);
log.groupEnd("info");
} else {
log("info", "[HMR] - " + moduleId);
}
});
var numberIds = renewedModules.every(function (moduleId) {
return typeof moduleId === "number";
});
if (numberIds)
log(
"info",
'[HMR] Consider using the optimization.moduleIds: "named" for module names.'
);
}
};

78
node_modules/webpack/hot/log.js generated vendored Normal file
View file

@ -0,0 +1,78 @@
/** @typedef {"info" | "warning" | "error"} LogLevel */
/** @type {LogLevel} */
var logLevel = "info";
function dummy() {}
/**
* @param {LogLevel} level log level
* @returns {boolean} true, if should log
*/
function shouldLog(level) {
var shouldLog =
(logLevel === "info" && level === "info") ||
(["info", "warning"].indexOf(logLevel) >= 0 && level === "warning") ||
(["info", "warning", "error"].indexOf(logLevel) >= 0 && level === "error");
return shouldLog;
}
/**
* @param {(msg?: string) => void} logFn log function
* @returns {(level: LogLevel, msg?: string) => void} function that logs when log level is sufficient
*/
function logGroup(logFn) {
return function (level, msg) {
if (shouldLog(level)) {
logFn(msg);
}
};
}
/**
* @param {LogLevel} level log level
* @param {string|Error} msg message
*/
module.exports = function (level, msg) {
if (shouldLog(level)) {
if (level === "info") {
console.log(msg);
} else if (level === "warning") {
console.warn(msg);
} else if (level === "error") {
console.error(msg);
}
}
};
var group = console.group || dummy;
var groupCollapsed = console.groupCollapsed || dummy;
var groupEnd = console.groupEnd || dummy;
module.exports.group = logGroup(group);
module.exports.groupCollapsed = logGroup(groupCollapsed);
module.exports.groupEnd = logGroup(groupEnd);
/**
* @param {LogLevel} level log level
*/
module.exports.setLogLevel = function (level) {
logLevel = level;
};
/**
* @param {Error} err error
* @returns {string} formatted error
*/
module.exports.formatError = function (err) {
var message = err.message;
var stack = err.stack;
if (!stack) {
return message;
} else if (stack.indexOf(message) < 0) {
return message + "\n" + stack;
}
return stack;
};

103
node_modules/webpack/hot/only-dev-server.js generated vendored Normal file
View file

@ -0,0 +1,103 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
/* globals __webpack_hash__ */
if (module.hot) {
/** @type {undefined|string} */
var lastHash;
var upToDate = function upToDate() {
return /** @type {string} */ (lastHash).indexOf(__webpack_hash__) >= 0;
};
var log = require("./log");
var check = function check() {
module.hot
.check()
.then(function (updatedModules) {
if (!updatedModules) {
log("warning", "[HMR] Cannot find update. Need to do a full reload!");
log(
"warning",
"[HMR] (Probably because of restarting the webpack-dev-server)"
);
return;
}
return module.hot
.apply({
ignoreUnaccepted: true,
ignoreDeclined: true,
ignoreErrored: true,
onUnaccepted: function (data) {
log(
"warning",
"Ignored an update to unaccepted module " +
data.chain.join(" -> ")
);
},
onDeclined: function (data) {
log(
"warning",
"Ignored an update to declined module " +
data.chain.join(" -> ")
);
},
onErrored: function (data) {
log("error", data.error);
log(
"warning",
"Ignored an error while updating module " +
data.moduleId +
" (" +
data.type +
")"
);
}
})
.then(function (renewedModules) {
if (!upToDate()) {
check();
}
require("./log-apply-result")(updatedModules, renewedModules);
if (upToDate()) {
log("info", "[HMR] App is up to date.");
}
});
})
.catch(function (err) {
var status = module.hot.status();
if (["abort", "fail"].indexOf(status) >= 0) {
log(
"warning",
"[HMR] Cannot check for update. Need to do a full reload!"
);
log("warning", "[HMR] " + log.formatError(err));
} else {
log("warning", "[HMR] Update check failed: " + log.formatError(err));
}
});
};
var hotEmitter = require("./emitter");
hotEmitter.on("webpackHotUpdate", function (currentHash) {
lastHash = currentHash;
if (!upToDate()) {
var status = module.hot.status();
if (status === "idle") {
log("info", "[HMR] Checking for updates on the server...");
check();
} else if (["abort", "fail"].indexOf(status) >= 0) {
log(
"warning",
"[HMR] Cannot apply update as a previous update " +
status +
"ed. Need to do a full reload!"
);
}
}
});
log("info", "[HMR] Waiting for update signal from WDS...");
} else {
throw new Error("[HMR] Hot Module Replacement is disabled.");
}

40
node_modules/webpack/hot/poll.js generated vendored Normal file
View file

@ -0,0 +1,40 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
/* globals __resourceQuery */
if (module.hot) {
var hotPollInterval = +__resourceQuery.slice(1) || 10 * 60 * 1000;
var log = require("./log");
/**
* @param {boolean=} fromUpdate true when called from update
*/
var checkForUpdate = function checkForUpdate(fromUpdate) {
if (module.hot.status() === "idle") {
module.hot
.check(true)
.then(function (updatedModules) {
if (!updatedModules) {
if (fromUpdate) log("info", "[HMR] Update applied.");
return;
}
require("./log-apply-result")(updatedModules, updatedModules);
checkForUpdate(true);
})
.catch(function (err) {
var status = module.hot.status();
if (["abort", "fail"].indexOf(status) >= 0) {
log("warning", "[HMR] Cannot apply update.");
log("warning", "[HMR] " + log.formatError(err));
log("warning", "[HMR] You need to restart the application!");
} else {
log("warning", "[HMR] Update failed: " + log.formatError(err));
}
});
}
};
setInterval(checkForUpdate, hotPollInterval);
} else {
throw new Error("[HMR] Hot Module Replacement is disabled.");
}

66
node_modules/webpack/hot/signal.js generated vendored Normal file
View file

@ -0,0 +1,66 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
/* globals __resourceQuery */
if (module.hot) {
var log = require("./log");
/**
* @param {boolean=} fromUpdate true when called from update
*/
var checkForUpdate = function checkForUpdate(fromUpdate) {
module.hot
.check()
.then(function (updatedModules) {
if (!updatedModules) {
if (fromUpdate) log("info", "[HMR] Update applied.");
else log("warning", "[HMR] Cannot find update.");
return;
}
return module.hot
.apply({
ignoreUnaccepted: true,
onUnaccepted: function (data) {
log(
"warning",
"Ignored an update to unaccepted module " +
data.chain.join(" -> ")
);
}
})
.then(function (renewedModules) {
require("./log-apply-result")(updatedModules, renewedModules);
checkForUpdate(true);
return null;
});
})
.catch(function (err) {
var status = module.hot.status();
if (["abort", "fail"].indexOf(status) >= 0) {
log("warning", "[HMR] Cannot apply update.");
log("warning", "[HMR] " + log.formatError(err));
log("warning", "[HMR] You need to restart the application!");
} else {
log("warning", "[HMR] Update failed: " + (err.stack || err.message));
}
});
};
process.on(__resourceQuery.slice(1) || "SIGUSR2", function () {
if (module.hot.status() !== "idle") {
log(
"warning",
"[HMR] Got signal but currently in " + module.hot.status() + " state."
);
log("warning", "[HMR] Need to be in idle state to start hot update.");
return;
}
checkForUpdate();
});
} else {
throw new Error("[HMR] Hot Module Replacement is disabled.");
}

324
node_modules/webpack/lib/APIPlugin.js generated vendored Normal file
View file

@ -0,0 +1,324 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const InitFragment = require("./InitFragment");
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const WebpackError = require("./WebpackError");
const ConstDependency = require("./dependencies/ConstDependency");
const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
const {
toConstantDependency,
evaluateToString
} = require("./javascript/JavascriptParserHelpers");
const ChunkNameRuntimeModule = require("./runtime/ChunkNameRuntimeModule");
const GetFullHashRuntimeModule = require("./runtime/GetFullHashRuntimeModule");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @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) {
return {
__webpack_require__: {
expr: RuntimeGlobals.require,
req: [RuntimeGlobals.require],
type: "function",
assign: false
},
__webpack_public_path__: {
expr: RuntimeGlobals.publicPath,
req: [RuntimeGlobals.publicPath],
type: "string",
assign: true
},
__webpack_base_uri__: {
expr: RuntimeGlobals.baseURI,
req: [RuntimeGlobals.baseURI],
type: "string",
assign: true
},
__webpack_modules__: {
expr: RuntimeGlobals.moduleFactories,
req: [RuntimeGlobals.moduleFactories],
type: "object",
assign: false
},
__webpack_chunk_load__: {
expr: RuntimeGlobals.ensureChunk,
req: [RuntimeGlobals.ensureChunk],
type: "function",
assign: true
},
__non_webpack_require__: {
expr: module
? `__WEBPACK_EXTERNAL_createRequire(${importMetaName}.url)`
: "require",
req: null,
type: undefined, // type is not known, depends on environment
assign: true
},
__webpack_nonce__: {
expr: RuntimeGlobals.scriptNonce,
req: [RuntimeGlobals.scriptNonce],
type: "string",
assign: true
},
__webpack_hash__: {
expr: `${RuntimeGlobals.getFullHash}()`,
req: [RuntimeGlobals.getFullHash],
type: "string",
assign: false
},
__webpack_chunkname__: {
expr: RuntimeGlobals.chunkName,
req: [RuntimeGlobals.chunkName],
type: "string",
assign: false
},
__webpack_get_script_filename__: {
expr: RuntimeGlobals.getChunkScriptFilename,
req: [RuntimeGlobals.getChunkScriptFilename],
type: "function",
assign: true
},
__webpack_runtime_id__: {
expr: RuntimeGlobals.runtimeId,
req: [RuntimeGlobals.runtimeId],
assign: false
},
"require.onError": {
expr: RuntimeGlobals.uncaughtErrorHandler,
req: [RuntimeGlobals.uncaughtErrorHandler],
type: undefined, // type is not known, could be function or undefined
assign: true // is never a pattern
},
__system_context__: {
expr: RuntimeGlobals.systemContext,
req: [RuntimeGlobals.systemContext],
type: "object",
assign: false
},
__webpack_share_scopes__: {
expr: RuntimeGlobals.shareScopeMap,
req: [RuntimeGlobals.shareScopeMap],
type: "object",
assign: false
},
__webpack_init_sharing__: {
expr: RuntimeGlobals.initializeSharing,
req: [RuntimeGlobals.initializeSharing],
type: "function",
assign: true
}
};
}
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
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
const importMetaName = /** @type {string} */ (
compilation.outputOptions.importMetaName
);
const REPLACEMENTS = getReplacements(
this.options.module,
importMetaName
);
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.chunkName)
.tap(PLUGIN_NAME, chunk => {
compilation.addRuntimeModule(
chunk,
new ChunkNameRuntimeModule(/** @type {string} */ (chunk.name))
);
return true;
});
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.getFullHash)
.tap(PLUGIN_NAME, (chunk, set) => {
compilation.addRuntimeModule(chunk, new GetFullHashRuntimeModule());
return true;
});
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
hooks.renderModuleContent.tap(
PLUGIN_NAME,
(source, module, renderContext) => {
if (/** @type {BuildInfo} */ (module.buildInfo).needCreateRequire) {
const needPrefix =
renderContext.runtimeTemplate.supportNodePrefixForCoreModules();
const chunkInitFragments = [
new InitFragment(
`import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "${
needPrefix ? "node:" : ""
}module";\n`,
InitFragment.STAGE_HARMONY_IMPORTS,
0,
"external module node-commonjs"
)
];
renderContext.chunkInitFragments.push(...chunkInitFragments);
}
return source;
}
);
/**
* @param {JavascriptParser} parser the parser
*/
const handler = parser => {
for (const key of Object.keys(REPLACEMENTS)) {
const info = REPLACEMENTS[key];
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;
}
return dep(expression);
});
if (info.assign === false) {
parser.hooks.assign.for(key).tap(PLUGIN_NAME, expr => {
const err = new WebpackError(`${key} must not be assigned`);
err.loc = /** @type {DependencyLocation} */ (expr.loc);
throw err;
});
}
if (info.type) {
parser.hooks.evaluateTypeof
.for(key)
.tap(PLUGIN_NAME, evaluateToString(info.type));
}
}
parser.hooks.expression
.for("__webpack_layer__")
.tap(PLUGIN_NAME, expr => {
const dep = new ConstDependency(
JSON.stringify(parser.state.module.layer),
/** @type {Range} */ (expr.range)
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
parser.hooks.evaluateIdentifier
.for("__webpack_layer__")
.tap(PLUGIN_NAME, expr =>
(parser.state.module.layer === null
? new BasicEvaluatedExpression().setNull()
: new BasicEvaluatedExpression().setString(
parser.state.module.layer
)
).setRange(/** @type {Range} */ (expr.range))
);
parser.hooks.evaluateTypeof
.for("__webpack_layer__")
.tap(PLUGIN_NAME, expr =>
new BasicEvaluatedExpression()
.setString(
parser.state.module.layer === null ? "object" : "string"
)
.setRange(/** @type {Range} */ (expr.range))
);
parser.hooks.expression
.for("__webpack_module__.id")
.tap(PLUGIN_NAME, expr => {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).moduleConcatenationBailout =
"__webpack_module__.id";
const dep = new ConstDependency(
`${parser.state.module.moduleArgument}.id`,
/** @type {Range} */ (expr.range),
[RuntimeGlobals.moduleId]
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
parser.hooks.expression
.for("__webpack_module__")
.tap(PLUGIN_NAME, expr => {
/** @type {BuildInfo} */
(parser.state.module.buildInfo).moduleConcatenationBailout =
"__webpack_module__";
const dep = new ConstDependency(
parser.state.module.moduleArgument,
/** @type {Range} */ (expr.range),
[RuntimeGlobals.module]
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
parser.hooks.evaluateTypeof
.for("__webpack_module__")
.tap(PLUGIN_NAME, evaluateToString("object"));
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
}
);
}
}
module.exports = APIPlugin;

54
node_modules/webpack/lib/AbstractMethodError.js generated vendored Normal file
View file

@ -0,0 +1,54 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Ivan Kopeykin @vankop
*/
"use strict";
const WebpackError = require("./WebpackError");
const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/;
/**
* @param {string=} method method name
* @returns {string} message
*/
function createMessage(method) {
return `Abstract method${method ? ` ${method}` : ""}. Must be overridden.`;
}
/**
* @constructor
*/
function Message() {
/** @type {string | undefined} */
this.stack = undefined;
Error.captureStackTrace(this);
/** @type {RegExpMatchArray | null} */
const match =
/** @type {string} */
(/** @type {unknown} */ (this.stack))
.split("\n")[3]
.match(CURRENT_METHOD_REGEXP);
this.message = match && match[1] ? createMessage(match[1]) : createMessage();
}
/**
* Error for abstract method
* @example
* ```js
* class FooClass {
* abstractMethod() {
* throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overridden.
* }
* }
* ```
*/
class AbstractMethodError extends WebpackError {
constructor() {
super(new Message().message);
this.name = "AbstractMethodError";
}
}
module.exports = AbstractMethodError;

114
node_modules/webpack/lib/AsyncDependenciesBlock.js generated vendored Normal file
View file

@ -0,0 +1,114 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
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 */
class AsyncDependenciesBlock extends DependenciesBlock {
/**
* @param {(ChunkGroupOptions & { entryOptions?: EntryOptions }) | null} groupOptions options for the group
* @param {(DependencyLocation | null)=} loc the line of code
* @param {(string | null)=} request the request
*/
constructor(groupOptions, loc, request) {
super();
if (typeof groupOptions === "string") {
groupOptions = { name: groupOptions };
} else if (!groupOptions) {
groupOptions = { name: undefined };
}
this.groupOptions = groupOptions;
this.loc = loc;
this.request = request;
this._stringifiedGroupOptions = undefined;
}
/**
* @returns {string | undefined} The name of the chunk
*/
get chunkName() {
return this.groupOptions.name;
}
/**
* @param {string | undefined} value The new chunk name
* @returns {void}
*/
set chunkName(value) {
if (this.groupOptions.name !== value) {
this.groupOptions.name = value;
this._stringifiedGroupOptions = undefined;
}
}
/**
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
const { chunkGraph } = context;
if (this._stringifiedGroupOptions === undefined) {
this._stringifiedGroupOptions = JSON.stringify(this.groupOptions);
}
const chunkGroup = chunkGraph.getBlockChunkGroup(this);
hash.update(
`${this._stringifiedGroupOptions}${chunkGroup ? chunkGroup.id : ""}`
);
super.updateHash(hash, context);
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.groupOptions);
write(this.loc);
write(this.request);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
this.groupOptions = read();
this.loc = read();
this.request = read();
super.deserialize(context);
}
}
makeSerializable(AsyncDependenciesBlock, "webpack/lib/AsyncDependenciesBlock");
Object.defineProperty(AsyncDependenciesBlock.prototype, "module", {
get() {
throw new Error(
"module property was removed from AsyncDependenciesBlock (it's not needed)"
);
},
set() {
throw new Error(
"module property was removed from AsyncDependenciesBlock (it's not needed)"
);
}
});
module.exports = AsyncDependenciesBlock;

View file

@ -0,0 +1,31 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sean Larkin @thelarkinn
*/
"use strict";
const WebpackError = require("./WebpackError");
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Module")} Module */
class AsyncDependencyToInitialChunkError extends WebpackError {
/**
* Creates an instance of AsyncDependencyToInitialChunkError.
* @param {string} chunkName Name of Chunk
* @param {Module} module module tied to dependency
* @param {DependencyLocation} loc location of dependency
*/
constructor(chunkName, module, loc) {
super(
`It's not allowed to load an initial chunk on demand. The chunk name "${chunkName}" is already used by an entrypoint.`
);
this.name = "AsyncDependencyToInitialChunkError";
this.module = module;
this.loc = loc;
}
}
module.exports = AsyncDependencyToInitialChunkError;

66
node_modules/webpack/lib/AutomaticPrefetchPlugin.js generated vendored Normal file
View file

@ -0,0 +1,66 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const NormalModule = require("./NormalModule");
const PrefetchDependency = require("./dependencies/PrefetchDependency");
/** @typedef {import("./Compiler")} Compiler */
class AutomaticPrefetchPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
"AutomaticPrefetchPlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
PrefetchDependency,
normalModuleFactory
);
}
);
/** @type {{context: string | null, request: string}[] | null} */
let lastModules = null;
compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => {
lastModules = [];
for (const m of compilation.modules) {
if (m instanceof NormalModule) {
lastModules.push({
context: m.context,
request: m.request
});
}
}
});
compiler.hooks.make.tapAsync(
"AutomaticPrefetchPlugin",
(compilation, callback) => {
if (!lastModules) return callback();
asyncLib.each(
lastModules,
(m, callback) => {
compilation.addModuleChain(
m.context || compiler.context,
new PrefetchDependency(`!!${m.request}`),
callback
);
},
err => {
lastModules = null;
callback(err);
}
);
}
);
}
}
module.exports = AutomaticPrefetchPlugin;

138
node_modules/webpack/lib/BannerPlugin.js generated vendored Normal file
View file

@ -0,0 +1,138 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ConcatSource } = require("webpack-sources");
const Compilation = require("./Compilation");
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const Template = require("./Template");
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 */
const validate = createSchemaValidation(
require("../schemas/plugins/BannerPlugin.check.js"),
() => require("../schemas/plugins/BannerPlugin.json"),
{
name: "Banner Plugin",
baseDataPath: "options"
}
);
/**
* @param {string} str string to wrap
* @returns {string} wrapped string
*/
const wrapComment = str => {
if (!str.includes("\n")) {
return Template.toComment(str);
}
return `/*!\n * ${str
.replace(/\*\//g, "* /")
.split("\n")
.join("\n * ")
.replace(/\s+\n/g, "\n")
.trimEnd()}\n */`;
};
class BannerPlugin {
/**
* @param {BannerPluginArgument} options options object
*/
constructor(options) {
if (typeof options === "string" || typeof options === "function") {
options = {
banner: options
};
}
validate(options);
this.options = options;
const bannerOption = options.banner;
if (typeof bannerOption === "function") {
const getBanner = bannerOption;
/** @type {BannerFunction} */
this.banner = this.options.raw
? getBanner
: /** @type {BannerFunction} */ data => wrapComment(getBanner(data));
} else {
const banner = this.options.raw
? bannerOption
: wrapComment(bannerOption);
/** @type {BannerFunction} */
this.banner = () => banner;
}
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const options = this.options;
const banner = this.banner;
const matchObject = ModuleFilenameHelpers.matchObject.bind(
undefined,
options
);
const cache = new WeakMap();
const stage =
this.options.stage || Compilation.PROCESS_ASSETS_STAGE_ADDITIONS;
compiler.hooks.compilation.tap("BannerPlugin", compilation => {
compilation.hooks.processAssets.tap(
{
name: "BannerPlugin",
stage
},
() => {
for (const chunk of compilation.chunks) {
if (options.entryOnly && !chunk.canBeInitial()) {
continue;
}
for (const file of chunk.files) {
if (!matchObject(file)) {
continue;
}
/** @type {PathData} */
const data = { chunk, filename: file };
const comment = compilation.getPath(
/** @type {TemplatePath} */
(banner),
data
);
compilation.updateAsset(file, old => {
const cached = cache.get(old);
if (!cached || cached.comment !== comment) {
const source = options.footer
? new ConcatSource(old, "\n", comment)
: new ConcatSource(comment, "\n", old);
cache.set(old, { source, comment });
return source;
}
return cached.source;
});
}
}
}
);
});
}
}
module.exports = BannerPlugin;

View file

@ -0,0 +1,71 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("./WebpackError");
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/**
* @param {Module[]} modules the modules to be sorted
* @returns {Module[]} sorted version of original modules
*/
const sortModules = modules =>
modules.sort((a, b) => {
const aIdent = a.identifier();
const bIdent = b.identifier();
/* istanbul ignore next */
if (aIdent < bIdent) return -1;
/* istanbul ignore next */
if (aIdent > bIdent) return 1;
/* istanbul ignore next */
return 0;
});
/**
* @param {Module[]} modules each module from throw
* @param {ModuleGraph} moduleGraph the module graph
* @returns {string} each message from provided modules
*/
const createModulesListMessage = (modules, moduleGraph) =>
modules
.map(m => {
let message = `* ${m.identifier()}`;
const validReasons = Array.from(
moduleGraph.getIncomingConnectionsByOriginModule(m).keys()
).filter(Boolean);
if (validReasons.length > 0) {
message += `\n Used by ${validReasons.length} module(s), i. e.`;
message += `\n ${
/** @type {Module[]} */ (validReasons)[0].identifier()
}`;
}
return message;
})
.join("\n");
class CaseSensitiveModulesWarning extends WebpackError {
/**
* Creates an instance of CaseSensitiveModulesWarning.
* @param {Iterable<Module>} modules modules that were detected
* @param {ModuleGraph} moduleGraph the module graph
*/
constructor(modules, moduleGraph) {
const sortedModules = sortModules(Array.from(modules));
const modulesList = createModulesListMessage(sortedModules, moduleGraph);
super(`There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:
${modulesList}`);
this.name = "CaseSensitiveModulesWarning";
this.module = sortedModules[0];
}
}
module.exports = CaseSensitiveModulesWarning;

844
node_modules/webpack/lib/Chunk.js generated vendored Normal file
View file

@ -0,0 +1,844 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ChunkGraph = require("./ChunkGraph");
const Entrypoint = require("./Entrypoint");
const { intersect } = require("./util/SetHelpers");
const SortableSet = require("./util/SortableSet");
const StringXor = require("./util/StringXor");
const {
compareModulesByIdentifier,
compareChunkGroupsByIndex,
compareModulesById
} = require("./util/comparators");
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 {number | string} ChunkId */
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<string|number, string>} hash
* @property {Record<string|number, Record<string, string>>} contentHash
* @property {Record<string|number, string>} name
*/
/**
* @deprecated
* @typedef {object} ChunkModuleMaps
* @property {Record<string|number, (string|number)[]>} id
* @property {Record<string|number, string>} hash
*/
let debugId = 1000;
/**
* A Chunk is a unit of encapsulation for Modules.
* Chunks are "rendered" into bundles that get emitted when the build completes.
*/
class Chunk {
/**
* @param {string=} name of chunk being created, is optional (for subclasses)
* @param {boolean} backCompat enable backward-compatibility
*/
constructor(name, backCompat = true) {
/** @type {ChunkId | null} */
this.id = null;
/** @type {ChunkId[] | null} */
this.ids = null;
/** @type {number} */
this.debugId = debugId++;
/** @type {string | undefined} */
this.name = name;
/** @type {SortableSet<string>} */
this.idNameHints = new SortableSet();
/** @type {boolean} */
this.preventIntegration = false;
/** @type {TemplatePath | undefined} */
this.filenameTemplate = undefined;
/** @type {TemplatePath | undefined} */
this.cssFilenameTemplate = undefined;
/**
* @private
* @type {SortableSet<ChunkGroup>}
*/
this._groups = new SortableSet(undefined, compareChunkGroupsByIndex);
/** @type {RuntimeSpec} */
this.runtime = undefined;
/** @type {Set<string>} */
this.files = backCompat ? new ChunkFilesSet() : new Set();
/** @type {Set<string>} */
this.auxiliaryFiles = new Set();
/** @type {boolean} */
this.rendered = false;
/** @type {string=} */
this.hash = undefined;
/** @type {Record<string, string>} */
this.contentHash = Object.create(null);
/** @type {string=} */
this.renderedHash = undefined;
/** @type {string=} */
this.chunkReason = undefined;
/** @type {boolean} */
this.extraAsync = false;
}
// TODO remove in webpack 6
// BACKWARD-COMPAT START
get entryModule() {
const entryModules = Array.from(
ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.entryModule",
"DEP_WEBPACK_CHUNK_ENTRY_MODULE"
).getChunkEntryModulesIterable(this)
);
if (entryModules.length === 0) {
return undefined;
} else if (entryModules.length === 1) {
return entryModules[0];
}
throw new Error(
"Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API)"
);
}
/**
* @returns {boolean} true, if the chunk contains an entry module
*/
hasEntryModule() {
return (
ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.hasEntryModule",
"DEP_WEBPACK_CHUNK_HAS_ENTRY_MODULE"
).getNumberOfEntryModules(this) > 0
);
}
/**
* @param {Module} module the module
* @returns {boolean} true, if the chunk could be added
*/
addModule(module) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.addModule",
"DEP_WEBPACK_CHUNK_ADD_MODULE"
);
if (chunkGraph.isModuleInChunk(module, this)) return false;
chunkGraph.connectChunkAndModule(this, module);
return true;
}
/**
* @param {Module} module the module
* @returns {void}
*/
removeModule(module) {
ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.removeModule",
"DEP_WEBPACK_CHUNK_REMOVE_MODULE"
).disconnectChunkAndModule(this, module);
}
/**
* @returns {number} the number of module which are contained in this chunk
*/
getNumberOfModules() {
return ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.getNumberOfModules",
"DEP_WEBPACK_CHUNK_GET_NUMBER_OF_MODULES"
).getNumberOfChunkModules(this);
}
get modulesIterable() {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.modulesIterable",
"DEP_WEBPACK_CHUNK_MODULES_ITERABLE"
);
return chunkGraph.getOrderedChunkModulesIterable(
this,
compareModulesByIdentifier
);
}
/**
* @param {Chunk} otherChunk the chunk to compare with
* @returns {-1|0|1} the comparison result
*/
compareTo(otherChunk) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.compareTo",
"DEP_WEBPACK_CHUNK_COMPARE_TO"
);
return chunkGraph.compareChunks(this, otherChunk);
}
/**
* @param {Module} module the module
* @returns {boolean} true, if the chunk contains the module
*/
containsModule(module) {
return ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.containsModule",
"DEP_WEBPACK_CHUNK_CONTAINS_MODULE"
).isModuleInChunk(module, this);
}
/**
* @returns {Module[]} the modules for this chunk
*/
getModules() {
return ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.getModules",
"DEP_WEBPACK_CHUNK_GET_MODULES"
).getChunkModules(this);
}
/**
* @returns {void}
*/
remove() {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.remove",
"DEP_WEBPACK_CHUNK_REMOVE"
);
chunkGraph.disconnectChunk(this);
this.disconnectFromGroups();
}
/**
* @param {Module} module the module
* @param {Chunk} otherChunk the target chunk
* @returns {void}
*/
moveModule(module, otherChunk) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.moveModule",
"DEP_WEBPACK_CHUNK_MOVE_MODULE"
);
chunkGraph.disconnectChunkAndModule(this, module);
chunkGraph.connectChunkAndModule(otherChunk, module);
}
/**
* @param {Chunk} otherChunk the other chunk
* @returns {boolean} true, if the specified chunk has been integrated
*/
integrate(otherChunk) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.integrate",
"DEP_WEBPACK_CHUNK_INTEGRATE"
);
if (chunkGraph.canChunksBeIntegrated(this, otherChunk)) {
chunkGraph.integrateChunks(this, otherChunk);
return true;
}
return false;
}
/**
* @param {Chunk} otherChunk the other chunk
* @returns {boolean} true, if chunks could be integrated
*/
canBeIntegrated(otherChunk) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.canBeIntegrated",
"DEP_WEBPACK_CHUNK_CAN_BE_INTEGRATED"
);
return chunkGraph.canChunksBeIntegrated(this, otherChunk);
}
/**
* @returns {boolean} true, if this chunk contains no module
*/
isEmpty() {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.isEmpty",
"DEP_WEBPACK_CHUNK_IS_EMPTY"
);
return chunkGraph.getNumberOfChunkModules(this) === 0;
}
/**
* @returns {number} total size of all modules in this chunk
*/
modulesSize() {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.modulesSize",
"DEP_WEBPACK_CHUNK_MODULES_SIZE"
);
return chunkGraph.getChunkModulesSize(this);
}
/**
* @param {ChunkSizeOptions} options options object
* @returns {number} total size of this chunk
*/
size(options = {}) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.size",
"DEP_WEBPACK_CHUNK_SIZE"
);
return chunkGraph.getChunkSize(this, options);
}
/**
* @param {Chunk} otherChunk the other chunk
* @param {ChunkSizeOptions} options options object
* @returns {number} total size of the chunk or false if the chunk can't be integrated
*/
integratedSize(otherChunk, options) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.integratedSize",
"DEP_WEBPACK_CHUNK_INTEGRATED_SIZE"
);
return chunkGraph.getIntegratedChunksSize(this, otherChunk, options);
}
/**
* @param {ModuleFilterPredicate} filterFn function used to filter modules
* @returns {ChunkModuleMaps} module map information
*/
getChunkModuleMaps(filterFn) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.getChunkModuleMaps",
"DEP_WEBPACK_CHUNK_GET_CHUNK_MODULE_MAPS"
);
/** @type {Record<string|number, (string|number)[]>} */
const chunkModuleIdMap = Object.create(null);
/** @type {Record<string|number, string>} */
const chunkModuleHashMap = Object.create(null);
for (const asyncChunk of this.getAllAsyncChunks()) {
/** @type {ChunkId[] | undefined} */
let array;
for (const module of chunkGraph.getOrderedChunkModulesIterable(
asyncChunk,
compareModulesById(chunkGraph)
)) {
if (filterFn(module)) {
if (array === undefined) {
array = [];
chunkModuleIdMap[/** @type {ChunkId} */ (asyncChunk.id)] = array;
}
const moduleId =
/** @type {ModuleId} */
(chunkGraph.getModuleId(module));
array.push(moduleId);
chunkModuleHashMap[moduleId] = chunkGraph.getRenderedModuleHash(
module,
undefined
);
}
}
}
return {
id: chunkModuleIdMap,
hash: chunkModuleHashMap
};
}
/**
* @param {ModuleFilterPredicate} filterFn predicate function used to filter modules
* @param {ChunkFilterPredicate=} filterChunkFn predicate function used to filter chunks
* @returns {boolean} return true if module exists in graph
*/
hasModuleInGraph(filterFn, filterChunkFn) {
const chunkGraph = ChunkGraph.getChunkGraphForChunk(
this,
"Chunk.hasModuleInGraph",
"DEP_WEBPACK_CHUNK_HAS_MODULE_IN_GRAPH"
);
return chunkGraph.hasModuleInGraph(this, filterFn, filterChunkFn);
}
/**
* @deprecated
* @param {boolean} realHash whether the full hash or the rendered hash is to be used
* @returns {ChunkMaps} the chunk map information
*/
getChunkMaps(realHash) {
/** @type {Record<string|number, string>} */
const chunkHashMap = Object.create(null);
/** @type {Record<string|number, Record<string, string>>} */
const chunkContentHashMap = Object.create(null);
/** @type {Record<string|number, string>} */
const chunkNameMap = Object.create(null);
for (const chunk of this.getAllAsyncChunks()) {
const id = /** @type {ChunkId} */ (chunk.id);
chunkHashMap[id] =
/** @type {string} */
(realHash ? chunk.hash : chunk.renderedHash);
for (const key of Object.keys(chunk.contentHash)) {
if (!chunkContentHashMap[key]) {
chunkContentHashMap[key] = Object.create(null);
}
chunkContentHashMap[key][id] = chunk.contentHash[key];
}
if (chunk.name) {
chunkNameMap[id] = chunk.name;
}
}
return {
hash: chunkHashMap,
contentHash: chunkContentHashMap,
name: chunkNameMap
};
}
// BACKWARD-COMPAT END
/**
* @returns {boolean} whether or not the Chunk will have a runtime
*/
hasRuntime() {
for (const chunkGroup of this._groups) {
if (
chunkGroup instanceof Entrypoint &&
chunkGroup.getRuntimeChunk() === this
) {
return true;
}
}
return false;
}
/**
* @returns {boolean} whether or not this chunk can be an initial chunk
*/
canBeInitial() {
for (const chunkGroup of this._groups) {
if (chunkGroup.isInitial()) return true;
}
return false;
}
/**
* @returns {boolean} whether this chunk can only be an initial chunk
*/
isOnlyInitial() {
if (this._groups.size <= 0) return false;
for (const chunkGroup of this._groups) {
if (!chunkGroup.isInitial()) return false;
}
return true;
}
/**
* @returns {EntryOptions | undefined} the entry options for this chunk
*/
getEntryOptions() {
for (const chunkGroup of this._groups) {
if (chunkGroup instanceof Entrypoint) {
return chunkGroup.options;
}
}
return undefined;
}
/**
* @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being added
* @returns {void}
*/
addGroup(chunkGroup) {
this._groups.add(chunkGroup);
}
/**
* @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being removed from
* @returns {void}
*/
removeGroup(chunkGroup) {
this._groups.delete(chunkGroup);
}
/**
* @param {ChunkGroup} chunkGroup the chunkGroup to check
* @returns {boolean} returns true if chunk has chunkGroup reference and exists in chunkGroup
*/
isInGroup(chunkGroup) {
return this._groups.has(chunkGroup);
}
/**
* @returns {number} the amount of groups that the said chunk is in
*/
getNumberOfGroups() {
return this._groups.size;
}
/**
* @returns {SortableSet<ChunkGroup>} the chunkGroups that the said chunk is referenced in
*/
get groupsIterable() {
this._groups.sort();
return this._groups;
}
/**
* @returns {void}
*/
disconnectFromGroups() {
for (const chunkGroup of this._groups) {
chunkGroup.removeChunk(this);
}
}
/**
* @param {Chunk} newChunk the new chunk that will be split out of
* @returns {void}
*/
split(newChunk) {
for (const chunkGroup of this._groups) {
chunkGroup.insertChunk(newChunk, this);
newChunk.addGroup(chunkGroup);
}
for (const idHint of this.idNameHints) {
newChunk.idNameHints.add(idHint);
}
newChunk.runtime = mergeRuntime(newChunk.runtime, this.runtime);
}
/**
* @param {Hash} hash hash (will be modified)
* @param {ChunkGraph} chunkGraph the chunk graph
* @returns {void}
*/
updateHash(hash, chunkGraph) {
hash.update(
`${this.id} ${this.ids ? this.ids.join() : ""} ${this.name || ""} `
);
const xor = new StringXor();
for (const m of chunkGraph.getChunkModulesIterable(this)) {
xor.add(chunkGraph.getModuleHash(m, this.runtime));
}
xor.updateHash(hash);
const entryModules =
chunkGraph.getChunkEntryModulesWithChunkGroupIterable(this);
for (const [m, chunkGroup] of entryModules) {
hash.update(
`entry${chunkGraph.getModuleId(m)}${
/** @type {ChunkGroup} */ (chunkGroup).id
}`
);
}
}
/**
* @returns {Set<Chunk>} a set of all the async chunks
*/
getAllAsyncChunks() {
const queue = new Set();
const chunks = new Set();
const initialChunks = intersect(
Array.from(this.groupsIterable, g => new Set(g.chunks))
);
const initialQueue = new Set(this.groupsIterable);
for (const chunkGroup of initialQueue) {
for (const child of chunkGroup.childrenIterable) {
if (child instanceof Entrypoint) {
initialQueue.add(child);
} else {
queue.add(child);
}
}
}
for (const chunkGroup of queue) {
for (const chunk of chunkGroup.chunks) {
if (!initialChunks.has(chunk)) {
chunks.add(chunk);
}
}
for (const child of chunkGroup.childrenIterable) {
queue.add(child);
}
}
return chunks;
}
/**
* @returns {Set<Chunk>} a set of all the initial chunks (including itself)
*/
getAllInitialChunks() {
const chunks = new Set();
const queue = new Set(this.groupsIterable);
for (const group of queue) {
if (group.isInitial()) {
for (const c of group.chunks) chunks.add(c);
for (const g of group.childrenIterable) queue.add(g);
}
}
return chunks;
}
/**
* @returns {Set<Chunk>} a set of all the referenced chunks (including itself)
*/
getAllReferencedChunks() {
const queue = new Set(this.groupsIterable);
const chunks = new Set();
for (const chunkGroup of queue) {
for (const chunk of chunkGroup.chunks) {
chunks.add(chunk);
}
for (const child of chunkGroup.childrenIterable) {
queue.add(child);
}
}
return chunks;
}
/**
* @returns {Set<Entrypoint>} a set of all the referenced entrypoints
*/
getAllReferencedAsyncEntrypoints() {
const queue = new Set(this.groupsIterable);
const entrypoints = new Set();
for (const chunkGroup of queue) {
for (const entrypoint of chunkGroup.asyncEntrypointsIterable) {
entrypoints.add(entrypoint);
}
for (const child of chunkGroup.childrenIterable) {
queue.add(child);
}
}
return entrypoints;
}
/**
* @returns {boolean} true, if the chunk references async chunks
*/
hasAsyncChunks() {
const queue = new Set();
const initialChunks = intersect(
Array.from(this.groupsIterable, g => new Set(g.chunks))
);
for (const chunkGroup of this.groupsIterable) {
for (const child of chunkGroup.childrenIterable) {
queue.add(child);
}
}
for (const chunkGroup of queue) {
for (const chunk of chunkGroup.chunks) {
if (!initialChunks.has(chunk)) {
return true;
}
}
for (const child of chunkGroup.childrenIterable) {
queue.add(child);
}
}
return false;
}
/**
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {ChunkFilterPredicate=} filterFn function used to filter chunks
* @returns {Record<string, (string | number)[]>} a record object of names to lists of child ids(?)
*/
getChildIdsByOrders(chunkGraph, filterFn) {
/** @type {Map<string, {order: number, group: ChunkGroup}[]>} */
const lists = new Map();
for (const group of this.groupsIterable) {
if (group.chunks[group.chunks.length - 1] === this) {
for (const childGroup of group.childrenIterable) {
for (const key of Object.keys(childGroup.options)) {
if (key.endsWith("Order")) {
const name = key.slice(0, key.length - "Order".length);
let list = lists.get(name);
if (list === undefined) {
list = [];
lists.set(name, list);
}
list.push({
order:
/** @type {number} */
(
childGroup.options[
/** @type {keyof ChunkGroupOptions} */ (key)
]
),
group: childGroup
});
}
}
}
}
}
/** @type {Record<string, (string | number)[]>} */
const result = Object.create(null);
for (const [name, list] of lists) {
list.sort((a, b) => {
const cmp = b.order - a.order;
if (cmp !== 0) return cmp;
return a.group.compareTo(chunkGraph, b.group);
});
/** @type {Set<string | number>} */
const chunkIdSet = new Set();
for (const item of list) {
for (const chunk of item.group.chunks) {
if (filterFn && !filterFn(chunk, chunkGraph)) continue;
chunkIdSet.add(/** @type {ChunkId} */ (chunk.id));
}
}
if (chunkIdSet.size > 0) {
result[name] = Array.from(chunkIdSet);
}
}
return result;
}
/**
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {string} type option name
* @returns {{ onChunks: Chunk[], chunks: Set<Chunk> }[] | undefined} referenced chunks for a specific type
*/
getChildrenOfTypeInOrder(chunkGraph, type) {
const list = [];
for (const group of this.groupsIterable) {
for (const childGroup of group.childrenIterable) {
const order =
childGroup.options[/** @type {keyof ChunkGroupOptions} */ (type)];
if (order === undefined) continue;
list.push({
order,
group,
childGroup
});
}
}
if (list.length === 0) return;
list.sort((a, b) => {
const cmp =
/** @type {number} */ (b.order) - /** @type {number} */ (a.order);
if (cmp !== 0) return cmp;
return a.group.compareTo(chunkGraph, b.group);
});
const result = [];
let lastEntry;
for (const { group, childGroup } of list) {
if (lastEntry && lastEntry.onChunks === group.chunks) {
for (const chunk of childGroup.chunks) {
lastEntry.chunks.add(chunk);
}
} else {
result.push(
(lastEntry = {
onChunks: group.chunks,
chunks: new Set(childGroup.chunks)
})
);
}
}
return result;
}
/**
* @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
*/
getChildIdsByOrdersMap(chunkGraph, includeDirectChildren, filterFn) {
/** @type {Record<string|number, Record<string, (string | number)[]>>} */
const chunkMaps = Object.create(null);
/**
* @param {Chunk} chunk a chunk
* @returns {void}
*/
const addChildIdsByOrdersToMap = chunk => {
const data = chunk.getChildIdsByOrders(chunkGraph, filterFn);
for (const key of Object.keys(data)) {
let chunkMap = chunkMaps[key];
if (chunkMap === undefined) {
chunkMaps[key] = chunkMap = Object.create(null);
}
chunkMap[/** @type {ChunkId} */ (chunk.id)] = data[key];
}
};
if (includeDirectChildren) {
/** @type {Set<Chunk>} */
const chunks = new Set();
for (const chunkGroup of this.groupsIterable) {
for (const chunk of chunkGroup.chunks) {
chunks.add(chunk);
}
}
for (const chunk of chunks) {
addChildIdsByOrdersToMap(chunk);
}
}
for (const chunk of this.getAllAsyncChunks()) {
addChildIdsByOrdersToMap(chunk);
}
return chunkMaps;
}
}
module.exports = Chunk;

604
node_modules/webpack/lib/ChunkGroup.js generated vendored Normal file
View file

@ -0,0 +1,604 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
const SortableSet = require("./util/SortableSet");
const {
compareLocations,
compareChunks,
compareIterables
} = require("./util/comparators");
/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Entrypoint")} Entrypoint */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {{id: number}} HasId */
/** @typedef {{module: Module | null, loc: DependencyLocation, request: string}} OriginRecord */
/**
* @typedef {object} RawChunkGroupOptions
* @property {number=} preloadOrder
* @property {number=} prefetchOrder
* @property {("low" | "high" | "auto")=} fetchPriority
*/
/** @typedef {RawChunkGroupOptions & { name?: string }} ChunkGroupOptions */
let debugId = 5000;
/**
* @template T
* @param {SortableSet<T>} set set to convert to array.
* @returns {T[]} the array format of existing set
*/
const getArray = set => Array.from(set);
/**
* A convenience method used to sort chunks based on their id's
* @param {ChunkGroup} a first sorting comparator
* @param {ChunkGroup} b second sorting comparator
* @returns {1|0|-1} a sorting index to determine order
*/
const sortById = (a, b) => {
if (a.id < b.id) return -1;
if (b.id < a.id) return 1;
return 0;
};
/**
* @param {OriginRecord} a the first comparator in sort
* @param {OriginRecord} b the second comparator in sort
* @returns {1|-1|0} returns sorting order as index
*/
const sortOrigin = (a, b) => {
const aIdent = a.module ? a.module.identifier() : "";
const bIdent = b.module ? b.module.identifier() : "";
if (aIdent < bIdent) return -1;
if (aIdent > bIdent) return 1;
return compareLocations(a.loc, b.loc);
};
class ChunkGroup {
/**
* Creates an instance of ChunkGroup.
* @param {string | ChunkGroupOptions=} options chunk group options passed to chunkGroup
*/
constructor(options) {
if (typeof options === "string") {
options = { name: options };
} else if (!options) {
options = { name: undefined };
}
/** @type {number} */
this.groupDebugId = debugId++;
this.options = /** @type {ChunkGroupOptions} */ (options);
/** @type {SortableSet<ChunkGroup>} */
this._children = new SortableSet(undefined, sortById);
/** @type {SortableSet<ChunkGroup>} */
this._parents = new SortableSet(undefined, sortById);
/** @type {SortableSet<ChunkGroup>} */
this._asyncEntrypoints = new SortableSet(undefined, sortById);
this._blocks = new SortableSet();
/** @type {Chunk[]} */
this.chunks = [];
/** @type {OriginRecord[]} */
this.origins = [];
/** Indices in top-down order */
/**
* @private
* @type {Map<Module, number>}
*/
this._modulePreOrderIndices = new Map();
/** Indices in bottom-up order */
/**
* @private
* @type {Map<Module, number>}
*/
this._modulePostOrderIndices = new Map();
/** @type {number | undefined} */
this.index = undefined;
}
/**
* when a new chunk is added to a chunkGroup, addingOptions will occur.
* @param {ChunkGroupOptions} options the chunkGroup options passed to addOptions
* @returns {void}
*/
addOptions(options) {
for (const _key of Object.keys(options)) {
const key = /** @type {keyof ChunkGroupOptions} */ (_key);
if (this.options[key] === undefined) {
/** @type {TODO} */
(this.options)[key] = options[key];
} else if (this.options[key] !== options[key]) {
if (key.endsWith("Order")) {
/** @type {TODO} */
(this.options)[key] = Math.max(
/** @type {number} */ (this.options[key]),
/** @type {number} */ (options[key])
);
} else {
throw new Error(
`ChunkGroup.addOptions: No option merge strategy for ${key}`
);
}
}
}
}
/**
* returns the name of current ChunkGroup
* @returns {string | undefined} returns the ChunkGroup name
*/
get name() {
return this.options.name;
}
/**
* sets a new name for current ChunkGroup
* @param {string | undefined} value the new name for ChunkGroup
* @returns {void}
*/
set name(value) {
this.options.name = value;
}
/* istanbul ignore next */
/**
* get a uniqueId for ChunkGroup, made up of its member Chunk debugId's
* @returns {string} a unique concatenation of chunk debugId's
*/
get debugId() {
return Array.from(this.chunks, x => x.debugId).join("+");
}
/**
* get a unique id for ChunkGroup, made up of its member Chunk id's
* @returns {string} a unique concatenation of chunk ids
*/
get id() {
return Array.from(this.chunks, x => x.id).join("+");
}
/**
* Performs an unshift of a specific chunk
* @param {Chunk} chunk chunk being unshifted
* @returns {boolean} returns true if attempted chunk shift is accepted
*/
unshiftChunk(chunk) {
const oldIdx = this.chunks.indexOf(chunk);
if (oldIdx > 0) {
this.chunks.splice(oldIdx, 1);
this.chunks.unshift(chunk);
} else if (oldIdx < 0) {
this.chunks.unshift(chunk);
return true;
}
return false;
}
/**
* inserts a chunk before another existing chunk in group
* @param {Chunk} chunk Chunk being inserted
* @param {Chunk} before Placeholder/target chunk marking new chunk insertion point
* @returns {boolean} return true if insertion was successful
*/
insertChunk(chunk, before) {
const oldIdx = this.chunks.indexOf(chunk);
const idx = this.chunks.indexOf(before);
if (idx < 0) {
throw new Error("before chunk not found");
}
if (oldIdx >= 0 && oldIdx > idx) {
this.chunks.splice(oldIdx, 1);
this.chunks.splice(idx, 0, chunk);
} else if (oldIdx < 0) {
this.chunks.splice(idx, 0, chunk);
return true;
}
return false;
}
/**
* add a chunk into ChunkGroup. Is pushed on or prepended
* @param {Chunk} chunk chunk being pushed into ChunkGroupS
* @returns {boolean} returns true if chunk addition was successful.
*/
pushChunk(chunk) {
const oldIdx = this.chunks.indexOf(chunk);
if (oldIdx >= 0) {
return false;
}
this.chunks.push(chunk);
return true;
}
/**
* @param {Chunk} oldChunk chunk to be replaced
* @param {Chunk} newChunk New chunk that will be replaced with
* @returns {boolean | undefined} returns true if the replacement was successful
*/
replaceChunk(oldChunk, newChunk) {
const oldIdx = this.chunks.indexOf(oldChunk);
if (oldIdx < 0) return false;
const newIdx = this.chunks.indexOf(newChunk);
if (newIdx < 0) {
this.chunks[oldIdx] = newChunk;
return true;
}
if (newIdx < oldIdx) {
this.chunks.splice(oldIdx, 1);
return true;
} else if (newIdx !== oldIdx) {
this.chunks[oldIdx] = newChunk;
this.chunks.splice(newIdx, 1);
return true;
}
}
/**
* @param {Chunk} chunk chunk to remove
* @returns {boolean} returns true if chunk was removed
*/
removeChunk(chunk) {
const idx = this.chunks.indexOf(chunk);
if (idx >= 0) {
this.chunks.splice(idx, 1);
return true;
}
return false;
}
/**
* @returns {boolean} true, when this chunk group will be loaded on initial page load
*/
isInitial() {
return false;
}
/**
* @param {ChunkGroup} group chunk group to add
* @returns {boolean} returns true if chunk group was added
*/
addChild(group) {
const size = this._children.size;
this._children.add(group);
return size !== this._children.size;
}
/**
* @returns {ChunkGroup[]} returns the children of this group
*/
getChildren() {
return this._children.getFromCache(getArray);
}
getNumberOfChildren() {
return this._children.size;
}
get childrenIterable() {
return this._children;
}
/**
* @param {ChunkGroup} group the chunk group to remove
* @returns {boolean} returns true if the chunk group was removed
*/
removeChild(group) {
if (!this._children.has(group)) {
return false;
}
this._children.delete(group);
group.removeParent(this);
return true;
}
/**
* @param {ChunkGroup} parentChunk the parent group to be added into
* @returns {boolean} returns true if this chunk group was added to the parent group
*/
addParent(parentChunk) {
if (!this._parents.has(parentChunk)) {
this._parents.add(parentChunk);
return true;
}
return false;
}
/**
* @returns {ChunkGroup[]} returns the parents of this group
*/
getParents() {
return this._parents.getFromCache(getArray);
}
getNumberOfParents() {
return this._parents.size;
}
/**
* @param {ChunkGroup} parent the parent group
* @returns {boolean} returns true if the parent group contains this group
*/
hasParent(parent) {
return this._parents.has(parent);
}
get parentsIterable() {
return this._parents;
}
/**
* @param {ChunkGroup} chunkGroup the parent group
* @returns {boolean} returns true if this group has been removed from the parent
*/
removeParent(chunkGroup) {
if (this._parents.delete(chunkGroup)) {
chunkGroup.removeChild(this);
return true;
}
return false;
}
/**
* @param {Entrypoint} entrypoint entrypoint to add
* @returns {boolean} returns true if entrypoint was added
*/
addAsyncEntrypoint(entrypoint) {
const size = this._asyncEntrypoints.size;
this._asyncEntrypoints.add(entrypoint);
return size !== this._asyncEntrypoints.size;
}
get asyncEntrypointsIterable() {
return this._asyncEntrypoints;
}
/**
* @returns {Array<AsyncDependenciesBlock>} an array containing the blocks
*/
getBlocks() {
return this._blocks.getFromCache(getArray);
}
getNumberOfBlocks() {
return this._blocks.size;
}
/**
* @param {AsyncDependenciesBlock} block block
* @returns {boolean} true, if block exists
*/
hasBlock(block) {
return this._blocks.has(block);
}
/**
* @returns {Iterable<AsyncDependenciesBlock>} blocks
*/
get blocksIterable() {
return this._blocks;
}
/**
* @param {AsyncDependenciesBlock} block a block
* @returns {boolean} false, if block was already added
*/
addBlock(block) {
if (!this._blocks.has(block)) {
this._blocks.add(block);
return true;
}
return false;
}
/**
* @param {Module | null} module origin module
* @param {DependencyLocation} loc location of the reference in the origin module
* @param {string} request request name of the reference
* @returns {void}
*/
addOrigin(module, loc, request) {
this.origins.push({
module,
loc,
request
});
}
/**
* @returns {string[]} the files contained this chunk group
*/
getFiles() {
const files = new Set();
for (const chunk of this.chunks) {
for (const file of chunk.files) {
files.add(file);
}
}
return Array.from(files);
}
/**
* @returns {void}
*/
remove() {
// cleanup parents
for (const parentChunkGroup of this._parents) {
// remove this chunk from its parents
parentChunkGroup._children.delete(this);
// cleanup "sub chunks"
for (const chunkGroup of this._children) {
/**
* remove this chunk as "intermediary" and connect
* it "sub chunks" and parents directly
*/
// add parent to each "sub chunk"
chunkGroup.addParent(parentChunkGroup);
// add "sub chunk" to parent
parentChunkGroup.addChild(chunkGroup);
}
}
/**
* we need to iterate again over the children
* to remove this from the child's parents.
* This can not be done in the above loop
* as it is not guaranteed that `this._parents` contains anything.
*/
for (const chunkGroup of this._children) {
// remove this as parent of every "sub chunk"
chunkGroup._parents.delete(this);
}
// remove chunks
for (const chunk of this.chunks) {
chunk.removeGroup(this);
}
}
sortItems() {
this.origins.sort(sortOrigin);
}
/**
* Sorting predicate which allows current ChunkGroup to be compared against another.
* Sorting values are based off of number of chunks in ChunkGroup.
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {ChunkGroup} otherGroup the chunkGroup to compare this against
* @returns {-1|0|1} sort position for comparison
*/
compareTo(chunkGraph, otherGroup) {
if (this.chunks.length > otherGroup.chunks.length) return -1;
if (this.chunks.length < otherGroup.chunks.length) return 1;
return compareIterables(compareChunks(chunkGraph))(
this.chunks,
otherGroup.chunks
);
}
/**
* @param {ModuleGraph} moduleGraph the module graph
* @param {ChunkGraph} chunkGraph the chunk graph
* @returns {Record<string, ChunkGroup[]>} mapping from children type to ordered list of ChunkGroups
*/
getChildrenByOrders(moduleGraph, chunkGraph) {
/** @type {Map<string, {order: number, group: ChunkGroup}[]>} */
const lists = new Map();
for (const childGroup of this._children) {
for (const key of Object.keys(childGroup.options)) {
if (key.endsWith("Order")) {
const name = key.slice(0, key.length - "Order".length);
let list = lists.get(name);
if (list === undefined) {
lists.set(name, (list = []));
}
list.push({
order:
/** @type {number} */
(
childGroup.options[/** @type {keyof ChunkGroupOptions} */ (key)]
),
group: childGroup
});
}
}
}
/** @type {Record<string, ChunkGroup[]>} */
const result = Object.create(null);
for (const [name, list] of lists) {
list.sort((a, b) => {
const cmp = b.order - a.order;
if (cmp !== 0) return cmp;
return a.group.compareTo(chunkGraph, b.group);
});
result[name] = list.map(i => i.group);
}
return result;
}
/**
* Sets the top-down index of a module in this ChunkGroup
* @param {Module} module module for which the index should be set
* @param {number} index the index of the module
* @returns {void}
*/
setModulePreOrderIndex(module, index) {
this._modulePreOrderIndices.set(module, index);
}
/**
* Gets the top-down index of a module in this ChunkGroup
* @param {Module} module the module
* @returns {number | undefined} index
*/
getModulePreOrderIndex(module) {
return this._modulePreOrderIndices.get(module);
}
/**
* Sets the bottom-up index of a module in this ChunkGroup
* @param {Module} module module for which the index should be set
* @param {number} index the index of the module
* @returns {void}
*/
setModulePostOrderIndex(module, index) {
this._modulePostOrderIndices.set(module, index);
}
/**
* Gets the bottom-up index of a module in this ChunkGroup
* @param {Module} module the module
* @returns {number | undefined} index
*/
getModulePostOrderIndex(module) {
return this._modulePostOrderIndices.get(module);
}
/* istanbul ignore next */
checkConstraints() {
const chunk = this;
for (const child of chunk._children) {
if (!child._parents.has(chunk)) {
throw new Error(
`checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}`
);
}
}
for (const parentChunk of chunk._parents) {
if (!parentChunk._children.has(chunk)) {
throw new Error(
`checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}`
);
}
}
}
}
ChunkGroup.prototype.getModuleIndex = util.deprecate(
ChunkGroup.prototype.getModulePreOrderIndex,
"ChunkGroup.getModuleIndex was renamed to getModulePreOrderIndex",
"DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX"
);
ChunkGroup.prototype.getModuleIndex2 = util.deprecate(
ChunkGroup.prototype.getModulePostOrderIndex,
"ChunkGroup.getModuleIndex2 was renamed to getModulePostOrderIndex",
"DEP_WEBPACK_CHUNK_GROUP_GET_MODULE_INDEX_2"
);
module.exports = ChunkGroup;

31
node_modules/webpack/lib/ChunkRenderError.js generated vendored Normal file
View file

@ -0,0 +1,31 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("./WebpackError");
/** @typedef {import("./Chunk")} Chunk */
class ChunkRenderError extends WebpackError {
/**
* Create a new ChunkRenderError
* @param {Chunk} chunk A chunk
* @param {string} file Related file
* @param {Error} error Original error
*/
constructor(chunk, file, error) {
super();
this.name = "ChunkRenderError";
this.error = error;
this.message = error.message;
this.details = error.stack;
this.file = file;
this.chunk = chunk;
}
}
module.exports = ChunkRenderError;

181
node_modules/webpack/lib/ChunkTemplate.js generated vendored Normal file
View file

@ -0,0 +1,181 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
const memoize = require("./util/memoize");
/** @typedef {import("tapable").Tap} Tap */
/** @typedef {import("../declarations/WebpackOptions").Output} OutputOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Compilation").ChunkHashContext} ChunkHashContext */
/** @typedef {import("./Compilation").Hash} Hash */
/** @typedef {import("./Compilation").RenderManifestEntry} RenderManifestEntry */
/** @typedef {import("./Compilation").RenderManifestOptions} RenderManifestOptions */
/** @typedef {import("./Compilation").Source} Source */
/** @typedef {import("./ModuleTemplate")} ModuleTemplate */
/** @typedef {import("./javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
/**
* @template T
* @typedef {import("tapable").IfSet<T>} IfSet
*/
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
);
// TODO webpack 6 remove this class
class ChunkTemplate {
/**
* @param {OutputOptions} outputOptions output options
* @param {Compilation} compilation the compilation
*/
constructor(outputOptions, compilation) {
this._outputOptions = outputOptions || {};
this.hooks = Object.freeze({
renderManifest: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(RenderManifestEntry[], RenderManifestOptions): RenderManifestEntry[]} fn function
*/
(options, fn) => {
compilation.hooks.renderManifest.tap(
options,
(entries, options) => {
if (options.chunk.hasRuntime()) return entries;
return fn(entries, options);
}
);
},
"ChunkTemplate.hooks.renderManifest is deprecated (use Compilation.hooks.renderManifest instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_RENDER_MANIFEST"
)
},
modules: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, ModuleTemplate, RenderContext): Source} fn function
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderChunk.tap(options, (source, renderContext) =>
fn(
source,
compilation.moduleTemplates.javascript,
renderContext
)
);
},
"ChunkTemplate.hooks.modules is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderChunk instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_MODULES"
)
},
render: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, ModuleTemplate, RenderContext): Source} fn function
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderChunk.tap(options, (source, renderContext) =>
fn(
source,
compilation.moduleTemplates.javascript,
renderContext
)
);
},
"ChunkTemplate.hooks.render is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderChunk instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_RENDER"
)
},
renderWithEntry: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Chunk): Source} fn function
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.render.tap(options, (source, renderContext) => {
if (
renderContext.chunkGraph.getNumberOfEntryModules(
renderContext.chunk
) === 0 ||
renderContext.chunk.hasRuntime()
) {
return source;
}
return fn(source, renderContext.chunk);
});
},
"ChunkTemplate.hooks.renderWithEntry is deprecated (use JavascriptModulesPlugin.getCompilationHooks().render instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_RENDER_WITH_ENTRY"
)
},
hash: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Hash): void} fn function
*/
(options, fn) => {
compilation.hooks.fullHash.tap(options, fn);
},
"ChunkTemplate.hooks.hash is deprecated (use Compilation.hooks.fullHash instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_HASH"
)
},
hashForChunk: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Hash, Chunk, ChunkHashContext): void} fn function
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.chunkHash.tap(options, (chunk, hash, context) => {
if (chunk.hasRuntime()) return;
fn(hash, chunk, context);
});
},
"ChunkTemplate.hooks.hashForChunk is deprecated (use JavascriptModulesPlugin.getCompilationHooks().chunkHash instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_HASH_FOR_CHUNK"
)
}
});
}
}
Object.defineProperty(ChunkTemplate.prototype, "outputOptions", {
get: util.deprecate(
/**
* @this {ChunkTemplate}
* @returns {OutputOptions} output options
*/
function () {
return this._outputOptions;
},
"ChunkTemplate.outputOptions is deprecated (use Compilation.outputOptions instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_OUTPUT_OPTIONS"
)
});
module.exports = ChunkTemplate;

32
node_modules/webpack/lib/CommentCompilationWarning.js generated vendored Normal file
View file

@ -0,0 +1,32 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("./WebpackError");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
class CommentCompilationWarning extends WebpackError {
/**
* @param {string} message warning message
* @param {DependencyLocation} loc affected lines of code
*/
constructor(message, loc) {
super(message);
this.name = "CommentCompilationWarning";
this.loc = loc;
}
}
makeSerializable(
CommentCompilationWarning,
"webpack/lib/CommentCompilationWarning"
);
module.exports = CommentCompilationWarning;

191
node_modules/webpack/lib/CompatibilityPlugin.js generated vendored Normal file
View file

@ -0,0 +1,191 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const ConstDependency = require("./dependencies/ConstDependency");
/** @typedef {import("estree").CallExpression} CallExpression */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
const nestedWebpackIdentifierTag = Symbol("nested webpack identifier");
const PLUGIN_NAME = "CompatibilityPlugin";
class CompatibilityPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, (parser, parserOptions) => {
if (
parserOptions.browserify !== undefined &&
!parserOptions.browserify
)
return;
parser.hooks.call.for("require").tap(
PLUGIN_NAME,
/**
* @param {CallExpression} expr call expression
* @returns {boolean | void} true when need to handle
*/
expr => {
// support for browserify style require delegator: "require(o, !0)"
if (expr.arguments.length !== 2) return;
const second = parser.evaluateExpression(expr.arguments[1]);
if (!second.isBoolean()) return;
if (second.asBool() !== true) return;
const dep = new ConstDependency(
"require",
/** @type {Range} */ (expr.callee.range)
);
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
];
if (
last.critical &&
last.options &&
last.options.request === "." &&
last.userRequest === "." &&
last.options.recursive
)
parser.state.current.dependencies.pop();
}
parser.state.module.addPresentationalDependency(dep);
return true;
}
);
});
/**
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const handler = parser => {
// Handle nested requires
parser.hooks.preStatement.tap(PLUGIN_NAME, statement => {
if (
statement.type === "FunctionDeclaration" &&
statement.id &&
statement.id.name === RuntimeGlobals.require
) {
const newName = `__nested_webpack_require_${
/** @type {Range} */ (statement.range)[0]
}__`;
parser.tagVariable(
statement.id.name,
nestedWebpackIdentifierTag,
{
name: newName,
declaration: {
updated: false,
loc: statement.id.loc,
range: statement.id.range
}
}
);
return true;
}
});
parser.hooks.pattern
.for(RuntimeGlobals.require)
.tap(PLUGIN_NAME, pattern => {
const newName = `__nested_webpack_require_${
/** @type {Range} */ (pattern.range)[0]
}__`;
parser.tagVariable(pattern.name, nestedWebpackIdentifierTag, {
name: newName,
declaration: {
updated: false,
loc: pattern.loc,
range: pattern.range
}
});
return true;
});
parser.hooks.pattern
.for(RuntimeGlobals.exports)
.tap(PLUGIN_NAME, pattern => {
parser.tagVariable(pattern.name, nestedWebpackIdentifierTag, {
name: "__nested_webpack_exports__",
declaration: {
updated: false,
loc: pattern.loc,
range: pattern.range
}
});
return true;
});
parser.hooks.expression
.for(nestedWebpackIdentifierTag)
.tap(PLUGIN_NAME, expr => {
const { name, declaration } = parser.currentTagData;
if (!declaration.updated) {
const dep = new ConstDependency(name, declaration.range);
dep.loc = declaration.loc;
parser.state.module.addPresentationalDependency(dep);
declaration.updated = true;
}
const dep = new ConstDependency(
name,
/** @type {Range} */ (expr.range)
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
// Handle hashbang
parser.hooks.program.tap(PLUGIN_NAME, (program, comments) => {
if (comments.length === 0) return;
const c = comments[0];
if (c.type === "Line" && /** @type {Range} */ (c.range)[0] === 0) {
if (parser.state.source.slice(0, 2).toString() !== "#!") return;
// this is a hashbang comment
const dep = new ConstDependency("//", 0);
dep.loc = /** @type {DependencyLocation} */ (c.loc);
parser.state.module.addPresentationalDependency(dep);
}
});
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
}
);
}
}
module.exports = CompatibilityPlugin;

5526
node_modules/webpack/lib/Compilation.js generated vendored Normal file

File diff suppressed because it is too large Load diff

1382
node_modules/webpack/lib/Compiler.js generated vendored Normal file

File diff suppressed because it is too large Load diff

18
node_modules/webpack/lib/ConcurrentCompilationError.js generated vendored Normal file
View file

@ -0,0 +1,18 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Maksim Nazarjev @acupofspirt
*/
"use strict";
const WebpackError = require("./WebpackError");
module.exports = class ConcurrentCompilationError extends WebpackError {
constructor() {
super();
this.name = "ConcurrentCompilationError";
this.message =
"You ran Webpack twice. Each instance only supports a single concurrent compilation at a time.";
}
};

537
node_modules/webpack/lib/ConstPlugin.js generated vendored Normal file
View file

@ -0,0 +1,537 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const CachedConstDependency = require("./dependencies/CachedConstDependency");
const ConstDependency = require("./dependencies/ConstDependency");
const { evaluateToString } = require("./javascript/JavascriptParserHelpers");
const { parseResource } = require("./util/identifier");
/** @typedef {import("estree").AssignmentProperty} AssignmentProperty */
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("estree").Identifier} Identifier */
/** @typedef {import("estree").Pattern} Pattern */
/** @typedef {import("estree").SourceLocation} SourceLocation */
/** @typedef {import("estree").Statement} Statement */
/** @typedef {import("estree").Super} Super */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/**
* @param {Set<string>} declarations set of declarations
* @param {Identifier | Pattern} pattern pattern to collect declarations from
*/
const collectDeclaration = (declarations, pattern) => {
const stack = [pattern];
while (stack.length > 0) {
const node = /** @type {Pattern} */ (stack.pop());
switch (node.type) {
case "Identifier":
declarations.add(node.name);
break;
case "ArrayPattern":
for (const element of node.elements) {
if (element) {
stack.push(element);
}
}
break;
case "AssignmentPattern":
stack.push(node.left);
break;
case "ObjectPattern":
for (const property of node.properties) {
stack.push(/** @type {AssignmentProperty} */ (property).value);
}
break;
case "RestElement":
stack.push(node.argument);
break;
}
}
};
/**
* @param {Statement} branch branch to get hoisted declarations from
* @param {boolean} includeFunctionDeclarations whether to include function declarations
* @returns {Array<string>} hoisted declarations
*/
const getHoistedDeclarations = (branch, includeFunctionDeclarations) => {
const declarations = new Set();
/** @type {Array<TODO | null | undefined>} */
const stack = [branch];
while (stack.length > 0) {
const node = stack.pop();
// Some node could be `null` or `undefined`.
if (!node) continue;
switch (node.type) {
// Walk through control statements to look for hoisted declarations.
// Some branches are skipped since they do not allow declarations.
case "BlockStatement":
for (const stmt of node.body) {
stack.push(stmt);
}
break;
case "IfStatement":
stack.push(node.consequent);
stack.push(node.alternate);
break;
case "ForStatement":
stack.push(node.init);
stack.push(node.body);
break;
case "ForInStatement":
case "ForOfStatement":
stack.push(node.left);
stack.push(node.body);
break;
case "DoWhileStatement":
case "WhileStatement":
case "LabeledStatement":
stack.push(node.body);
break;
case "SwitchStatement":
for (const cs of node.cases) {
for (const consequent of cs.consequent) {
stack.push(consequent);
}
}
break;
case "TryStatement":
stack.push(node.block);
if (node.handler) {
stack.push(node.handler.body);
}
stack.push(node.finalizer);
break;
case "FunctionDeclaration":
if (includeFunctionDeclarations) {
collectDeclaration(declarations, /** @type {Identifier} */ (node.id));
}
break;
case "VariableDeclaration":
if (node.kind === "var") {
for (const decl of node.declarations) {
collectDeclaration(declarations, decl.id);
}
}
break;
}
}
return Array.from(declarations);
};
const PLUGIN_NAME = "ConstPlugin";
class ConstPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const cachedParseResource = parseResource.bindCache(compiler.root);
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
compilation.dependencyTemplates.set(
CachedConstDependency,
new CachedConstDependency.Template()
);
/**
* @param {JavascriptParser} parser the parser
*/
const handler = parser => {
parser.hooks.statementIf.tap(PLUGIN_NAME, statement => {
if (parser.scope.isAsmJs) return;
const param = parser.evaluateExpression(statement.test);
const bool = param.asBool();
if (typeof bool === "boolean") {
if (!param.couldHaveSideEffects()) {
const dep = new ConstDependency(
`${bool}`,
/** @type {Range} */ (param.range)
);
dep.loc = /** @type {SourceLocation} */ (statement.loc);
parser.state.module.addPresentationalDependency(dep);
} else {
parser.walkExpression(statement.test);
}
const branchToRemove = bool
? statement.alternate
: statement.consequent;
if (branchToRemove) {
// Before removing the dead branch, the hoisted declarations
// must be collected.
//
// Given the following code:
//
// if (true) f() else g()
// if (false) {
// function f() {}
// const g = function g() {}
// if (someTest) {
// let a = 1
// var x, {y, z} = obj
// }
// } else {
// …
// }
//
// the generated code is:
//
// if (true) f() else {}
// if (false) {
// var f, x, y, z; (in loose mode)
// var x, y, z; (in strict mode)
// } else {
// …
// }
//
// NOTE: When code runs in strict mode, `var` declarations
// are hoisted but `function` declarations don't.
//
const declarations = parser.scope.isStrict
? getHoistedDeclarations(branchToRemove, false)
: getHoistedDeclarations(branchToRemove, true);
const replacement =
declarations.length > 0
? `{ var ${declarations.join(", ")}; }`
: "{}";
const dep = new ConstDependency(
replacement,
/** @type {Range} */ (branchToRemove.range)
);
dep.loc = /** @type {SourceLocation} */ (branchToRemove.loc);
parser.state.module.addPresentationalDependency(dep);
}
return bool;
}
});
parser.hooks.expressionConditionalOperator.tap(
PLUGIN_NAME,
expression => {
if (parser.scope.isAsmJs) return;
const param = parser.evaluateExpression(expression.test);
const bool = param.asBool();
if (typeof bool === "boolean") {
if (!param.couldHaveSideEffects()) {
const dep = new ConstDependency(
` ${bool}`,
/** @type {Range} */ (param.range)
);
dep.loc = /** @type {SourceLocation} */ (expression.loc);
parser.state.module.addPresentationalDependency(dep);
} else {
parser.walkExpression(expression.test);
}
// Expressions do not hoist.
// It is safe to remove the dead branch.
//
// Given the following code:
//
// false ? someExpression() : otherExpression();
//
// the generated code is:
//
// false ? 0 : otherExpression();
//
const branchToRemove = bool
? expression.alternate
: expression.consequent;
const dep = new ConstDependency(
"0",
/** @type {Range} */ (branchToRemove.range)
);
dep.loc = /** @type {SourceLocation} */ (branchToRemove.loc);
parser.state.module.addPresentationalDependency(dep);
return bool;
}
}
);
parser.hooks.expressionLogicalOperator.tap(
PLUGIN_NAME,
expression => {
if (parser.scope.isAsmJs) return;
if (
expression.operator === "&&" ||
expression.operator === "||"
) {
const param = parser.evaluateExpression(expression.left);
const bool = param.asBool();
if (typeof bool === "boolean") {
// Expressions do not hoist.
// It is safe to remove the dead branch.
//
// ------------------------------------------
//
// Given the following code:
//
// falsyExpression() && someExpression();
//
// the generated code is:
//
// falsyExpression() && false;
//
// ------------------------------------------
//
// Given the following code:
//
// truthyExpression() && someExpression();
//
// the generated code is:
//
// true && someExpression();
//
// ------------------------------------------
//
// Given the following code:
//
// truthyExpression() || someExpression();
//
// the generated code is:
//
// truthyExpression() || false;
//
// ------------------------------------------
//
// Given the following code:
//
// falsyExpression() || someExpression();
//
// the generated code is:
//
// false && someExpression();
//
const keepRight =
(expression.operator === "&&" && bool) ||
(expression.operator === "||" && !bool);
if (
!param.couldHaveSideEffects() &&
(param.isBoolean() || keepRight)
) {
// for case like
//
// return'development'===process.env.NODE_ENV&&'foo'
//
// we need a space before the bool to prevent result like
//
// returnfalse&&'foo'
//
const dep = new ConstDependency(
` ${bool}`,
/** @type {Range} */ (param.range)
);
dep.loc = /** @type {SourceLocation} */ (expression.loc);
parser.state.module.addPresentationalDependency(dep);
} else {
parser.walkExpression(expression.left);
}
if (!keepRight) {
const dep = new ConstDependency(
"0",
/** @type {Range} */ (expression.right.range)
);
dep.loc = /** @type {SourceLocation} */ (expression.loc);
parser.state.module.addPresentationalDependency(dep);
}
return keepRight;
}
} else if (expression.operator === "??") {
const param = parser.evaluateExpression(expression.left);
const keepRight = param.asNullish();
if (typeof keepRight === "boolean") {
// ------------------------------------------
//
// Given the following code:
//
// nonNullish ?? someExpression();
//
// the generated code is:
//
// nonNullish ?? 0;
//
// ------------------------------------------
//
// Given the following code:
//
// nullish ?? someExpression();
//
// the generated code is:
//
// null ?? someExpression();
//
if (!param.couldHaveSideEffects() && keepRight) {
// cspell:word returnnull
// for case like
//
// return('development'===process.env.NODE_ENV&&null)??'foo'
//
// we need a space before the bool to prevent result like
//
// returnnull??'foo'
//
const dep = new ConstDependency(
" null",
/** @type {Range} */ (param.range)
);
dep.loc = /** @type {SourceLocation} */ (expression.loc);
parser.state.module.addPresentationalDependency(dep);
} else {
const dep = new ConstDependency(
"0",
/** @type {Range} */ (expression.right.range)
);
dep.loc = /** @type {SourceLocation} */ (expression.loc);
parser.state.module.addPresentationalDependency(dep);
parser.walkExpression(expression.left);
}
return keepRight;
}
}
}
);
parser.hooks.optionalChaining.tap(PLUGIN_NAME, expr => {
/** @type {Expression[]} */
const optionalExpressionsStack = [];
/** @type {Expression | Super} */
let next = expr.expression;
while (
next.type === "MemberExpression" ||
next.type === "CallExpression"
) {
if (next.type === "MemberExpression") {
if (next.optional) {
// SuperNode can not be optional
optionalExpressionsStack.push(
/** @type {Expression} */ (next.object)
);
}
next = next.object;
} else {
if (next.optional) {
// SuperNode can not be optional
optionalExpressionsStack.push(
/** @type {Expression} */ (next.callee)
);
}
next = next.callee;
}
}
while (optionalExpressionsStack.length) {
const expression = optionalExpressionsStack.pop();
const evaluated = parser.evaluateExpression(
/** @type {Expression} */ (expression)
);
if (evaluated.asNullish()) {
// ------------------------------------------
//
// Given the following code:
//
// nullishMemberChain?.a.b();
//
// the generated code is:
//
// undefined;
//
// ------------------------------------------
//
const dep = new ConstDependency(
" undefined",
/** @type {Range} */ (expr.range)
);
dep.loc = /** @type {SourceLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
}
}
});
parser.hooks.evaluateIdentifier
.for("__resourceQuery")
.tap(PLUGIN_NAME, expr => {
if (parser.scope.isAsmJs) return;
if (!parser.state.module) return;
return evaluateToString(
cachedParseResource(parser.state.module.resource).query
)(expr);
});
parser.hooks.expression
.for("__resourceQuery")
.tap(PLUGIN_NAME, expr => {
if (parser.scope.isAsmJs) return;
if (!parser.state.module) return;
const dep = new CachedConstDependency(
JSON.stringify(
cachedParseResource(parser.state.module.resource).query
),
/** @type {Range} */ (expr.range),
"__resourceQuery"
);
dep.loc = /** @type {SourceLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
parser.hooks.evaluateIdentifier
.for("__resourceFragment")
.tap(PLUGIN_NAME, expr => {
if (parser.scope.isAsmJs) return;
if (!parser.state.module) return;
return evaluateToString(
cachedParseResource(parser.state.module.resource).fragment
)(expr);
});
parser.hooks.expression
.for("__resourceFragment")
.tap(PLUGIN_NAME, expr => {
if (parser.scope.isAsmJs) return;
if (!parser.state.module) return;
const dep = new CachedConstDependency(
JSON.stringify(
cachedParseResource(parser.state.module.resource).fragment
),
/** @type {Range} */ (expr.range),
"__resourceFragment"
);
dep.loc = /** @type {SourceLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
}
);
}
}
module.exports = ConstPlugin;

32
node_modules/webpack/lib/ContextExclusionPlugin.js generated vendored Normal file
View file

@ -0,0 +1,32 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./ContextModuleFactory")} ContextModuleFactory */
class ContextExclusionPlugin {
/**
* @param {RegExp} negativeMatcher Matcher regular expression
*/
constructor(negativeMatcher) {
this.negativeMatcher = negativeMatcher;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.contextModuleFactory.tap("ContextExclusionPlugin", cmf => {
cmf.hooks.contextModuleFiles.tap("ContextExclusionPlugin", files =>
files.filter(filePath => !this.negativeMatcher.test(filePath))
);
});
}
}
module.exports = ContextExclusionPlugin;

1254
node_modules/webpack/lib/ContextModule.js generated vendored Normal file

File diff suppressed because it is too large Load diff

481
node_modules/webpack/lib/ContextModuleFactory.js generated vendored Normal file
View file

@ -0,0 +1,481 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const { AsyncSeriesWaterfallHook, SyncWaterfallHook } = require("tapable");
const ContextModule = require("./ContextModule");
const ModuleFactory = require("./ModuleFactory");
const ContextElementDependency = require("./dependencies/ContextElementDependency");
const LazySet = require("./util/LazySet");
const { cachedSetProperty } = require("./util/cleverMerge");
const { createFakeHook } = require("./util/deprecation");
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").ModuleFactoryResult} ModuleFactoryResult */
/** @typedef {import("./ResolverFactory")} ResolverFactory */
/** @typedef {import("./dependencies/ContextDependency")} ContextDependency */
/** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
/**
* @template T
* @typedef {import("./util/deprecation").FakeHook<T>} FakeHook<T>
*/
/** @typedef {import("./util/fs").IStats} IStats */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {{ context: string, request: string }} ContextAlternativeRequest */
const EMPTY_RESOLVE_OPTIONS = {};
module.exports = class ContextModuleFactory extends ModuleFactory {
/**
* @param {ResolverFactory} resolverFactory resolverFactory
*/
constructor(resolverFactory) {
super();
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[], ContextModuleOptions]>} */
const alternativeRequests = new AsyncSeriesWaterfallHook([
"modules",
"options"
]);
this.hooks = Object.freeze({
/** @type {AsyncSeriesWaterfallHook<[TODO]>} */
beforeResolve: new AsyncSeriesWaterfallHook(["data"]),
/** @type {AsyncSeriesWaterfallHook<[TODO]>} */
afterResolve: new AsyncSeriesWaterfallHook(["data"]),
/** @type {SyncWaterfallHook<[string[]]>} */
contextModuleFiles: new SyncWaterfallHook(["files"]),
/** @type {FakeHook<Pick<AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>, "tap" | "tapAsync" | "tapPromise" | "name">>} */
alternatives: createFakeHook(
{
name: "alternatives",
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["intercept"]} */
intercept: interceptor => {
throw new Error(
"Intercepting fake hook ContextModuleFactory.hooks.alternatives is not possible, use ContextModuleFactory.hooks.alternativeRequests instead"
);
},
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["tap"]} */
tap: (options, fn) => {
alternativeRequests.tap(options, fn);
},
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["tapAsync"]} */
tapAsync: (options, fn) => {
alternativeRequests.tapAsync(options, (items, _options, callback) =>
fn(items, callback)
);
},
/** @type {AsyncSeriesWaterfallHook<[ContextAlternativeRequest[]]>["tapPromise"]} */
tapPromise: (options, fn) => {
alternativeRequests.tapPromise(options, fn);
}
},
"ContextModuleFactory.hooks.alternatives has deprecated in favor of ContextModuleFactory.hooks.alternativeRequests with an additional options argument.",
"DEP_WEBPACK_CONTEXT_MODULE_FACTORY_ALTERNATIVES"
),
alternativeRequests
});
this.resolverFactory = resolverFactory;
}
/**
* @param {ModuleFactoryCreateData} data data object
* @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback
* @returns {void}
*/
create(data, callback) {
const context = data.context;
const dependencies = data.dependencies;
const resolveOptions = data.resolveOptions;
const dependency = /** @type {ContextDependency} */ (dependencies[0]);
const fileDependencies = new LazySet();
const missingDependencies = new LazySet();
const contextDependencies = new LazySet();
this.hooks.beforeResolve.callAsync(
{
context,
dependencies,
layer: data.contextInfo.issuerLayer,
resolveOptions,
fileDependencies,
missingDependencies,
contextDependencies,
...dependency.options
},
(err, beforeResolveResult) => {
if (err) {
return callback(err, {
fileDependencies,
missingDependencies,
contextDependencies
});
}
// Ignored
if (!beforeResolveResult) {
return callback(null, {
fileDependencies,
missingDependencies,
contextDependencies
});
}
const context = beforeResolveResult.context;
const request = beforeResolveResult.request;
const resolveOptions = beforeResolveResult.resolveOptions;
let loaders;
let resource;
let loadersPrefix = "";
const idx = request.lastIndexOf("!");
if (idx >= 0) {
let loadersRequest = request.slice(0, idx + 1);
let i;
for (
i = 0;
i < loadersRequest.length && loadersRequest[i] === "!";
i++
) {
loadersPrefix += "!";
}
loadersRequest = loadersRequest
.slice(i)
.replace(/!+$/, "")
.replace(/!!+/g, "!");
loaders = loadersRequest === "" ? [] : loadersRequest.split("!");
resource = request.slice(idx + 1);
} else {
loaders = [];
resource = request;
}
const contextResolver = this.resolverFactory.get(
"context",
dependencies.length > 0
? cachedSetProperty(
resolveOptions || EMPTY_RESOLVE_OPTIONS,
"dependencyType",
dependencies[0].category
)
: resolveOptions
);
const loaderResolver = this.resolverFactory.get("loader");
asyncLib.parallel(
[
callback => {
const results = /** @type ResolveRequest[] */ ([]);
/**
* @param {ResolveRequest} obj obj
* @returns {void}
*/
const yield_ = obj => {
results.push(obj);
};
contextResolver.resolve(
{},
context,
resource,
{
fileDependencies,
missingDependencies,
contextDependencies,
yield: yield_
},
err => {
if (err) return callback(err);
callback(null, results);
}
);
},
callback => {
asyncLib.map(
loaders,
(loader, callback) => {
loaderResolver.resolve(
{},
context,
loader,
{
fileDependencies,
missingDependencies,
contextDependencies
},
(err, result) => {
if (err) return callback(err);
callback(null, /** @type {string} */ (result));
}
);
},
callback
);
}
],
(err, result) => {
if (err) {
return callback(err, {
fileDependencies,
missingDependencies,
contextDependencies
});
}
let [contextResult, loaderResult] =
/** @type {[ResolveRequest[], string[]]} */ (result);
if (contextResult.length > 1) {
const first = contextResult[0];
contextResult = contextResult.filter(r => r.path);
if (contextResult.length === 0) contextResult.push(first);
}
this.hooks.afterResolve.callAsync(
{
addon:
loadersPrefix +
loaderResult.join("!") +
(loaderResult.length > 0 ? "!" : ""),
resource:
contextResult.length > 1
? contextResult.map(r => r.path)
: contextResult[0].path,
resolveDependencies: this.resolveDependencies.bind(this),
resourceQuery: contextResult[0].query,
resourceFragment: contextResult[0].fragment,
...beforeResolveResult
},
(err, result) => {
if (err) {
return callback(err, {
fileDependencies,
missingDependencies,
contextDependencies
});
}
// Ignored
if (!result) {
return callback(null, {
fileDependencies,
missingDependencies,
contextDependencies
});
}
return callback(null, {
module: new ContextModule(result.resolveDependencies, result),
fileDependencies,
missingDependencies,
contextDependencies
});
}
);
}
);
}
);
}
/**
* @param {InputFileSystem} fs file system
* @param {ContextModuleOptions} options options
* @param {ResolveDependenciesCallback} callback callback function
* @returns {void}
*/
resolveDependencies(fs, options, callback) {
const cmf = this;
const {
resource,
resourceQuery,
resourceFragment,
recursive,
regExp,
include,
exclude,
referencedExports,
category,
typePrefix,
attributes
} = options;
if (!regExp || !resource) return callback(null, []);
/**
* @param {string} ctx context
* @param {string} directory directory
* @param {Set<string>} visited visited
* @param {ResolveDependenciesCallback} callback callback
*/
const addDirectoryChecked = (ctx, directory, visited, callback) => {
/** @type {NonNullable<InputFileSystem["realpath"]>} */
(fs.realpath)(directory, (err, _realPath) => {
if (err) return callback(err);
const realPath = /** @type {string} */ (_realPath);
if (visited.has(realPath)) return callback(null, []);
/** @type {Set<string> | undefined} */
let recursionStack;
addDirectory(
ctx,
directory,
(_, dir, callback) => {
if (recursionStack === undefined) {
recursionStack = new Set(visited);
recursionStack.add(realPath);
}
addDirectoryChecked(ctx, dir, recursionStack, callback);
},
callback
);
});
};
/**
* @param {string} ctx context
* @param {string} directory directory
* @param {function(string, string, function(): void): void} addSubDirectory addSubDirectoryFn
* @param {ResolveDependenciesCallback} callback callback
*/
const addDirectory = (ctx, directory, addSubDirectory, callback) => {
fs.readdir(directory, (err, files) => {
if (err) return callback(err);
const processedFiles = cmf.hooks.contextModuleFiles.call(
/** @type {string[]} */ (files).map(file => file.normalize("NFC"))
);
if (!processedFiles || processedFiles.length === 0)
return callback(null, []);
asyncLib.map(
processedFiles.filter(p => p.indexOf(".") !== 0),
(segment, callback) => {
const subResource = join(fs, directory, segment);
if (!exclude || !subResource.match(exclude)) {
fs.stat(subResource, (err, _stat) => {
if (err) {
if (err.code === "ENOENT") {
// ENOENT is ok here because the file may have been deleted between
// the readdir and stat calls.
return callback();
}
return callback(err);
}
const stat = /** @type {IStats} */ (_stat);
if (stat.isDirectory()) {
if (!recursive) return callback();
addSubDirectory(ctx, subResource, callback);
} else if (
stat.isFile() &&
(!include || subResource.match(include))
) {
/** @type {{ context: string, request: string }} */
const obj = {
context: ctx,
request: `.${subResource.slice(ctx.length).replace(/\\/g, "/")}`
};
this.hooks.alternativeRequests.callAsync(
[obj],
options,
(err, alternatives) => {
if (err) return callback(err);
callback(
null,
/** @type {ContextAlternativeRequest[]} */
(alternatives)
.filter(obj =>
regExp.test(/** @type {string} */ (obj.request))
)
.map(obj => {
const dep = new ContextElementDependency(
`${obj.request}${resourceQuery}${resourceFragment}`,
obj.request,
typePrefix,
/** @type {string} */
(category),
referencedExports,
/** @type {TODO} */
(obj.context),
attributes
);
dep.optional = true;
return dep;
})
);
}
);
} else {
callback();
}
});
} else {
callback();
}
},
(err, result) => {
if (err) return callback(err);
if (!result) return callback(null, []);
const flattenedResult = [];
for (const item of result) {
if (item) flattenedResult.push(...item);
}
callback(null, flattenedResult);
}
);
});
};
/**
* @param {string} ctx context
* @param {string} dir dir
* @param {ResolveDependenciesCallback} callback callback
* @returns {void}
*/
const addSubDirectory = (ctx, dir, callback) =>
addDirectory(ctx, dir, addSubDirectory, callback);
/**
* @param {string} resource resource
* @param {ResolveDependenciesCallback} callback callback
*/
const visitResource = (resource, callback) => {
if (typeof fs.realpath === "function") {
addDirectoryChecked(resource, resource, new Set(), callback);
} else {
addDirectory(resource, resource, addSubDirectory, callback);
}
};
if (typeof resource === "string") {
visitResource(resource, callback);
} else {
asyncLib.map(resource, visitResource, (err, _result) => {
if (err) return callback(err);
const result = /** @type {ContextElementDependency[][]} */ (_result);
// result dependencies should have unique userRequest
// ordered by resolve result
/** @type {Set<string>} */
const temp = new Set();
/** @type {ContextElementDependency[]} */
const res = [];
for (let i = 0; i < result.length; i++) {
const inner = result[i];
for (const el of inner) {
if (temp.has(el.userRequest)) continue;
res.push(el);
temp.add(el.userRequest);
}
}
callback(null, res);
});
}
}
};

172
node_modules/webpack/lib/ContextReplacementPlugin.js generated vendored Normal file
View file

@ -0,0 +1,172 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ContextElementDependency = require("./dependencies/ContextElementDependency");
const { join } = require("./util/fs");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
class ContextReplacementPlugin {
/**
* @param {RegExp} resourceRegExp A regular expression that determines which files will be selected
* @param {TODO=} newContentResource A new resource to replace the match
* @param {TODO=} newContentRecursive If true, all subdirectories are searched for matches
* @param {RegExp=} newContentRegExp A regular expression that determines which files will be selected
*/
constructor(
resourceRegExp,
newContentResource,
newContentRecursive,
newContentRegExp
) {
this.resourceRegExp = resourceRegExp;
if (typeof newContentResource === "function") {
this.newContentCallback = newContentResource;
} else if (
typeof newContentResource === "string" &&
typeof newContentRecursive === "object"
) {
this.newContentResource = newContentResource;
this.newContentCreateContextMap = (fs, callback) => {
callback(null, newContentRecursive);
};
} else if (
typeof newContentResource === "string" &&
typeof newContentRecursive === "function"
) {
this.newContentResource = newContentResource;
this.newContentCreateContextMap = newContentRecursive;
} else {
if (typeof newContentResource !== "string") {
newContentRegExp = newContentRecursive;
newContentRecursive = newContentResource;
newContentResource = undefined;
}
if (typeof newContentRecursive !== "boolean") {
newContentRegExp = newContentRecursive;
newContentRecursive = undefined;
}
this.newContentResource = newContentResource;
this.newContentRecursive = newContentRecursive;
this.newContentRegExp = newContentRegExp;
}
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const resourceRegExp = this.resourceRegExp;
const newContentCallback = this.newContentCallback;
const newContentResource = this.newContentResource;
const newContentRecursive = this.newContentRecursive;
const newContentRegExp = this.newContentRegExp;
const newContentCreateContextMap = this.newContentCreateContextMap;
compiler.hooks.contextModuleFactory.tap("ContextReplacementPlugin", cmf => {
cmf.hooks.beforeResolve.tap("ContextReplacementPlugin", result => {
if (!result) return;
if (resourceRegExp.test(result.request)) {
if (newContentResource !== undefined) {
result.request = newContentResource;
}
if (newContentRecursive !== undefined) {
result.recursive = newContentRecursive;
}
if (newContentRegExp !== undefined) {
result.regExp = newContentRegExp;
}
if (typeof newContentCallback === "function") {
newContentCallback(result);
} else {
for (const d of result.dependencies) {
if (d.critical) d.critical = false;
}
}
}
return result;
});
cmf.hooks.afterResolve.tap("ContextReplacementPlugin", result => {
if (!result) return;
if (resourceRegExp.test(result.resource)) {
if (newContentResource !== undefined) {
if (
newContentResource.startsWith("/") ||
(newContentResource.length > 1 && newContentResource[1] === ":")
) {
result.resource = newContentResource;
} else {
result.resource = join(
/** @type {InputFileSystem} */ (compiler.inputFileSystem),
result.resource,
newContentResource
);
}
}
if (newContentRecursive !== undefined) {
result.recursive = newContentRecursive;
}
if (newContentRegExp !== undefined) {
result.regExp = newContentRegExp;
}
if (typeof newContentCreateContextMap === "function") {
result.resolveDependencies =
createResolveDependenciesFromContextMap(
newContentCreateContextMap
);
}
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
);
}
} else {
for (const d of result.dependencies) {
if (d.critical) d.critical = false;
}
}
}
return result;
});
});
}
}
const createResolveDependenciesFromContextMap = createContextMap => {
const resolveDependenciesFromContextMap = (fs, options, callback) => {
createContextMap(fs, (err, map) => {
if (err) return callback(err);
const dependencies = Object.keys(map).map(
key =>
new ContextElementDependency(
map[key] + options.resourceQuery + options.resourceFragment,
key,
options.category,
options.referencedExports
)
);
callback(null, dependencies);
});
};
return resolveDependenciesFromContextMap;
};
module.exports = ContextReplacementPlugin;

707
node_modules/webpack/lib/DefinePlugin.js generated vendored Normal file
View file

@ -0,0 +1,707 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_ESM,
JAVASCRIPT_MODULE_TYPE_DYNAMIC
} = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const WebpackError = require("./WebpackError");
const ConstDependency = require("./dependencies/ConstDependency");
const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression");
const {
evaluateToString,
toConstantDependency
} = require("./javascript/JavascriptParserHelpers");
const createHash = require("./util/createHash");
/** @typedef {import("estree").Expression} Expression */
/** @typedef {import("./Compilation").ValueCacheVersion} ValueCacheVersion */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").DestructuringAssignmentProperty} DestructuringAssignmentProperty */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
/** @typedef {import("./logging/Logger").Logger} Logger */
/** @typedef {import("./util/createHash").Algorithm} Algorithm */
/** @typedef {null|undefined|RegExp|Function|string|number|boolean|bigint|undefined} CodeValuePrimitive */
/** @typedef {RecursiveArrayOrRecord<CodeValuePrimitive|RuntimeValue>} CodeValue */
/**
* @typedef {object} RuntimeValueOptions
* @property {string[]=} fileDependencies
* @property {string[]=} contextDependencies
* @property {string[]=} missingDependencies
* @property {string[]=} buildDependencies
* @property {string|function(): string=} version
*/
/** @typedef {function({ module: NormalModule, key: string, readonly version: ValueCacheVersion }): CodeValuePrimitive} GeneratorFn */
class RuntimeValue {
/**
* @param {GeneratorFn} fn generator function
* @param {true | string[] | RuntimeValueOptions=} options options
*/
constructor(fn, options) {
this.fn = fn;
if (Array.isArray(options)) {
options = {
fileDependencies: options
};
}
this.options = options || {};
}
get fileDependencies() {
return this.options === true ? true : this.options.fileDependencies;
}
/**
* @param {JavascriptParser} parser the parser
* @param {Map<string, ValueCacheVersion>} valueCacheVersions valueCacheVersions
* @param {string} key the defined key
* @returns {CodeValuePrimitive} code
*/
exec(parser, valueCacheVersions, key) {
const buildInfo = /** @type {BuildInfo} */ (parser.state.module.buildInfo);
if (this.options === true) {
buildInfo.cacheable = false;
} else {
if (this.options.fileDependencies) {
for (const dep of this.options.fileDependencies) {
/** @type {NonNullable<BuildInfo["fileDependencies"]>} */
(buildInfo.fileDependencies).add(dep);
}
}
if (this.options.contextDependencies) {
for (const dep of this.options.contextDependencies) {
/** @type {NonNullable<BuildInfo["contextDependencies"]>} */
(buildInfo.contextDependencies).add(dep);
}
}
if (this.options.missingDependencies) {
for (const dep of this.options.missingDependencies) {
/** @type {NonNullable<BuildInfo["missingDependencies"]>} */
(buildInfo.missingDependencies).add(dep);
}
}
if (this.options.buildDependencies) {
for (const dep of this.options.buildDependencies) {
/** @type {NonNullable<BuildInfo["buildDependencies"]>} */
(buildInfo.buildDependencies).add(dep);
}
}
}
return this.fn({
module: parser.state.module,
key,
get version() {
return valueCacheVersions.get(VALUE_DEP_PREFIX + key);
}
});
}
getCacheVersion() {
return this.options === true
? undefined
: (typeof this.options.version === "function"
? this.options.version()
: this.options.version) || "unset";
}
}
/**
* @param {Set<DestructuringAssignmentProperty> | undefined} properties properties
* @returns {Set<string> | undefined} used keys
*/
function getObjKeys(properties) {
if (!properties) return;
return new Set([...properties].map(p => p.id));
}
/** @typedef {Set<string> | null} ObjKeys */
/** @typedef {boolean | undefined | null} AsiSafe */
/**
* @param {any[]|{[k: string]: any}} obj obj
* @param {JavascriptParser} parser Parser
* @param {Map<string, ValueCacheVersion>} valueCacheVersions valueCacheVersions
* @param {string} key the defined key
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {Logger} logger the logger object
* @param {AsiSafe=} asiSafe asi safe (undefined: unknown, null: unneeded)
* @param {ObjKeys=} objKeys used keys
* @returns {string} code converted to string that evaluates
*/
const stringifyObj = (
obj,
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
asiSafe,
objKeys
) => {
let code;
const arr = Array.isArray(obj);
if (arr) {
code = `[${
/** @type {any[]} */ (obj)
.map(code =>
toCode(
code,
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
null
)
)
.join(",")
}]`;
} else {
let keys = Object.keys(obj);
if (objKeys) {
keys = objKeys.size === 0 ? [] : keys.filter(k => objKeys.has(k));
}
code = `{${keys
.map(key => {
const code = /** @type {{[k: string]: any}} */ (obj)[key];
return `${JSON.stringify(key)}:${toCode(
code,
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
null
)}`;
})
.join(",")}}`;
}
switch (asiSafe) {
case null:
return code;
case true:
return arr ? code : `(${code})`;
case false:
return arr ? `;${code}` : `;(${code})`;
default:
return `/*#__PURE__*/Object(${code})`;
}
};
/**
* Convert code to a string that evaluates
* @param {CodeValue} code Code to evaluate
* @param {JavascriptParser} parser Parser
* @param {Map<string, ValueCacheVersion>} valueCacheVersions valueCacheVersions
* @param {string} key the defined key
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {Logger} logger the logger object
* @param {boolean | undefined | null=} asiSafe asi safe (undefined: unknown, null: unneeded)
* @param {ObjKeys=} objKeys used keys
* @returns {string} code converted to string that evaluates
*/
const toCode = (
code,
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
asiSafe,
objKeys
) => {
const transformToCode = () => {
if (code === null) {
return "null";
}
if (code === undefined) {
return "undefined";
}
if (Object.is(code, -0)) {
return "-0";
}
if (code instanceof RuntimeValue) {
return toCode(
code.exec(parser, valueCacheVersions, key),
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
asiSafe
);
}
if (code instanceof RegExp && code.toString) {
return code.toString();
}
if (typeof code === "function" && code.toString) {
return `(${code.toString()})`;
}
if (typeof code === "object") {
return stringifyObj(
code,
parser,
valueCacheVersions,
key,
runtimeTemplate,
logger,
asiSafe,
objKeys
);
}
if (typeof code === "bigint") {
return runtimeTemplate.supportsBigIntLiteral()
? `${code}n`
: `BigInt("${code}")`;
}
return `${code}`;
};
const strCode = transformToCode();
logger.debug(`Replaced "${key}" with "${strCode}"`);
return strCode;
};
/**
* @param {CodeValue} code code
* @returns {string | undefined} result
*/
const toCacheVersion = code => {
if (code === null) {
return "null";
}
if (code === undefined) {
return "undefined";
}
if (Object.is(code, -0)) {
return "-0";
}
if (code instanceof RuntimeValue) {
return code.getCacheVersion();
}
if (code instanceof RegExp && code.toString) {
return code.toString();
}
if (typeof code === "function" && code.toString) {
return `(${code.toString()})`;
}
if (typeof code === "object") {
const items = Object.keys(code).map(key => ({
key,
value: toCacheVersion(/** @type {Record<string, any>} */ (code)[key])
}));
if (items.some(({ value }) => value === undefined)) return;
return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`;
}
if (typeof code === "bigint") {
return `${code}n`;
}
return `${code}`;
};
const PLUGIN_NAME = "DefinePlugin";
const VALUE_DEP_PREFIX = `webpack/${PLUGIN_NAME} `;
const VALUE_DEP_MAIN = `webpack/${PLUGIN_NAME}_hash`;
const TYPEOF_OPERATOR_REGEXP = /^typeof\s+/;
const WEBPACK_REQUIRE_FUNCTION_REGEXP = new RegExp(
`${RuntimeGlobals.require}\\s*(!?\\.)`
);
const WEBPACK_REQUIRE_IDENTIFIER_REGEXP = new RegExp(RuntimeGlobals.require);
class DefinePlugin {
/**
* Create a new define plugin
* @param {Record<string, CodeValue>} definitions A map of global object definitions
*/
constructor(definitions) {
this.definitions = definitions;
}
/**
* @param {GeneratorFn} fn generator function
* @param {true | string[] | RuntimeValueOptions=} options options
* @returns {RuntimeValue} runtime value
*/
static runtimeValue(fn, options) {
return new RuntimeValue(fn, options);
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const definitions = this.definitions;
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
const logger = compilation.getLogger("webpack.DefinePlugin");
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
const { runtimeTemplate } = compilation;
const mainHash = createHash(
/** @type {Algorithm} */
(compilation.outputOptions.hashFunction)
);
mainHash.update(
/** @type {string} */
(compilation.valueCacheVersions.get(VALUE_DEP_MAIN)) || ""
);
/**
* Handler
* @param {JavascriptParser} parser Parser
* @returns {void}
*/
const handler = parser => {
const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN);
parser.hooks.program.tap(PLUGIN_NAME, () => {
const buildInfo = /** @type {BuildInfo} */ (
parser.state.module.buildInfo
);
if (!buildInfo.valueDependencies)
buildInfo.valueDependencies = new Map();
buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);
});
/**
* @param {string} key key
*/
const addValueDependency = key => {
const buildInfo =
/** @type {BuildInfo} */
(parser.state.module.buildInfo);
/** @type {NonNullable<BuildInfo["valueDependencies"]>} */
(buildInfo.valueDependencies).set(
VALUE_DEP_PREFIX + key,
compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key)
);
};
/**
* @template {Function} T
* @param {string} key key
* @param {T} fn fn
* @returns {function(TODO): TODO} result
*/
const withValueDependency =
(key, fn) =>
(...args) => {
addValueDependency(key);
return fn(...args);
};
/**
* Walk definitions
* @param {Record<string, CodeValue>} definitions Definitions map
* @param {string} prefix Prefix string
* @returns {void}
*/
const walkDefinitions = (definitions, prefix) => {
for (const key of Object.keys(definitions)) {
const code = definitions[key];
if (
code &&
typeof code === "object" &&
!(code instanceof RuntimeValue) &&
!(code instanceof RegExp)
) {
walkDefinitions(
/** @type {Record<string, CodeValue>} */ (code),
`${prefix + key}.`
);
applyObjectDefine(prefix + key, code);
continue;
}
applyDefineKey(prefix, key);
applyDefine(prefix + key, code);
}
};
/**
* Apply define key
* @param {string} prefix Prefix
* @param {string} key Key
* @returns {void}
*/
const applyDefineKey = (prefix, key) => {
const splittedKey = key.split(".");
for (const [i, _] of splittedKey.slice(1).entries()) {
const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
parser.hooks.canRename.for(fullKey).tap(PLUGIN_NAME, () => {
addValueDependency(key);
return true;
});
}
};
/**
* Apply Code
* @param {string} key Key
* @param {CodeValue} code Code
* @returns {void}
*/
const applyDefine = (key, code) => {
const originalKey = key;
const isTypeof = TYPEOF_OPERATOR_REGEXP.test(key);
if (isTypeof) key = key.replace(TYPEOF_OPERATOR_REGEXP, "");
let recurse = false;
let recurseTypeof = false;
if (!isTypeof) {
parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
addValueDependency(originalKey);
return true;
});
parser.hooks.evaluateIdentifier
.for(key)
.tap(PLUGIN_NAME, expr => {
/**
* this is needed in case there is a recursion in the DefinePlugin
* to prevent an endless recursion
* e.g.: new DefinePlugin({
* "a": "b",
* "b": "a"
* });
*/
if (recurse) return;
addValueDependency(originalKey);
recurse = true;
const res = parser.evaluate(
toCode(
code,
parser,
compilation.valueCacheVersions,
key,
runtimeTemplate,
logger,
null
)
);
recurse = false;
res.setRange(/** @type {Range} */ (expr.range));
return res;
});
parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
addValueDependency(originalKey);
let strCode = toCode(
code,
parser,
compilation.valueCacheVersions,
originalKey,
runtimeTemplate,
logger,
!parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
null
);
if (parser.scope.inShorthand) {
strCode = `${parser.scope.inShorthand}:${strCode}`;
}
if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.require
])(expr);
} else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.requireScope
])(expr);
}
return toConstantDependency(parser, strCode)(expr);
});
}
parser.hooks.evaluateTypeof.for(key).tap(PLUGIN_NAME, expr => {
/**
* this is needed in case there is a recursion in the DefinePlugin
* to prevent an endless recursion
* e.g.: new DefinePlugin({
* "typeof a": "typeof b",
* "typeof b": "typeof a"
* });
*/
if (recurseTypeof) return;
recurseTypeof = true;
addValueDependency(originalKey);
const codeCode = toCode(
code,
parser,
compilation.valueCacheVersions,
originalKey,
runtimeTemplate,
logger,
null
);
const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
const res = parser.evaluate(typeofCode);
recurseTypeof = false;
res.setRange(/** @type {Range} */ (expr.range));
return res;
});
parser.hooks.typeof.for(key).tap(PLUGIN_NAME, expr => {
addValueDependency(originalKey);
const codeCode = toCode(
code,
parser,
compilation.valueCacheVersions,
originalKey,
runtimeTemplate,
logger,
null
);
const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
const res = parser.evaluate(typeofCode);
if (!res.isString()) return;
return toConstantDependency(
parser,
JSON.stringify(res.string)
).bind(parser)(expr);
});
};
/**
* Apply Object
* @param {string} key Key
* @param {object} obj Object
* @returns {void}
*/
const applyObjectDefine = (key, obj) => {
parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
addValueDependency(key);
return true;
});
parser.hooks.evaluateIdentifier.for(key).tap(PLUGIN_NAME, expr => {
addValueDependency(key);
return new BasicEvaluatedExpression()
.setTruthy()
.setSideEffects(false)
.setRange(/** @type {Range} */ (expr.range));
});
parser.hooks.evaluateTypeof
.for(key)
.tap(
PLUGIN_NAME,
withValueDependency(key, evaluateToString("object"))
);
parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
addValueDependency(key);
let strCode = stringifyObj(
obj,
parser,
compilation.valueCacheVersions,
key,
runtimeTemplate,
logger,
!parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
getObjKeys(parser.destructuringAssignmentPropertiesFor(expr))
);
if (parser.scope.inShorthand) {
strCode = `${parser.scope.inShorthand}:${strCode}`;
}
if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.require
])(expr);
} else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
return toConstantDependency(parser, strCode, [
RuntimeGlobals.requireScope
])(expr);
}
return toConstantDependency(parser, strCode)(expr);
});
parser.hooks.typeof
.for(key)
.tap(
PLUGIN_NAME,
withValueDependency(
key,
toConstantDependency(parser, JSON.stringify("object"))
)
);
};
walkDefinitions(definitions, "");
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
/**
* Walk definitions
* @param {Record<string, CodeValue>} definitions Definitions map
* @param {string} prefix Prefix string
* @returns {void}
*/
const walkDefinitionsForValues = (definitions, prefix) => {
for (const key of Object.keys(definitions)) {
const code = definitions[key];
const version = toCacheVersion(code);
const name = VALUE_DEP_PREFIX + prefix + key;
mainHash.update(`|${prefix}${key}`);
const oldVersion = compilation.valueCacheVersions.get(name);
if (oldVersion === undefined) {
compilation.valueCacheVersions.set(name, version);
} else if (oldVersion !== version) {
const warning = new WebpackError(
`${PLUGIN_NAME}\nConflicting values for '${prefix + key}'`
);
warning.details = `'${oldVersion}' !== '${version}'`;
warning.hideStack = true;
compilation.warnings.push(warning);
}
if (
code &&
typeof code === "object" &&
!(code instanceof RuntimeValue) &&
!(code instanceof RegExp)
) {
walkDefinitionsForValues(
/** @type {Record<string, CodeValue>} */ (code),
`${prefix + key}.`
);
}
}
};
walkDefinitionsForValues(definitions, "");
compilation.valueCacheVersions.set(
VALUE_DEP_MAIN,
/** @type {string} */ (mainHash.digest("hex").slice(0, 8))
);
}
);
}
}
module.exports = DefinePlugin;

262
node_modules/webpack/lib/DelegatedModule.js generated vendored Normal file
View file

@ -0,0 +1,262 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { OriginalSource, RawSource } = require("webpack-sources");
const Module = require("./Module");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
const StaticExportsDependency = require("./dependencies/StaticExportsDependency");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./LibManifestPlugin").ManifestModuleData} ManifestModuleData */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").SourceContext} SourceContext */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @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("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {string} SourceRequest */
/** @typedef {"require" | "object"} Type */
/** @typedef {TODO} Data */
const TYPES = new Set(["javascript"]);
const RUNTIME_REQUIREMENTS = new Set([
RuntimeGlobals.module,
RuntimeGlobals.require
]);
class DelegatedModule extends Module {
/**
* @param {SourceRequest} sourceRequest source request
* @param {Data} data data
* @param {Type} type type
* @param {string} userRequest user request
* @param {string | Module} originalRequest original request
*/
constructor(sourceRequest, data, type, userRequest, originalRequest) {
super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
// Info from Factory
this.sourceRequest = sourceRequest;
this.request = data.id;
this.delegationType = type;
this.userRequest = userRequest;
this.originalRequest = originalRequest;
/** @type {ManifestModuleData | undefined} */
this.delegateData = data;
// Build info
this.delegatedSourceDependency = undefined;
}
/**
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
}
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
libIdent(options) {
return typeof this.originalRequest === "string"
? this.originalRequest
: this.originalRequest.libIdent(options);
}
/**
* @returns {string} a unique identifier of the module
*/
identifier() {
return `delegated ${JSON.stringify(this.request)} from ${
this.sourceRequest
}`;
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return `delegated ${this.userRequest} from ${this.sourceRequest}`;
}
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
return callback(null, !this.buildMeta);
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
const delegateData = /** @type {ManifestModuleData} */ (this.delegateData);
this.buildMeta = { ...delegateData.buildMeta };
this.buildInfo = {};
this.dependencies.length = 0;
this.delegatedSourceDependency = new DelegatedSourceDependency(
this.sourceRequest
);
this.addDependency(this.delegatedSourceDependency);
this.addDependency(
new StaticExportsDependency(delegateData.exports || true, false)
);
callback();
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) {
const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]);
const sourceModule = moduleGraph.getModule(dep);
let str;
if (!sourceModule) {
str = runtimeTemplate.throwMissingModuleErrorBlock({
request: this.sourceRequest
});
} else {
str = `module.exports = (${runtimeTemplate.moduleExports({
module: sourceModule,
chunkGraph,
request: dep.request,
runtimeRequirements: new Set()
})})`;
switch (this.delegationType) {
case "require":
str += `(${JSON.stringify(this.request)})`;
break;
case "object":
str += `[${JSON.stringify(this.request)}]`;
break;
}
str += ";";
}
const sources = new Map();
if (this.useSourceMap || this.useSimpleSourceMap) {
sources.set("javascript", new OriginalSource(str, this.identifier()));
} else {
sources.set("javascript", new RawSource(str));
}
return {
sources,
runtimeRequirements: RUNTIME_REQUIREMENTS
};
}
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
return 42;
}
/**
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
hash.update(this.delegationType);
hash.update(JSON.stringify(this.request));
super.updateHash(hash, context);
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
// constructor
write(this.sourceRequest);
write(this.delegateData);
write(this.delegationType);
write(this.userRequest);
write(this.originalRequest);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context\
* @returns {DelegatedModule} DelegatedModule
*/
static deserialize(context) {
const { read } = context;
const obj = new DelegatedModule(
read(), // sourceRequest
read(), // delegateData
read(), // delegationType
read(), // userRequest
read() // originalRequest
);
obj.deserialize(context);
return obj;
}
/**
* Assuming this module is in the cache. Update the (cached) module with
* the fresh module from the factory. Usually updates internal references
* and properties.
* @param {Module} module fresh module
* @returns {void}
*/
updateCacheModule(module) {
super.updateCacheModule(module);
const m = /** @type {DelegatedModule} */ (module);
this.delegationType = m.delegationType;
this.userRequest = m.userRequest;
this.originalRequest = m.originalRequest;
this.delegateData = m.delegateData;
}
/**
* Assuming this module is in the cache. Remove internal references to allow freeing some memory.
*/
cleanupForCache() {
super.cleanupForCache();
this.delegateData = undefined;
}
}
makeSerializable(DelegatedModule, "webpack/lib/DelegatedModule");
module.exports = DelegatedModule;

View file

@ -0,0 +1,111 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DelegatedModule = require("./DelegatedModule");
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */
/** @typedef {import("./DelegatedModule").Data} Data */
/** @typedef {import("./DelegatedModule").SourceRequest} SourceRequest */
/** @typedef {import("./DelegatedModule").Type} Type */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/**
* @typedef {object} Options
* @property {SourceRequest} source source
* @property {NonNullable<DllReferencePluginOptions["context"]>} context absolute context path to which lib ident is relative to
* @property {DllReferencePluginOptionsContent} content content
* @property {DllReferencePluginOptions["type"]} type type
* @property {DllReferencePluginOptions["extensions"]} extensions extensions
* @property {DllReferencePluginOptions["scope"]} scope scope
* @property {object=} associatedObjectForCache object for caching
*/
class DelegatedModuleFactoryPlugin {
/**
* @param {Options} options options
*/
constructor(options) {
this.options = options;
options.type = options.type || "require";
options.extensions = options.extensions || ["", ".js", ".json", ".wasm"];
}
/**
* @param {NormalModuleFactory} normalModuleFactory the normal module factory
* @returns {void}
*/
apply(normalModuleFactory) {
const scope = this.options.scope;
if (scope) {
normalModuleFactory.hooks.factorize.tapAsync(
"DelegatedModuleFactoryPlugin",
(data, callback) => {
const [dependency] = data.dependencies;
const { request } = dependency;
if (request && request.startsWith(`${scope}/`)) {
const innerRequest = `.${request.slice(scope.length)}`;
let resolved;
if (innerRequest in this.options.content) {
resolved = this.options.content[innerRequest];
return callback(
null,
new DelegatedModule(
this.options.source,
resolved,
/** @type {Type} */ (this.options.type),
innerRequest,
request
)
);
}
const extensions =
/** @type {string[]} */
(this.options.extensions);
for (let i = 0; i < extensions.length; i++) {
const extension = extensions[i];
const requestPlusExt = innerRequest + extension;
if (requestPlusExt in this.options.content) {
resolved = this.options.content[requestPlusExt];
return callback(
null,
new DelegatedModule(
this.options.source,
resolved,
/** @type {Type} */ (this.options.type),
requestPlusExt,
request + extension
)
);
}
}
}
return callback();
}
);
} else {
normalModuleFactory.hooks.module.tap(
"DelegatedModuleFactoryPlugin",
module => {
const request = module.libIdent(this.options);
if (request && request in this.options.content) {
const resolved = this.options.content[request];
return new DelegatedModule(
this.options.source,
resolved,
/** @type {Type} */ (this.options.type),
request,
module
);
}
return module;
}
);
}
}
}
module.exports = DelegatedModuleFactoryPlugin;

47
node_modules/webpack/lib/DelegatedPlugin.js generated vendored Normal file
View file

@ -0,0 +1,47 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin");
const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DelegatedModuleFactoryPlugin").Options} Options */
class DelegatedPlugin {
/**
* @param {Options} options options
*/
constructor(options) {
this.options = options;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
"DelegatedPlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
DelegatedSourceDependency,
normalModuleFactory
);
}
);
compiler.hooks.compile.tap("DelegatedPlugin", ({ normalModuleFactory }) => {
new DelegatedModuleFactoryPlugin({
associatedObjectForCache: compiler.root,
...this.options
}).apply(normalModuleFactory);
});
}
}
module.exports = DelegatedPlugin;

122
node_modules/webpack/lib/DependenciesBlock.js generated vendored Normal file
View file

@ -0,0 +1,122 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
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 */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */
/**
* DependenciesBlock is the base class for all Module classes in webpack. It describes a
* "block" of dependencies which are pointers to other DependenciesBlock instances. For example
* when a Module has a CommonJs require statement, the DependencyBlock for the CommonJs module
* would be added as a dependency to the Module. DependenciesBlock is inherited by two types of classes:
* Module subclasses and AsyncDependenciesBlock subclasses. The only difference between the two is that
* AsyncDependenciesBlock subclasses are used for code-splitting (async boundary) and Module subclasses are not.
*/
class DependenciesBlock {
constructor() {
/** @type {Dependency[]} */
this.dependencies = [];
/** @type {AsyncDependenciesBlock[]} */
this.blocks = [];
/** @type {DependenciesBlock | undefined} */
this.parent = undefined;
}
getRootBlock() {
/** @type {DependenciesBlock} */
let current = this;
while (current.parent) current = current.parent;
return current;
}
/**
* Adds a DependencyBlock to DependencyBlock relationship.
* This is used for when a Module has a AsyncDependencyBlock tie (for code-splitting)
* @param {AsyncDependenciesBlock} block block being added
* @returns {void}
*/
addBlock(block) {
this.blocks.push(block);
block.parent = this;
}
/**
* @param {Dependency} dependency dependency being tied to block.
* This is an "edge" pointing to another "node" on module graph.
* @returns {void}
*/
addDependency(dependency) {
this.dependencies.push(dependency);
}
/**
* @param {Dependency} dependency dependency being removed
* @returns {void}
*/
removeDependency(dependency) {
const idx = this.dependencies.indexOf(dependency);
if (idx >= 0) {
this.dependencies.splice(idx, 1);
}
}
/**
* Removes all dependencies and blocks
* @returns {void}
*/
clearDependenciesAndBlocks() {
this.dependencies.length = 0;
this.blocks.length = 0;
}
/**
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
for (const dep of this.dependencies) {
dep.updateHash(hash, context);
}
for (const block of this.blocks) {
block.updateHash(hash, context);
}
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize({ write }) {
write(this.dependencies);
write(this.blocks);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize({ read }) {
this.dependencies = read();
this.blocks = read();
for (const block of this.blocks) {
block.parent = this;
}
}
}
makeSerializable(DependenciesBlock, "webpack/lib/DependenciesBlock");
module.exports = DependenciesBlock;

367
node_modules/webpack/lib/Dependency.js generated vendored Normal file
View file

@ -0,0 +1,367 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const RawModule = require("./RawModule");
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 */
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
/** @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 */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/**
* @typedef {object} UpdateHashContext
* @property {ChunkGraph} chunkGraph
* @property {RuntimeSpec} runtime
* @property {RuntimeTemplate=} runtimeTemplate
*/
/**
* @typedef {object} SourcePosition
* @property {number} line
* @property {number=} column
*/
/**
* @typedef {object} RealDependencyLocation
* @property {SourcePosition} start
* @property {SourcePosition=} end
* @property {number=} index
*/
/**
* @typedef {object} SyntheticDependencyLocation
* @property {string} name
* @property {number=} index
*/
/** @typedef {SyntheticDependencyLocation | RealDependencyLocation} DependencyLocation */
/**
* @typedef {object} ExportSpec
* @property {string} name the name of the export
* @property {boolean=} canMangle can the export be renamed (defaults to true)
* @property {boolean=} terminalBinding is the export a terminal binding that should be checked for export star conflicts
* @property {(string | ExportSpec)[]=} exports nested exports
* @property {ModuleGraphConnection=} from when reexported: from which module
* @property {string[] | null=} export when reexported: from which export
* @property {number=} priority when reexported: with which priority
* @property {boolean=} hidden export is not visible, because another export blends over it
*/
/**
* @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 {(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
* @property {boolean=} canMangle can the export be renamed (defaults to true)
* @property {boolean=} terminalBinding are the exports terminal bindings that should be checked for export star conflicts
* @property {Module[]=} dependencies module on which the result depends on
*/
/**
* @typedef {object} ReferencedExport
* @property {string[]} name name of the referenced export
* @property {boolean=} canMangle when false, referenced export can not be mangled, defaults to true
*/
/** @typedef {function(ModuleGraphConnection, RuntimeSpec): ConnectionState} GetConditionFn */
const TRANSITIVE = Symbol("transitive");
const getIgnoredModule = memoize(
() => new RawModule("/* (ignored) */", "ignored", "(ignored)")
);
class Dependency {
constructor() {
/** @type {Module | undefined} */
this._parentModule = undefined;
/** @type {DependenciesBlock | undefined} */
this._parentDependenciesBlock = undefined;
/** @type {number} */
this._parentDependenciesBlockIndex = -1;
// TODO check if this can be moved into ModuleDependency
/** @type {boolean} */
this.weak = false;
// TODO check if this can be moved into ModuleDependency
/** @type {boolean} */
this.optional = false;
this._locSL = 0;
this._locSC = 0;
this._locEL = 0;
this._locEC = 0;
this._locI = undefined;
this._locN = undefined;
this._loc = undefined;
}
/**
* @returns {string} a display name for the type of dependency
*/
get type() {
return "unknown";
}
/**
* @returns {string} a dependency category, typical categories are "commonjs", "amd", "esm"
*/
get category() {
return "unknown";
}
/**
* @returns {DependencyLocation} location
*/
get loc() {
if (this._loc !== undefined) return this._loc;
/** @type {SyntheticDependencyLocation & RealDependencyLocation} */
const loc = {};
if (this._locSL > 0) {
loc.start = { line: this._locSL, column: this._locSC };
}
if (this._locEL > 0) {
loc.end = { line: this._locEL, column: this._locEC };
}
if (this._locN !== undefined) {
loc.name = this._locN;
}
if (this._locI !== undefined) {
loc.index = this._locI;
}
return (this._loc = loc);
}
set loc(loc) {
if ("start" in loc && typeof loc.start === "object") {
this._locSL = loc.start.line || 0;
this._locSC = loc.start.column || 0;
} else {
this._locSL = 0;
this._locSC = 0;
}
if ("end" in loc && typeof loc.end === "object") {
this._locEL = loc.end.line || 0;
this._locEC = loc.end.column || 0;
} else {
this._locEL = 0;
this._locEC = 0;
}
this._locI = "index" in loc ? loc.index : undefined;
this._locN = "name" in loc ? loc.name : undefined;
this._loc = loc;
}
/**
* @param {number} startLine start line
* @param {number} startColumn start column
* @param {number} endLine end line
* @param {number} endColumn end column
*/
setLoc(startLine, startColumn, endLine, endColumn) {
this._locSL = startLine;
this._locSC = startColumn;
this._locEL = endLine;
this._locEC = endColumn;
this._locI = undefined;
this._locN = undefined;
this._loc = undefined;
}
/**
* @returns {string | undefined} a request context
*/
getContext() {
return undefined;
}
/**
* @returns {string | null} an identifier to merge equal requests
*/
getResourceIdentifier() {
return null;
}
/**
* @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module
*/
couldAffectReferencingModule() {
return TRANSITIVE;
}
/**
* Returns the referenced module and export
* @deprecated
* @param {ModuleGraph} moduleGraph module graph
* @returns {never} throws error
*/
getReference(moduleGraph) {
throw new Error(
"Dependency.getReference was removed in favor of Dependency.getReferencedExports, ModuleGraph.getModule and ModuleGraph.getConnection().active"
);
}
/**
* 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
*/
getReferencedExports(moduleGraph, runtime) {
return Dependency.EXPORTS_OBJECT_REFERENCED;
}
/**
* @param {ModuleGraph} moduleGraph module graph
* @returns {null | false | GetConditionFn} function to determine if the connection is active
*/
getCondition(moduleGraph) {
return null;
}
/**
* Returns the exported names
* @param {ModuleGraph} moduleGraph module graph
* @returns {ExportsSpec | undefined} export names
*/
getExports(moduleGraph) {
return undefined;
}
/**
* Returns warnings
* @param {ModuleGraph} moduleGraph module graph
* @returns {WebpackError[] | null | undefined} warnings
*/
getWarnings(moduleGraph) {
return null;
}
/**
* Returns errors
* @param {ModuleGraph} moduleGraph module graph
* @returns {WebpackError[] | null | undefined} errors
*/
getErrors(moduleGraph) {
return null;
}
/**
* Update the hash
* @param {Hash} hash hash to be updated
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {}
/**
* implement this method to allow the occurrence order plugin to count correctly
* @returns {number} count how often the id is used in this dependency
*/
getNumberOfIdOccurrences() {
return 1;
}
/**
* @param {ModuleGraph} moduleGraph the module graph
* @returns {ConnectionState} how this dependency connects the module to referencing modules
*/
getModuleEvaluationSideEffectsState(moduleGraph) {
return true;
}
/**
* @param {string} context context directory
* @returns {Module | null} a module
*/
createIgnoredModule(context) {
return getIgnoredModule();
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize({ write }) {
write(this.weak);
write(this.optional);
write(this._locSL);
write(this._locSC);
write(this._locEL);
write(this._locEC);
write(this._locI);
write(this._locN);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize({ read }) {
this.weak = read();
this.optional = read();
this._locSL = read();
this._locSC = read();
this._locEL = read();
this._locEC = read();
this._locI = read();
this._locN = read();
}
}
/** @type {string[][]} */
Dependency.NO_EXPORTS_REFERENCED = [];
/** @type {string[][]} */
Dependency.EXPORTS_OBJECT_REFERENCED = [[]];
// eslint-disable-next-line no-warning-comments
// @ts-ignore https://github.com/microsoft/TypeScript/issues/42919
Object.defineProperty(Dependency.prototype, "module", {
/**
* @deprecated
* @returns {never} throws
*/
get() {
throw new Error(
"module property was removed from Dependency (use compilation.moduleGraph.getModule(dependency) instead)"
);
},
/**
* @deprecated
* @returns {never} throws
*/
set() {
throw new Error(
"module property was removed from Dependency (use compilation.moduleGraph.updateModule(dependency, module) instead)"
);
}
});
// eslint-disable-next-line no-warning-comments
// @ts-ignore https://github.com/microsoft/TypeScript/issues/42919
Object.defineProperty(Dependency.prototype, "disconnect", {
get() {
throw new Error(
"disconnect was removed from Dependency (Dependency no longer carries graph specific information)"
);
}
});
Dependency.TRANSITIVE = TRANSITIVE;
module.exports = Dependency;

72
node_modules/webpack/lib/DllEntryPlugin.js generated vendored Normal file
View file

@ -0,0 +1,72 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DllModuleFactory = require("./DllModuleFactory");
const DllEntryDependency = require("./dependencies/DllEntryDependency");
const EntryDependency = require("./dependencies/EntryDependency");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {string[]} Entries */
/** @typedef {{ name: string, filename: TODO }} Options */
class DllEntryPlugin {
/**
* @param {string} context context
* @param {Entries} entries entry names
* @param {Options} options options
*/
constructor(context, entries, options) {
this.context = context;
this.entries = entries;
this.options = options;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
"DllEntryPlugin",
(compilation, { normalModuleFactory }) => {
const dllModuleFactory = new DllModuleFactory();
compilation.dependencyFactories.set(
DllEntryDependency,
dllModuleFactory
);
compilation.dependencyFactories.set(
EntryDependency,
normalModuleFactory
);
}
);
compiler.hooks.make.tapAsync("DllEntryPlugin", (compilation, callback) => {
compilation.addEntry(
this.context,
new DllEntryDependency(
this.entries.map((e, idx) => {
const dep = new EntryDependency(e);
dep.loc = {
name: this.options.name,
index: idx
};
return dep;
}),
this.options.name
),
this.options,
error => {
if (error) return callback(error);
callback();
}
);
});
}
}
module.exports = DllEntryPlugin;

174
node_modules/webpack/lib/DllModule.js generated vendored Normal file
View file

@ -0,0 +1,174 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { RawSource } = require("webpack-sources");
const Module = require("./Module");
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("./Compilation")} Compilation */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").SourceContext} SourceContext */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @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 */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
const TYPES = new Set(["javascript"]);
const RUNTIME_REQUIREMENTS = new Set([
RuntimeGlobals.require,
RuntimeGlobals.module
]);
class DllModule extends Module {
/**
* @param {string} context context path
* @param {Dependency[]} dependencies dependencies
* @param {string} name name
*/
constructor(context, dependencies, name) {
super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, context);
// Info from Factory
/** @type {Dependency[]} */
this.dependencies = dependencies;
this.name = name;
}
/**
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
}
/**
* @returns {string} a unique identifier of the module
*/
identifier() {
return `dll ${this.name}`;
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return `dll ${this.name}`;
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
this.buildMeta = {};
this.buildInfo = {};
return callback();
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration(context) {
const sources = new Map();
sources.set(
"javascript",
new RawSource(`module.exports = ${RuntimeGlobals.require};`)
);
return {
sources,
runtimeRequirements: RUNTIME_REQUIREMENTS
};
}
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
return callback(null, !this.buildMeta);
}
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
return 12;
}
/**
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
hash.update(`dll module${this.name || ""}`);
super.updateHash(hash, context);
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
context.write(this.name);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
this.name = context.read();
super.deserialize(context);
}
/**
* Assuming this module is in the cache. Update the (cached) module with
* the fresh module from the factory. Usually updates internal references
* and properties.
* @param {Module} module fresh module
* @returns {void}
*/
updateCacheModule(module) {
super.updateCacheModule(module);
this.dependencies = module.dependencies;
}
/**
* Assuming this module is in the cache. Remove internal references to allow freeing some memory.
*/
cleanupForCache() {
super.cleanupForCache();
this.dependencies = undefined;
}
}
makeSerializable(DllModule, "webpack/lib/DllModule");
module.exports = DllModule;

38
node_modules/webpack/lib/DllModuleFactory.js generated vendored Normal file
View file

@ -0,0 +1,38 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DllModule = require("./DllModule");
const ModuleFactory = require("./ModuleFactory");
/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
/** @typedef {import("./dependencies/DllEntryDependency")} DllEntryDependency */
class DllModuleFactory extends ModuleFactory {
constructor() {
super();
this.hooks = Object.freeze({});
}
/**
* @param {ModuleFactoryCreateData} data data object
* @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback
* @returns {void}
*/
create(data, callback) {
const dependency = /** @type {DllEntryDependency} */ (data.dependencies[0]);
callback(null, {
module: new DllModule(
data.context,
dependency.dependencies,
dependency.name
)
});
}
}
module.exports = DllModuleFactory;

70
node_modules/webpack/lib/DllPlugin.js generated vendored Normal file
View file

@ -0,0 +1,70 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DllEntryPlugin = require("./DllEntryPlugin");
const FlagAllModulesAsUsedPlugin = require("./FlagAllModulesAsUsedPlugin");
const LibManifestPlugin = require("./LibManifestPlugin");
const createSchemaValidation = require("./util/create-schema-validation");
/** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DllEntryPlugin").Entries} Entries */
/** @typedef {import("./DllEntryPlugin").Options} Options */
const validate = createSchemaValidation(
require("../schemas/plugins/DllPlugin.check.js"),
() => require("../schemas/plugins/DllPlugin.json"),
{
name: "Dll Plugin",
baseDataPath: "options"
}
);
class DllPlugin {
/**
* @param {DllPluginOptions} options options object
*/
constructor(options) {
validate(options);
this.options = {
...options,
entryOnly: options.entryOnly !== false
};
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.entryOption.tap("DllPlugin", (context, entry) => {
if (typeof entry !== "function") {
for (const name of Object.keys(entry)) {
/** @type {Options} */
const options = { name, filename: entry.filename };
new DllEntryPlugin(
context,
/** @type {Entries} */ (entry[name].import),
options
).apply(compiler);
}
} else {
throw new Error(
"DllPlugin doesn't support dynamic entry (function) yet"
);
}
return true;
});
new LibManifestPlugin(this.options).apply(compiler);
if (!this.options.entryOnly) {
new FlagAllModulesAsUsedPlugin("DllPlugin").apply(compiler);
}
}
}
module.exports = DllPlugin;

193
node_modules/webpack/lib/DllReferencePlugin.js generated vendored Normal file
View file

@ -0,0 +1,193 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const parseJson = require("json-parse-even-better-errors");
const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin");
const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin");
const WebpackError = require("./WebpackError");
const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
const createSchemaValidation = require("./util/create-schema-validation");
const makePathsRelative = require("./util/identifier").makePathsRelative;
/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsContent} DllReferencePluginOptionsContent */
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
const validate = createSchemaValidation(
require("../schemas/plugins/DllReferencePlugin.check.js"),
() => require("../schemas/plugins/DllReferencePlugin.json"),
{
name: "Dll Reference Plugin",
baseDataPath: "options"
}
);
/** @typedef {{ path: string, data: DllReferencePluginOptionsManifest | undefined, error: Error | undefined }} CompilationDataItem */
class DllReferencePlugin {
/**
* @param {DllReferencePluginOptions} options options object
*/
constructor(options) {
validate(options);
this.options = options;
/** @type {WeakMap<object, CompilationDataItem>} */
this._compilationData = new WeakMap();
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
"DllReferencePlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
DelegatedSourceDependency,
normalModuleFactory
);
}
);
compiler.hooks.beforeCompile.tapAsync(
"DllReferencePlugin",
(params, callback) => {
if ("manifest" in this.options) {
const manifest = this.options.manifest;
if (typeof manifest === "string") {
/** @type {InputFileSystem} */
(compiler.inputFileSystem).readFile(manifest, (err, result) => {
if (err) return callback(err);
/** @type {CompilationDataItem} */
const data = {
path: manifest,
data: undefined,
error: undefined
};
// Catch errors parsing the manifest so that blank
// or malformed manifest files don't kill the process.
try {
data.data = parseJson(
/** @type {Buffer} */ (result).toString("utf-8")
);
} catch (parseErr) {
// 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),
manifest,
compiler.root
);
data.error = new DllManifestError(
manifestPath,
/** @type {Error} */ (parseErr).message
);
}
this._compilationData.set(params, data);
return callback();
});
return;
}
}
return callback();
}
);
compiler.hooks.compile.tap("DllReferencePlugin", params => {
let name = this.options.name;
let sourceType = this.options.sourceType;
let resolvedContent =
"content" in this.options ? this.options.content : undefined;
if ("manifest" in this.options) {
const manifestParameter = this.options.manifest;
let manifest;
if (typeof manifestParameter === "string") {
const data =
/** @type {CompilationDataItem} */
(this._compilationData.get(params));
// If there was an error parsing the manifest
// file, exit now because the error will be added
// as a compilation error in the "compilation" hook.
if (data.error) {
return;
}
manifest = data.data;
} else {
manifest = manifestParameter;
}
if (manifest) {
if (!name) name = manifest.name;
if (!sourceType) sourceType = manifest.type;
if (!resolvedContent) resolvedContent = manifest.content;
}
}
/** @type {Externals} */
const externals = {};
const source = `dll-reference ${name}`;
externals[source] = /** @type {string} */ (name);
const normalModuleFactory = params.normalModuleFactory;
new ExternalModuleFactoryPlugin(sourceType || "var", externals).apply(
normalModuleFactory
);
new DelegatedModuleFactoryPlugin({
source,
type: this.options.type,
scope: this.options.scope,
context:
/** @type {string} */
(this.options.context || compiler.options.context),
content:
/** @type {DllReferencePluginOptionsContent} */
(resolvedContent),
extensions: this.options.extensions,
associatedObjectForCache: compiler.root
}).apply(normalModuleFactory);
});
compiler.hooks.compilation.tap(
"DllReferencePlugin",
(compilation, params) => {
if ("manifest" in this.options) {
const manifest = this.options.manifest;
if (typeof manifest === "string") {
const data = /** @type {CompilationDataItem} */ (
this._compilationData.get(params)
);
// If there was an error parsing the manifest file, add the
// error as a compilation error to make the compilation fail.
if (data.error) {
compilation.errors.push(
/** @type {DllManifestError} */ (data.error)
);
}
compilation.fileDependencies.add(manifest);
}
}
}
);
}
}
class DllManifestError extends WebpackError {
/**
* @param {string} filename filename of the manifest
* @param {string} message error message
*/
constructor(filename, message) {
super();
this.name = "DllManifestError";
this.message = `Dll manifest ${filename}\n${message}`;
}
}
module.exports = DllReferencePlugin;

79
node_modules/webpack/lib/DynamicEntryPlugin.js generated vendored Normal file
View file

@ -0,0 +1,79 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Naoyuki Kanezawa @nkzawa
*/
"use strict";
const EntryOptionPlugin = require("./EntryOptionPlugin");
const EntryPlugin = require("./EntryPlugin");
const EntryDependency = require("./dependencies/EntryDependency");
/** @typedef {import("../declarations/WebpackOptions").EntryDynamicNormalized} EntryDynamic */
/** @typedef {import("../declarations/WebpackOptions").EntryItem} EntryItem */
/** @typedef {import("../declarations/WebpackOptions").EntryStaticNormalized} EntryStatic */
/** @typedef {import("./Compiler")} Compiler */
class DynamicEntryPlugin {
/**
* @param {string} context the context path
* @param {EntryDynamic} entry the entry value
*/
constructor(context, entry) {
this.context = context;
this.entry = entry;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
"DynamicEntryPlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
EntryDependency,
normalModuleFactory
);
}
);
compiler.hooks.make.tapPromise(
"DynamicEntryPlugin",
(compilation, callback) =>
Promise.resolve(this.entry())
.then(entry => {
const promises = [];
for (const name of Object.keys(entry)) {
const desc = entry[name];
const options = EntryOptionPlugin.entryDescriptionToOptions(
compiler,
name,
desc
);
for (const entry of desc.import) {
promises.push(
new Promise((resolve, reject) => {
compilation.addEntry(
this.context,
EntryPlugin.createDependency(entry, options),
options,
err => {
if (err) return reject(err);
resolve();
}
);
})
);
}
}
return Promise.all(promises);
})
.then(x => {})
);
}
}
module.exports = DynamicEntryPlugin;

96
node_modules/webpack/lib/EntryOptionPlugin.js generated vendored Normal file
View file

@ -0,0 +1,96 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */
/** @typedef {import("../declarations/WebpackOptions").EntryNormalized} Entry */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
class EntryOptionPlugin {
/**
* @param {Compiler} compiler the compiler instance one is tapping into
* @returns {void}
*/
apply(compiler) {
compiler.hooks.entryOption.tap("EntryOptionPlugin", (context, entry) => {
EntryOptionPlugin.applyEntryOption(compiler, context, entry);
return true;
});
}
/**
* @param {Compiler} compiler the compiler
* @param {string} context context directory
* @param {Entry} entry request
* @returns {void}
*/
static applyEntryOption(compiler, context, entry) {
if (typeof entry === "function") {
const DynamicEntryPlugin = require("./DynamicEntryPlugin");
new DynamicEntryPlugin(context, entry).apply(compiler);
} else {
const EntryPlugin = require("./EntryPlugin");
for (const name of Object.keys(entry)) {
const desc = entry[name];
const options = EntryOptionPlugin.entryDescriptionToOptions(
compiler,
name,
desc
);
const descImport =
/** @type {Exclude<EntryDescription["import"], undefined>} */
(desc.import);
for (const entry of descImport) {
new EntryPlugin(context, entry, options).apply(compiler);
}
}
}
}
/**
* @param {Compiler} compiler the compiler
* @param {string} name entry name
* @param {EntryDescription} desc entry description
* @returns {EntryOptions} options for the entry
*/
static entryDescriptionToOptions(compiler, name, desc) {
/** @type {EntryOptions} */
const options = {
name,
filename: desc.filename,
runtime: desc.runtime,
layer: desc.layer,
dependOn: desc.dependOn,
baseUri: desc.baseUri,
publicPath: desc.publicPath,
chunkLoading: desc.chunkLoading,
asyncChunks: desc.asyncChunks,
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");
EnableChunkLoadingPlugin.checkEnabled(compiler, desc.chunkLoading);
}
if (desc.wasmLoading) {
const EnableWasmLoadingPlugin = require("./wasm/EnableWasmLoadingPlugin");
EnableWasmLoadingPlugin.checkEnabled(compiler, desc.wasmLoading);
}
if (desc.library) {
const EnableLibraryPlugin = require("./library/EnableLibraryPlugin");
EnableLibraryPlugin.checkEnabled(compiler, desc.library.type);
}
return options;
}
}
module.exports = EntryOptionPlugin;

101
node_modules/webpack/lib/Entrypoint.js generated vendored Normal file
View file

@ -0,0 +1,101 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ChunkGroup = require("./ChunkGroup");
/** @typedef {import("../declarations/WebpackOptions").EntryDescriptionNormalized} EntryDescription */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {{ name?: string } & Omit<EntryDescription, "import">} EntryOptions */
/**
* Entrypoint serves as an encapsulation primitive for chunks that are
* a part of a single ChunkGroup. They represent all bundles that need to be loaded for a
* single instance of a page. Multi-page application architectures will typically yield multiple Entrypoint objects
* inside of the compilation, whereas a Single Page App may only contain one with many lazy-loaded chunks.
*/
class Entrypoint extends ChunkGroup {
/**
* Creates an instance of Entrypoint.
* @param {EntryOptions | string} entryOptions the options for the entrypoint (or name)
* @param {boolean=} initial false, when the entrypoint is not initial loaded
*/
constructor(entryOptions, initial = true) {
if (typeof entryOptions === "string") {
entryOptions = { name: entryOptions };
}
super({
name: entryOptions.name
});
this.options = entryOptions;
/** @type {Chunk=} */
this._runtimeChunk = undefined;
/** @type {Chunk=} */
this._entrypointChunk = undefined;
/** @type {boolean} */
this._initial = initial;
}
/**
* @returns {boolean} true, when this chunk group will be loaded on initial page load
*/
isInitial() {
return this._initial;
}
/**
* Sets the runtimeChunk for an entrypoint.
* @param {Chunk} chunk the chunk being set as the runtime chunk.
* @returns {void}
*/
setRuntimeChunk(chunk) {
this._runtimeChunk = chunk;
}
/**
* Fetches the chunk reference containing the webpack bootstrap code
* @returns {Chunk | null} returns the runtime chunk or null if there is none
*/
getRuntimeChunk() {
if (this._runtimeChunk) return this._runtimeChunk;
for (const parent of this.parentsIterable) {
if (parent instanceof Entrypoint) return parent.getRuntimeChunk();
}
return null;
}
/**
* Sets the chunk with the entrypoint modules for an entrypoint.
* @param {Chunk} chunk the chunk being set as the entrypoint chunk.
* @returns {void}
*/
setEntrypointChunk(chunk) {
this._entrypointChunk = chunk;
}
/**
* Returns the chunk which contains the entrypoint modules
* (or at least the execution of them)
* @returns {Chunk} chunk
*/
getEntrypointChunk() {
return /** @type {Chunk} */ (this._entrypointChunk);
}
/**
* @param {Chunk} oldChunk chunk to be replaced
* @param {Chunk} newChunk New chunk that will be replaced with
* @returns {boolean | undefined} returns true if the replacement was successful
*/
replaceChunk(oldChunk, newChunk) {
if (this._runtimeChunk === oldChunk) this._runtimeChunk = newChunk;
if (this._entrypointChunk === oldChunk) this._entrypointChunk = newChunk;
return super.replaceChunk(oldChunk, newChunk);
}
}
module.exports = Entrypoint;

66
node_modules/webpack/lib/EnvironmentPlugin.js generated vendored Normal file
View file

@ -0,0 +1,66 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
*/
"use strict";
const DefinePlugin = require("./DefinePlugin");
const WebpackError = require("./WebpackError");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DefinePlugin").CodeValue} CodeValue */
class EnvironmentPlugin {
/**
* @param {(string | string[] | Record<string, string>)[]} keys keys
*/
constructor(...keys) {
if (keys.length === 1 && Array.isArray(keys[0])) {
this.keys = keys[0];
this.defaultValues = {};
} else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") {
this.keys = Object.keys(keys[0]);
this.defaultValues = /** @type {Record<string, string>} */ (keys[0]);
} else {
this.keys = /** @type {string[]} */ (keys);
this.defaultValues = {};
}
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
/** @type {Record<string, CodeValue>} */
const definitions = {};
for (const key of this.keys) {
const value =
process.env[key] !== undefined
? process.env[key]
: this.defaultValues[key];
if (value === undefined) {
compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => {
const error = new WebpackError(
`EnvironmentPlugin - ${key} environment variable is undefined.\n\n` +
"You can pass an object with default values to suppress this warning.\n" +
"See https://webpack.js.org/plugins/environment-plugin for example."
);
error.name = "EnvVariableNotDefinedError";
compilation.errors.push(error);
});
}
definitions[`process.env.${key}`] =
value === undefined ? "undefined" : JSON.stringify(value);
}
new DefinePlugin(definitions).apply(compiler);
}
}
module.exports = EnvironmentPlugin;

100
node_modules/webpack/lib/ErrorHelpers.js generated vendored Normal file
View file

@ -0,0 +1,100 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const loaderFlag = "LOADER_EXECUTION";
const webpackOptionsFlag = "WEBPACK_OPTIONS";
/**
* @param {string} stack stack trace
* @param {string} flag flag to cut off
* @returns {string} stack trace without the specified flag included
*/
const cutOffByFlag = (stack, flag) => {
const errorStack = stack.split("\n");
for (let i = 0; i < errorStack.length; i++) {
if (errorStack[i].includes(flag)) {
errorStack.length = i;
}
}
return errorStack.join("\n");
};
/**
* @param {string} stack stack trace
* @returns {string} stack trace without the loader execution flag included
*/
const cutOffLoaderExecution = stack => cutOffByFlag(stack, loaderFlag);
/**
* @param {string} stack stack trace
* @returns {string} stack trace without the webpack options flag included
*/
const cutOffWebpackOptions = stack => cutOffByFlag(stack, webpackOptionsFlag);
/**
* @param {string} stack stack trace
* @param {string} message error message
* @returns {string} stack trace without the message included
*/
const cutOffMultilineMessage = (stack, message) => {
const stackSplitByLines = stack.split("\n");
const messageSplitByLines = message.split("\n");
/** @type {string[]} */
const result = [];
for (const [idx, line] of stackSplitByLines.entries()) {
if (!line.includes(messageSplitByLines[idx])) result.push(line);
}
return result.join("\n");
};
/**
* @param {string} stack stack trace
* @param {string} message error message
* @returns {string} stack trace without the message included
*/
const cutOffMessage = (stack, message) => {
const nextLine = stack.indexOf("\n");
if (nextLine === -1) {
return stack === message ? "" : stack;
}
const firstLine = stack.slice(0, nextLine);
return firstLine === message ? stack.slice(nextLine + 1) : stack;
};
/**
* @param {string} stack stack trace
* @param {string} message error message
* @returns {string} stack trace without the loader execution flag and message included
*/
const cleanUp = (stack, message) => {
stack = cutOffLoaderExecution(stack);
stack = cutOffMessage(stack, message);
return stack;
};
/**
* @param {string} stack stack trace
* @param {string} message error message
* @returns {string} stack trace without the webpack options flag and message included
*/
const cleanUpWebpackOptions = (stack, message) => {
stack = cutOffWebpackOptions(stack);
stack = cutOffMultilineMessage(stack, message);
return stack;
};
module.exports.cutOffByFlag = cutOffByFlag;
module.exports.cutOffLoaderExecution = cutOffLoaderExecution;
module.exports.cutOffWebpackOptions = cutOffWebpackOptions;
module.exports.cutOffMultilineMessage = cutOffMultilineMessage;
module.exports.cutOffMessage = cutOffMessage;
module.exports.cleanUp = cleanUp;
module.exports.cleanUpWebpackOptions = cleanUpWebpackOptions;

126
node_modules/webpack/lib/EvalDevToolModulePlugin.js generated vendored Normal file
View file

@ -0,0 +1,126 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ConcatSource, RawSource } = require("webpack-sources");
const ExternalModule = require("./ExternalModule");
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const RuntimeGlobals = require("./RuntimeGlobals");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").OutputNormalized} OutputOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @type {WeakMap<Source, Source>} */
const cache = new WeakMap();
const devtoolWarning = new RawSource(`/*
* ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
* This devtool is neither made for production nor for readable output files.
* It uses "eval()" calls to create a separate source file in the browser devtools.
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
* or disable the default devtool with "devtool: false".
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
*/
`);
/**
* @typedef {object} EvalDevToolModulePluginOptions
* @property {OutputOptions["devtoolNamespace"]=} namespace namespace
* @property {string=} sourceUrlComment source url comment
* @property {OutputOptions["devtoolModuleFilenameTemplate"]=} moduleFilenameTemplate module filename template
*/
class EvalDevToolModulePlugin {
/**
* @param {EvalDevToolModulePluginOptions=} options options
*/
constructor(options = {}) {
this.namespace = options.namespace || "";
this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]";
this.moduleFilenameTemplate =
options.moduleFilenameTemplate ||
"webpack://[namespace]/[resourcePath]?[loaders]";
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap("EvalDevToolModulePlugin", compilation => {
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
hooks.renderModuleContent.tap(
"EvalDevToolModulePlugin",
(source, module, { runtimeTemplate, chunkGraph }) => {
const cacheEntry = cache.get(source);
if (cacheEntry !== undefined) return cacheEntry;
if (module instanceof ExternalModule) {
cache.set(source, source);
return source;
}
const content = source.source();
const str = ModuleFilenameHelpers.createFilename(
module,
{
moduleFilenameTemplate: this.moduleFilenameTemplate,
namespace: this.namespace
},
{
requestShortener: runtimeTemplate.requestShortener,
chunkGraph,
hashFunction: compilation.outputOptions.hashFunction
}
);
const footer = `\n${this.sourceUrlComment.replace(
/\[url\]/g,
encodeURI(str)
.replace(/%2F/g, "/")
.replace(/%20/g, "_")
.replace(/%5E/g, "^")
.replace(/%5C/g, "\\")
.replace(/^\//, "")
)}`;
const result = new RawSource(
`eval(${
compilation.outputOptions.trustedTypes
? `${RuntimeGlobals.createScript}(${JSON.stringify(
content + footer
)})`
: JSON.stringify(content + footer)
});`
);
cache.set(source, result);
return result;
}
);
hooks.inlineInRuntimeBailout.tap(
"EvalDevToolModulePlugin",
() => "the eval devtool is used."
);
hooks.render.tap(
"EvalDevToolModulePlugin",
source => new ConcatSource(devtoolWarning, source)
);
hooks.chunkHash.tap("EvalDevToolModulePlugin", (chunk, hash) => {
hash.update("EvalDevToolModulePlugin");
hash.update("2");
});
if (compilation.outputOptions.trustedTypes) {
compilation.hooks.additionalModuleRuntimeRequirements.tap(
"EvalDevToolModulePlugin",
(module, set, context) => {
set.add(RuntimeGlobals.createScript);
}
);
}
});
}
}
module.exports = EvalDevToolModulePlugin;

219
node_modules/webpack/lib/EvalSourceMapDevToolPlugin.js generated vendored Normal file
View file

@ -0,0 +1,219 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ConcatSource, RawSource } = require("webpack-sources");
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const NormalModule = require("./NormalModule");
const RuntimeGlobals = require("./RuntimeGlobals");
const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
const ConcatenatedModule = require("./optimize/ConcatenatedModule");
const { makePathsAbsolute } = require("./util/identifier");
/** @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 */
/** @typedef {import("./NormalModule").SourceMap} SourceMap */
/** @type {WeakMap<Source, Source>} */
const cache = new WeakMap();
const devtoolWarning = new RawSource(`/*
* ATTENTION: An "eval-source-map" devtool has been used.
* This devtool is neither made for production nor for readable output files.
* It uses "eval()" calls to create a separate source file with attached SourceMaps in the browser devtools.
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
* or disable the default devtool with "devtool: false".
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
*/
`);
class EvalSourceMapDevToolPlugin {
/**
* @param {SourceMapDevToolPluginOptions|string} inputOptions Options object
*/
constructor(inputOptions) {
/** @type {SourceMapDevToolPluginOptions} */
let options;
if (typeof inputOptions === "string") {
options = {
append: inputOptions
};
} else {
options = inputOptions;
}
this.sourceMapComment =
options.append && typeof options.append !== "function"
? options.append
: "//# sourceURL=[module]\n//# sourceMappingURL=[url]";
this.moduleFilenameTemplate =
options.moduleFilenameTemplate ||
"webpack://[namespace]/[resource-path]?[hash]";
this.namespace = options.namespace || "";
this.options = options;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const options = this.options;
compiler.hooks.compilation.tap(
"EvalSourceMapDevToolPlugin",
compilation => {
const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
const matchModule = ModuleFilenameHelpers.matchObject.bind(
ModuleFilenameHelpers,
options
);
hooks.renderModuleContent.tap(
"EvalSourceMapDevToolPlugin",
(source, m, { runtimeTemplate, chunkGraph }) => {
const cachedSource = cache.get(source);
if (cachedSource !== undefined) {
return cachedSource;
}
/**
* @param {Source} r result
* @returns {Source} result
*/
const result = r => {
cache.set(source, r);
return r;
};
if (m instanceof NormalModule) {
const module = /** @type {NormalModule} */ (m);
if (!matchModule(module.resource)) {
return result(source);
}
} else if (m instanceof ConcatenatedModule) {
const concatModule = /** @type {ConcatenatedModule} */ (m);
if (concatModule.rootModule instanceof NormalModule) {
const module = /** @type {NormalModule} */ (
concatModule.rootModule
);
if (!matchModule(module.resource)) {
return result(source);
}
} else {
return result(source);
}
} else {
return result(source);
}
/** @type {SourceMap} */
let sourceMap;
let content;
if (source.sourceAndMap) {
const sourceAndMap = source.sourceAndMap(options);
sourceMap = /** @type {SourceMap} */ (sourceAndMap.map);
content = sourceAndMap.source;
} else {
sourceMap = /** @type {SourceMap} */ (source.map(options));
content = source.source();
}
if (!sourceMap) {
return result(source);
}
// Clone (flat) the sourcemap to ensure that the mutations below do not persist.
sourceMap = { ...sourceMap };
const context = /** @type {string} */ (compiler.options.context);
const root = compiler.root;
const modules = sourceMap.sources.map(source => {
if (!source.startsWith("webpack://")) return source;
source = makePathsAbsolute(context, source.slice(10), root);
const module = compilation.findModule(source);
return module || source;
});
let moduleFilenames = modules.map(module =>
ModuleFilenameHelpers.createFilename(
module,
{
moduleFilenameTemplate: this.moduleFilenameTemplate,
namespace: this.namespace
},
{
requestShortener: runtimeTemplate.requestShortener,
chunkGraph,
hashFunction: compilation.outputOptions.hashFunction
}
)
);
moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(
moduleFilenames,
(filename, i, n) => {
for (let j = 0; j < n; j++) filename += "*";
return filename;
}
);
sourceMap.sources = moduleFilenames;
if (options.noSources) {
sourceMap.sourcesContent = undefined;
}
sourceMap.sourceRoot = options.sourceRoot || "";
const moduleId =
/** @type {ModuleId} */
(chunkGraph.getModuleId(m));
sourceMap.file =
typeof moduleId === "number" ? `${moduleId}.js` : moduleId;
const footer = `${this.sourceMapComment.replace(
/\[url\]/g,
`data:application/json;charset=utf-8;base64,${Buffer.from(
JSON.stringify(sourceMap),
"utf8"
).toString("base64")}`
)}\n//# sourceURL=webpack-internal:///${moduleId}\n`; // workaround for chrome bug
return result(
new RawSource(
`eval(${
compilation.outputOptions.trustedTypes
? `${RuntimeGlobals.createScript}(${JSON.stringify(
content + footer
)})`
: JSON.stringify(content + footer)
});`
)
);
}
);
hooks.inlineInRuntimeBailout.tap(
"EvalDevToolModulePlugin",
() => "the eval-source-map devtool is used."
);
hooks.render.tap(
"EvalSourceMapDevToolPlugin",
source => new ConcatSource(devtoolWarning, source)
);
hooks.chunkHash.tap("EvalSourceMapDevToolPlugin", (chunk, hash) => {
hash.update("EvalSourceMapDevToolPlugin");
hash.update("2");
});
if (compilation.outputOptions.trustedTypes) {
compilation.hooks.additionalModuleRuntimeRequirements.tap(
"EvalSourceMapDevToolPlugin",
(module, set, context) => {
set.add(RuntimeGlobals.createScript);
}
);
}
}
);
}
}
module.exports = EvalSourceMapDevToolPlugin;

980
node_modules/webpack/lib/ExternalModule.js generated vendored Normal file
View file

@ -0,0 +1,980 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { OriginalSource, RawSource } = require("webpack-sources");
const ConcatenationScope = require("./ConcatenationScope");
const EnvironmentNotSupportAsyncWarning = require("./EnvironmentNotSupportAsyncWarning");
const { UsageState } = require("./ExportsInfo");
const InitFragment = require("./InitFragment");
const Module = require("./Module");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const Template = require("./Template");
const StaticExportsDependency = require("./dependencies/StaticExportsDependency");
const createHash = require("./util/createHash");
const extractUrlAndGlobal = require("./util/extractUrlAndGlobal");
const makeSerializable = require("./util/makeSerializable");
const propertyAccess = require("./util/propertyAccess");
const { register } = require("./util/serialization");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./ExportsInfo")} ExportsInfo */
/** @typedef {import("./Generator").GenerateContext} GenerateContext */
/** @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").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/** @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 */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {typeof import("./util/Hash")} HashConstructor */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/** @typedef {{ attributes?: ImportAttributes, externalType: "import" | "module" | undefined }} ImportDependencyMeta */
/** @typedef {{ layer?: string, supports?: string, media?: string }} CssImportDependencyMeta */
/** @typedef {ImportDependencyMeta | CssImportDependencyMeta} DependencyMeta */
/**
* @typedef {object} SourceData
* @property {boolean=} iife
* @property {string=} init
* @property {string} expression
* @property {InitFragment<ChunkRenderContext>[]=} chunkInitFragments
* @property {ReadOnlyRuntimeRequirements=} runtimeRequirements
*/
const TYPES = new Set(["javascript"]);
const CSS_TYPES = new Set(["css-import"]);
const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]);
const RUNTIME_REQUIREMENTS_FOR_SCRIPT = new Set([RuntimeGlobals.loadScript]);
const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([
RuntimeGlobals.definePropertyGetters
]);
const EMPTY_RUNTIME_REQUIREMENTS = new Set([]);
/**
* @param {string|string[]} variableName the variable name or path
* @param {string} type the module system
* @returns {SourceData} the generated source
*/
const getSourceForGlobalVariableExternal = (variableName, type) => {
if (!Array.isArray(variableName)) {
// make it an array as the look up works the same basically
variableName = [variableName];
}
// needed for e.g. window["some"]["thing"]
const objectLookup = variableName.map(r => `[${JSON.stringify(r)}]`).join("");
return {
iife: type === "this",
expression: `${type}${objectLookup}`
};
};
/**
* @param {string|string[]} moduleAndSpecifiers the module request
* @returns {SourceData} the generated source
*/
const getSourceForCommonJsExternal = moduleAndSpecifiers => {
if (!Array.isArray(moduleAndSpecifiers)) {
return {
expression: `require(${JSON.stringify(moduleAndSpecifiers)})`
};
}
const moduleName = moduleAndSpecifiers[0];
return {
expression: `require(${JSON.stringify(moduleName)})${propertyAccess(
moduleAndSpecifiers,
1
)}`
};
};
/**
* @param {string|string[]} moduleAndSpecifiers the module request
* @param {string} importMetaName import.meta name
* @param {boolean} needPrefix need to use `node:` prefix for `module` import
* @returns {SourceData} the generated source
*/
const getSourceForCommonJsExternalInNodeModule = (
moduleAndSpecifiers,
importMetaName,
needPrefix
) => {
const chunkInitFragments = [
new InitFragment(
`import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "${
needPrefix ? "node:" : ""
}module";\n`,
InitFragment.STAGE_HARMONY_IMPORTS,
0,
"external module node-commonjs"
)
];
if (!Array.isArray(moduleAndSpecifiers)) {
return {
chunkInitFragments,
expression: `__WEBPACK_EXTERNAL_createRequire(${importMetaName}.url)(${JSON.stringify(
moduleAndSpecifiers
)})`
};
}
const moduleName = moduleAndSpecifiers[0];
return {
chunkInitFragments,
expression: `__WEBPACK_EXTERNAL_createRequire(${importMetaName}.url)(${JSON.stringify(
moduleName
)})${propertyAccess(moduleAndSpecifiers, 1)}`
};
};
/**
* @param {string|string[]} moduleAndSpecifiers the module request
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {ImportDependencyMeta=} dependencyMeta the dependency meta
* @returns {SourceData} the generated source
*/
const getSourceForImportExternal = (
moduleAndSpecifiers,
runtimeTemplate,
dependencyMeta
) => {
const importName = runtimeTemplate.outputOptions.importFunctionName;
if (
!runtimeTemplate.supportsDynamicImport() &&
(importName === "import" || importName === "module-import")
) {
throw new Error(
"The target environment doesn't support 'import()' so it's not possible to use external type 'import'"
);
}
const attributes =
dependencyMeta && dependencyMeta.attributes
? dependencyMeta.attributes._isLegacyAssert
? `, { assert: ${JSON.stringify(
dependencyMeta.attributes,
importAssertionReplacer
)} }`
: `, { with: ${JSON.stringify(dependencyMeta.attributes)} }`
: "";
if (!Array.isArray(moduleAndSpecifiers)) {
return {
expression: `${importName}(${JSON.stringify(
moduleAndSpecifiers
)}${attributes});`
};
}
if (moduleAndSpecifiers.length === 1) {
return {
expression: `${importName}(${JSON.stringify(
moduleAndSpecifiers[0]
)}${attributes});`
};
}
const moduleName = moduleAndSpecifiers[0];
return {
expression: `${importName}(${JSON.stringify(
moduleName
)}${attributes}).then(${runtimeTemplate.returningFunction(
`module${propertyAccess(moduleAndSpecifiers, 1)}`,
"module"
)});`
};
};
/**
* @param {string} key key
* @param {any | undefined} value value
* @returns {undefined | string} replaced value
*/
const importAssertionReplacer = (key, value) => {
if (key === "_isLegacyAssert") {
return;
}
return value;
};
/**
* @extends {InitFragment<ChunkRenderContext>}
*/
class ModuleExternalInitFragment extends InitFragment {
/**
* @param {string} request import source
* @param {string=} ident recomputed ident
* @param {ImportDependencyMeta=} dependencyMeta the dependency meta
* @param {string | HashConstructor=} hashFunction the hash function to use
*/
constructor(request, ident, dependencyMeta, hashFunction = "md4") {
if (ident === undefined) {
ident = Template.toIdentifier(request);
if (ident !== request) {
ident += `_${createHash(hashFunction)
.update(request)
.digest("hex")
.slice(0, 8)}`;
}
}
const identifier = `__WEBPACK_EXTERNAL_MODULE_${ident}__`;
super(
`import * as ${identifier} from ${JSON.stringify(request)}${
dependencyMeta && dependencyMeta.attributes
? dependencyMeta.attributes._isLegacyAssert
? ` assert ${JSON.stringify(
dependencyMeta.attributes,
importAssertionReplacer
)}`
: ` with ${JSON.stringify(dependencyMeta.attributes)}`
: ""
};\n`,
InitFragment.STAGE_HARMONY_IMPORTS,
0,
`external module import ${ident}`
);
this._ident = ident;
this._request = request;
this._dependencyMeta = request;
this._identifier = identifier;
}
getNamespaceIdentifier() {
return this._identifier;
}
}
register(
ModuleExternalInitFragment,
"webpack/lib/ExternalModule",
"ModuleExternalInitFragment",
{
serialize(obj, { write }) {
write(obj._request);
write(obj._ident);
write(obj._dependencyMeta);
},
deserialize({ read }) {
return new ModuleExternalInitFragment(read(), read(), read());
}
}
);
/**
* @param {string} input input
* @param {ExportsInfo} exportsInfo the exports info
* @param {RuntimeSpec=} runtime the runtime
* @param {RuntimeTemplate=} runtimeTemplate the runtime template
* @returns {string | undefined} the module remapping
*/
const generateModuleRemapping = (
input,
exportsInfo,
runtime,
runtimeTemplate
) => {
if (exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused) {
const properties = [];
for (const exportInfo of exportsInfo.orderedExports) {
const used = exportInfo.getUsedName(exportInfo.name, runtime);
if (!used) continue;
const nestedInfo = exportInfo.getNestedExportsInfo();
if (nestedInfo) {
const nestedExpr = generateModuleRemapping(
`${input}${propertyAccess([exportInfo.name])}`,
nestedInfo
);
if (nestedExpr) {
properties.push(`[${JSON.stringify(used)}]: y(${nestedExpr})`);
continue;
}
}
properties.push(
`[${JSON.stringify(used)}]: ${
/** @type {RuntimeTemplate} */ (runtimeTemplate).returningFunction(
`${input}${propertyAccess([exportInfo.name])}`
)
}`
);
}
return `x({ ${properties.join(", ")} })`;
}
};
/**
* @param {string|string[]} moduleAndSpecifiers the module request
* @param {ExportsInfo} exportsInfo exports info of this module
* @param {RuntimeSpec} runtime the runtime
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {ImportDependencyMeta} dependencyMeta the dependency meta
* @returns {SourceData} the generated source
*/
const getSourceForModuleExternal = (
moduleAndSpecifiers,
exportsInfo,
runtime,
runtimeTemplate,
dependencyMeta
) => {
if (!Array.isArray(moduleAndSpecifiers))
moduleAndSpecifiers = [moduleAndSpecifiers];
const initFragment = new ModuleExternalInitFragment(
moduleAndSpecifiers[0],
undefined,
dependencyMeta,
runtimeTemplate.outputOptions.hashFunction
);
const baseAccess = `${initFragment.getNamespaceIdentifier()}${propertyAccess(
moduleAndSpecifiers,
1
)}`;
const moduleRemapping = generateModuleRemapping(
baseAccess,
exportsInfo,
runtime,
runtimeTemplate
);
const expression = moduleRemapping || baseAccess;
return {
expression,
init: moduleRemapping
? `var x = ${runtimeTemplate.basicFunction(
"y",
`var x = {}; ${RuntimeGlobals.definePropertyGetters}(x, y); return x`
)} \nvar y = ${runtimeTemplate.returningFunction(
runtimeTemplate.returningFunction("x"),
"x"
)}`
: undefined,
runtimeRequirements: moduleRemapping
? RUNTIME_REQUIREMENTS_FOR_MODULE
: undefined,
chunkInitFragments: [initFragment]
};
};
/**
* @param {string|string[]} urlAndGlobal the script request
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
const getSourceForScriptExternal = (urlAndGlobal, runtimeTemplate) => {
if (typeof urlAndGlobal === "string") {
urlAndGlobal = extractUrlAndGlobal(urlAndGlobal);
}
const url = urlAndGlobal[0];
const globalName = urlAndGlobal[1];
return {
init: "var __webpack_error__ = new Error();",
expression: `new Promise(${runtimeTemplate.basicFunction(
"resolve, reject",
[
`if(typeof ${globalName} !== "undefined") return resolve();`,
`${RuntimeGlobals.loadScript}(${JSON.stringify(
url
)}, ${runtimeTemplate.basicFunction("event", [
`if(typeof ${globalName} !== "undefined") return resolve();`,
"var errorType = event && (event.type === 'load' ? 'missing' : event.type);",
"var realSrc = event && event.target && event.target.src;",
"__webpack_error__.message = 'Loading script failed.\\n(' + errorType + ': ' + realSrc + ')';",
"__webpack_error__.name = 'ScriptExternalLoadError';",
"__webpack_error__.type = errorType;",
"__webpack_error__.request = realSrc;",
"reject(__webpack_error__);"
])}, ${JSON.stringify(globalName)});`
]
)}).then(${runtimeTemplate.returningFunction(
`${globalName}${propertyAccess(urlAndGlobal, 2)}`
)})`,
runtimeRequirements: RUNTIME_REQUIREMENTS_FOR_SCRIPT
};
};
/**
* @param {string} variableName the variable name to check
* @param {string} request the request path
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {string} the generated source
*/
const checkExternalVariable = (variableName, request, runtimeTemplate) =>
`if(typeof ${variableName} === 'undefined') { ${runtimeTemplate.throwMissingModuleErrorBlock(
{ request }
)} }\n`;
/**
* @param {string|number} id the module id
* @param {boolean} optional true, if the module is optional
* @param {string|string[]} request the request path
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
const getSourceForAmdOrUmdExternal = (
id,
optional,
request,
runtimeTemplate
) => {
const externalVariable = `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(
`${id}`
)}__`;
return {
init: optional
? checkExternalVariable(
externalVariable,
Array.isArray(request) ? request.join(".") : request,
runtimeTemplate
)
: undefined,
expression: externalVariable
};
};
/**
* @param {boolean} optional true, if the module is optional
* @param {string|string[]} request the request path
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @returns {SourceData} the generated source
*/
const getSourceForDefaultCase = (optional, request, runtimeTemplate) => {
if (!Array.isArray(request)) {
// make it an array as the look up works the same basically
request = [request];
}
const variableName = request[0];
const objectLookup = propertyAccess(request, 1);
return {
init: optional
? checkExternalVariable(variableName, request.join("."), runtimeTemplate)
: undefined,
expression: `${variableName}${objectLookup}`
};
};
/** @typedef {Record<string, string | string[]>} RequestRecord */
class ExternalModule extends Module {
/**
* @param {string | string[] | RequestRecord} request request
* @param {string} type type
* @param {string} userRequest user request
* @param {DependencyMeta=} dependencyMeta dependency meta
*/
constructor(request, type, userRequest, dependencyMeta) {
super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
// Info from Factory
/** @type {string | string[] | Record<string, string | string[]>} */
this.request = request;
/** @type {string} */
this.externalType = type;
/** @type {string} */
this.userRequest = userRequest;
/** @type {DependencyMeta=} */
this.dependencyMeta = dependencyMeta;
}
/**
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return this.externalType === "css-import" ? CSS_TYPES : TYPES;
}
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
libIdent(options) {
return this.userRequest;
}
/**
* @param {Chunk} chunk the chunk which condition should be checked
* @param {Compilation} compilation the compilation
* @returns {boolean} true, if the chunk is ok for the module
*/
chunkCondition(chunk, { chunkGraph }) {
return this.externalType === "css-import"
? true
: chunkGraph.getNumberOfEntryModules(chunk) > 0;
}
/**
* @returns {string} a unique identifier of the module
*/
identifier() {
return `external ${this.externalType} ${JSON.stringify(this.request)}`;
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return `external ${JSON.stringify(this.request)}`;
}
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
return callback(null, !this.buildMeta);
}
/**
* @param {string} externalType raw external type
* @returns {string} resolved external type
*/
getModuleImportType(externalType) {
if (externalType === "module-import") {
if (
this.dependencyMeta &&
/** @type {ImportDependencyMeta} */ (this.dependencyMeta).externalType
) {
return /** @type {ImportDependencyMeta} */ (this.dependencyMeta)
.externalType;
}
return "module";
}
return externalType;
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
this.buildMeta = {
async: false,
exportsType: undefined
};
this.buildInfo = {
strict: true,
topLevelDeclarations: new Set(),
module: compilation.outputOptions.module
};
const { request, externalType } = this._getRequestAndExternalType();
this.buildMeta.exportsType = "dynamic";
let canMangle = false;
this.clearDependenciesAndBlocks();
switch (externalType) {
case "this":
this.buildInfo.strict = false;
break;
case "system":
if (!Array.isArray(request) || request.length === 1) {
this.buildMeta.exportsType = "namespace";
canMangle = true;
}
break;
case "script":
this.buildMeta.async = true;
EnvironmentNotSupportAsyncWarning.check(
this,
compilation.runtimeTemplate,
"external script"
);
break;
case "promise":
this.buildMeta.async = true;
EnvironmentNotSupportAsyncWarning.check(
this,
compilation.runtimeTemplate,
"external promise"
);
break;
case "module":
case "import":
case "module-import": {
const type = this.getModuleImportType(externalType);
if (type === "module") {
if (this.buildInfo.module) {
if (!Array.isArray(request) || request.length === 1) {
this.buildMeta.exportsType = "namespace";
canMangle = true;
}
} else {
this.buildMeta.async = true;
EnvironmentNotSupportAsyncWarning.check(
this,
compilation.runtimeTemplate,
"external module"
);
if (!Array.isArray(request) || request.length === 1) {
this.buildMeta.exportsType = "namespace";
canMangle = false;
}
}
}
if (type === "import") {
this.buildMeta.async = true;
EnvironmentNotSupportAsyncWarning.check(
this,
compilation.runtimeTemplate,
"external import"
);
if (!Array.isArray(request) || request.length === 1) {
this.buildMeta.exportsType = "namespace";
canMangle = false;
}
}
break;
}
}
this.addDependency(new StaticExportsDependency(true, canMangle));
callback();
}
/**
* restore unsafe cache data
* @param {object} unsafeCacheData data from getUnsafeCacheData
* @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching
*/
restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory);
}
/**
* @param {ConcatenationBailoutReasonContext} context context
* @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
*/
getConcatenationBailoutReason({ moduleGraph }) {
switch (this.externalType) {
case "amd":
case "amd-require":
case "umd":
case "umd2":
case "system":
case "jsonp":
return `${this.externalType} externals can't be concatenated`;
}
return undefined;
}
_getRequestAndExternalType() {
let { request, externalType } = this;
if (typeof request === "object" && !Array.isArray(request))
request = request[externalType];
return { request, externalType };
}
/**
* @private
* @param {string | string[]} request request
* @param {string} externalType the external type
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {ModuleGraph} moduleGraph the module graph
* @param {ChunkGraph} chunkGraph the chunk graph
* @param {RuntimeSpec} runtime the runtime
* @param {DependencyMeta | undefined} dependencyMeta the dependency meta
* @returns {SourceData} the source data
*/
_getSourceData(
request,
externalType,
runtimeTemplate,
moduleGraph,
chunkGraph,
runtime,
dependencyMeta
) {
switch (externalType) {
case "this":
case "window":
case "self":
return getSourceForGlobalVariableExternal(request, this.externalType);
case "global":
return getSourceForGlobalVariableExternal(
request,
runtimeTemplate.globalObject
);
case "commonjs":
case "commonjs2":
case "commonjs-module":
case "commonjs-static":
return getSourceForCommonJsExternal(request);
case "node-commonjs":
return /** @type {BuildInfo} */ (this.buildInfo).module
? getSourceForCommonJsExternalInNodeModule(
request,
/** @type {string} */
(runtimeTemplate.outputOptions.importMetaName),
/** @type {boolean} */
(runtimeTemplate.supportNodePrefixForCoreModules())
)
: getSourceForCommonJsExternal(request);
case "amd":
case "amd-require":
case "umd":
case "umd2":
case "system":
case "jsonp": {
const id = chunkGraph.getModuleId(this);
return getSourceForAmdOrUmdExternal(
id !== null ? id : this.identifier(),
this.isOptional(moduleGraph),
request,
runtimeTemplate
);
}
case "script":
return getSourceForScriptExternal(request, runtimeTemplate);
case "module":
case "import":
case "module-import": {
const type = this.getModuleImportType(externalType);
if (type === "import") {
return getSourceForImportExternal(
request,
runtimeTemplate,
/** @type {ImportDependencyMeta} */ (dependencyMeta)
);
}
if (type === "module") {
if (!(/** @type {BuildInfo} */ (this.buildInfo).module)) {
if (!runtimeTemplate.supportsDynamicImport()) {
throw new Error(
`The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script${
runtimeTemplate.supportsEcmaScriptModuleSyntax()
? "\nDid you mean to build a EcmaScript Module ('output.module: true')?"
: ""
}`
);
}
return getSourceForImportExternal(
request,
runtimeTemplate,
/** @type {ImportDependencyMeta} */ (dependencyMeta)
);
}
if (!runtimeTemplate.supportsEcmaScriptModuleSyntax()) {
throw new Error(
"The target environment doesn't support EcmaScriptModule syntax so it's not possible to use external type 'module'"
);
}
return getSourceForModuleExternal(
request,
moduleGraph.getExportsInfo(this),
runtime,
runtimeTemplate,
/** @type {ImportDependencyMeta} */ (dependencyMeta)
);
}
break;
}
case "var":
case "promise":
case "const":
case "let":
case "assign":
default:
return getSourceForDefaultCase(
this.isOptional(moduleGraph),
request,
runtimeTemplate
);
}
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration({
runtimeTemplate,
moduleGraph,
chunkGraph,
runtime,
concatenationScope
}) {
const { request, externalType } = this._getRequestAndExternalType();
switch (externalType) {
case "asset": {
const sources = new Map();
sources.set(
"javascript",
new RawSource(`module.exports = ${JSON.stringify(request)};`)
);
const data = new Map();
data.set("url", request);
return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS, data };
}
case "css-import": {
const sources = new Map();
const dependencyMeta = /** @type {CssImportDependencyMeta} */ (
this.dependencyMeta
);
const layer =
dependencyMeta.layer !== undefined
? ` layer(${dependencyMeta.layer})`
: "";
const supports = dependencyMeta.supports
? ` supports(${dependencyMeta.supports})`
: "";
const media = dependencyMeta.media ? ` ${dependencyMeta.media}` : "";
sources.set(
"css-import",
new RawSource(
`@import url(${JSON.stringify(
request
)})${layer}${supports}${media};`
)
);
return {
sources,
runtimeRequirements: EMPTY_RUNTIME_REQUIREMENTS
};
}
default: {
const sourceData = this._getSourceData(
request,
externalType,
runtimeTemplate,
moduleGraph,
chunkGraph,
runtime,
this.dependencyMeta
);
let sourceString = sourceData.expression;
if (sourceData.iife)
sourceString = `(function() { return ${sourceString}; }())`;
if (concatenationScope) {
sourceString = `${
runtimeTemplate.supportsConst() ? "const" : "var"
} ${ConcatenationScope.NAMESPACE_OBJECT_EXPORT} = ${sourceString};`;
concatenationScope.registerNamespaceExport(
ConcatenationScope.NAMESPACE_OBJECT_EXPORT
);
} else {
sourceString = `module.exports = ${sourceString};`;
}
if (sourceData.init)
sourceString = `${sourceData.init}\n${sourceString}`;
let data;
if (sourceData.chunkInitFragments) {
data = new Map();
data.set("chunkInitFragments", sourceData.chunkInitFragments);
}
const sources = new Map();
if (this.useSourceMap || this.useSimpleSourceMap) {
sources.set(
"javascript",
new OriginalSource(sourceString, this.identifier())
);
} else {
sources.set("javascript", new RawSource(sourceString));
}
let runtimeRequirements = sourceData.runtimeRequirements;
if (!concatenationScope) {
if (!runtimeRequirements) {
runtimeRequirements = RUNTIME_REQUIREMENTS;
} else {
const set = new Set(runtimeRequirements);
set.add(RuntimeGlobals.module);
runtimeRequirements = set;
}
}
return {
sources,
runtimeRequirements:
runtimeRequirements || EMPTY_RUNTIME_REQUIREMENTS,
data
};
}
}
}
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
return 42;
}
/**
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
const { chunkGraph } = context;
hash.update(
`${this.externalType}${JSON.stringify(this.request)}${this.isOptional(
chunkGraph.moduleGraph
)}`
);
super.updateHash(hash, context);
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.request);
write(this.externalType);
write(this.userRequest);
write(this.dependencyMeta);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
this.request = read();
this.externalType = read();
this.userRequest = read();
this.dependencyMeta = read();
super.deserialize(context);
}
}
makeSerializable(ExternalModule, "webpack/lib/ExternalModule");
module.exports = ExternalModule;

302
node_modules/webpack/lib/ExternalModuleFactoryPlugin.js generated vendored Normal file
View file

@ -0,0 +1,302 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
const ExternalModule = require("./ExternalModule");
const ContextElementDependency = require("./dependencies/ContextElementDependency");
const CssImportDependency = require("./dependencies/CssImportDependency");
const HarmonyImportDependency = require("./dependencies/HarmonyImportDependency");
const ImportDependency = require("./dependencies/ImportDependency");
const { resolveByProperty, cachedSetProperty } = require("./util/cleverMerge");
/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */
/** @typedef {import("./Compilation").DepConstructor} DepConstructor */
/** @typedef {import("./ExternalModule").DependencyMeta} DependencyMeta */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
const UNSPECIFIED_EXTERNAL_TYPE_REGEXP = /^[a-z0-9-]+ /;
const EMPTY_RESOLVE_OPTIONS = {};
// TODO webpack 6 remove this
const callDeprecatedExternals = util.deprecate(
(externalsFunction, context, request, cb) => {
// eslint-disable-next-line no-useless-call
externalsFunction.call(null, context, request, cb);
},
"The externals-function should be defined like ({context, request}, cb) => { ... }",
"DEP_WEBPACK_EXTERNALS_FUNCTION_PARAMETERS"
);
const cache = new WeakMap();
/**
* @param {object} obj obj
* @param {TODO} layer layer
* @returns {object} result
*/
const resolveLayer = (obj, layer) => {
let map = cache.get(obj);
if (map === undefined) {
map = new Map();
cache.set(obj, map);
} else {
const cacheEntry = map.get(layer);
if (cacheEntry !== undefined) return cacheEntry;
}
const result = resolveByProperty(obj, "byLayer", layer);
map.set(layer, result);
return result;
};
/** @typedef {string|string[]|boolean|Record<string, string|string[]>} ExternalValue */
/** @typedef {string|undefined} ExternalType */
class ExternalModuleFactoryPlugin {
/**
* @param {string | undefined} type default external type
* @param {Externals} externals externals config
*/
constructor(type, externals) {
this.type = type;
this.externals = externals;
}
/**
* @param {NormalModuleFactory} normalModuleFactory the normal module factory
* @returns {void}
*/
apply(normalModuleFactory) {
const globalType = this.type;
normalModuleFactory.hooks.factorize.tapAsync(
"ExternalModuleFactoryPlugin",
(data, callback) => {
const context = data.context;
const contextInfo = data.contextInfo;
const dependency = data.dependencies[0];
const dependencyType = data.dependencyType;
/**
* @param {ExternalValue} value the external config
* @param {ExternalType | undefined} type type of external
* @param {function((Error | null)=, ExternalModule=): void} callback callback
* @returns {void}
*/
const handleExternal = (value, type, callback) => {
if (value === false) {
// Not externals, fallback to original factory
return callback();
}
/** @type {string | string[] | Record<string, string|string[]>} */
let externalConfig = value === true ? dependency.request : value;
// When no explicit type is specified, extract it from the externalConfig
if (type === undefined) {
if (
typeof externalConfig === "string" &&
UNSPECIFIED_EXTERNAL_TYPE_REGEXP.test(externalConfig)
) {
const idx = externalConfig.indexOf(" ");
type = externalConfig.slice(0, idx);
externalConfig = externalConfig.slice(idx + 1);
} else if (
Array.isArray(externalConfig) &&
externalConfig.length > 0 &&
UNSPECIFIED_EXTERNAL_TYPE_REGEXP.test(externalConfig[0])
) {
const firstItem = externalConfig[0];
const idx = firstItem.indexOf(" ");
type = firstItem.slice(0, idx);
externalConfig = [
firstItem.slice(idx + 1),
...externalConfig.slice(1)
];
}
}
// TODO make it pluggable/add hooks to `ExternalModule` to allow output modules own externals?
/** @type {DependencyMeta | undefined} */
let dependencyMeta;
if (
dependency instanceof HarmonyImportDependency ||
dependency instanceof ImportDependency ||
dependency instanceof ContextElementDependency
) {
const externalType =
dependency instanceof HarmonyImportDependency
? "module"
: dependency instanceof ImportDependency
? "import"
: undefined;
dependencyMeta = {
attributes: dependency.assertions,
externalType
};
} else if (dependency instanceof CssImportDependency) {
dependencyMeta = {
layer: dependency.layer,
supports: dependency.supports,
media: dependency.media
};
}
callback(
null,
new ExternalModule(
externalConfig,
/** @type {string} */
(type || globalType),
dependency.request,
dependencyMeta
)
);
};
/**
* @param {Externals} externals externals config
* @param {function((Error | null)=, ExternalModule=): void} callback callback
* @returns {void}
*/
const handleExternals = (externals, callback) => {
if (typeof externals === "string") {
if (externals === dependency.request) {
return handleExternal(dependency.request, undefined, callback);
}
} else if (Array.isArray(externals)) {
let i = 0;
const next = () => {
/** @type {boolean | undefined} */
let asyncFlag;
/**
* @param {(Error | null)=} err err
* @param {ExternalModule=} module module
* @returns {void}
*/
const handleExternalsAndCallback = (err, module) => {
if (err) return callback(err);
if (!module) {
if (asyncFlag) {
asyncFlag = false;
return;
}
return next();
}
callback(null, module);
};
do {
asyncFlag = true;
if (i >= externals.length) return callback();
handleExternals(externals[i++], handleExternalsAndCallback);
} while (!asyncFlag);
asyncFlag = false;
};
next();
return;
} else if (externals instanceof RegExp) {
if (externals.test(dependency.request)) {
return handleExternal(dependency.request, undefined, callback);
}
} else if (typeof externals === "function") {
const cb = (err, value, type) => {
if (err) return callback(err);
if (value !== undefined) {
handleExternal(value, type, callback);
} else {
callback();
}
};
if (externals.length === 3) {
// TODO webpack 6 remove this
callDeprecatedExternals(
externals,
context,
dependency.request,
cb
);
} else {
const promise = externals(
{
context,
request: dependency.request,
dependencyType,
contextInfo,
getResolve: options => (context, request, callback) => {
const resolveContext = {
fileDependencies: data.fileDependencies,
missingDependencies: data.missingDependencies,
contextDependencies: data.contextDependencies
};
let resolver = normalModuleFactory.getResolver(
"normal",
dependencyType
? cachedSetProperty(
data.resolveOptions || EMPTY_RESOLVE_OPTIONS,
"dependencyType",
dependencyType
)
: data.resolveOptions
);
if (options) resolver = resolver.withOptions(options);
if (callback) {
resolver.resolve(
{},
context,
request,
resolveContext,
callback
);
} else {
return new Promise((resolve, reject) => {
resolver.resolve(
{},
context,
request,
resolveContext,
(err, result) => {
if (err) reject(err);
else resolve(result);
}
);
});
}
}
},
cb
);
if (promise && promise.then) promise.then(r => cb(null, r), cb);
}
return;
} else if (typeof externals === "object") {
const resolvedExternals = resolveLayer(
externals,
contextInfo.issuerLayer
);
if (
Object.prototype.hasOwnProperty.call(
resolvedExternals,
dependency.request
)
) {
return handleExternal(
resolvedExternals[dependency.request],
undefined,
callback
);
}
}
callback();
};
handleExternals(this.externals, callback);
}
);
}
}
module.exports = ExternalModuleFactoryPlugin;

37
node_modules/webpack/lib/ExternalsPlugin.js generated vendored Normal file
View file

@ -0,0 +1,37 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin");
/** @typedef {import("../declarations/WebpackOptions").Externals} Externals */
/** @typedef {import("./Compiler")} Compiler */
class ExternalsPlugin {
/**
* @param {string | undefined} type default external type
* @param {Externals} externals externals config
*/
constructor(type, externals) {
this.type = type;
this.externals = externals;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compile.tap("ExternalsPlugin", ({ normalModuleFactory }) => {
new ExternalModuleFactoryPlugin(this.type, this.externals).apply(
normalModuleFactory
);
});
}
}
module.exports = ExternalsPlugin;

55
node_modules/webpack/lib/FlagAllModulesAsUsedPlugin.js generated vendored Normal file
View file

@ -0,0 +1,55 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { getEntryRuntime, mergeRuntimeOwned } = require("./util/runtime");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module").FactoryMeta} FactoryMeta */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
const PLUGIN_NAME = "FlagAllModulesAsUsedPlugin";
class FlagAllModulesAsUsedPlugin {
/**
* @param {string} explanation explanation
*/
constructor(explanation) {
this.explanation = explanation;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
const moduleGraph = compilation.moduleGraph;
compilation.hooks.optimizeDependencies.tap(PLUGIN_NAME, modules => {
/** @type {RuntimeSpec} */
let runtime;
for (const [name, { options }] of compilation.entries) {
runtime = mergeRuntimeOwned(
runtime,
getEntryRuntime(compilation, name, options)
);
}
for (const module of modules) {
const exportsInfo = moduleGraph.getExportsInfo(module);
exportsInfo.setUsedInUnknownWay(runtime);
moduleGraph.addExtraReason(module, this.explanation);
if (module.factoryMeta === undefined) {
module.factoryMeta = {};
}
/** @type {FactoryMeta} */
(module.factoryMeta).sideEffectFree = false;
}
});
});
}
}
module.exports = FlagAllModulesAsUsedPlugin;

420
node_modules/webpack/lib/FlagDependencyExportsPlugin.js generated vendored Normal file
View file

@ -0,0 +1,420 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const Queue = require("./util/Queue");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Dependency").ExportSpec} ExportSpec */
/** @typedef {import("./Dependency").ExportsSpec} ExportsSpec */
/** @typedef {import("./ExportsInfo")} ExportsInfo */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
const PLUGIN_NAME = "FlagDependencyExportsPlugin";
const PLUGIN_LOGGER_NAME = `webpack.${PLUGIN_NAME}`;
class FlagDependencyExportsPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
const moduleGraph = compilation.moduleGraph;
const cache = compilation.getCache(PLUGIN_NAME);
compilation.hooks.finishModules.tapAsync(
PLUGIN_NAME,
(modules, callback) => {
const logger = compilation.getLogger(PLUGIN_LOGGER_NAME);
let statRestoredFromMemCache = 0;
let statRestoredFromCache = 0;
let statNoExports = 0;
let statFlaggedUncached = 0;
let statNotCached = 0;
let statQueueItemsProcessed = 0;
const { moduleMemCaches } = compilation;
/** @type {Queue<Module>} */
const queue = new Queue();
// Step 1: Try to restore cached provided export info from cache
logger.time("restore cached provided exports");
asyncLib.each(
modules,
(module, callback) => {
const exportsInfo = moduleGraph.getExportsInfo(module);
// If the module doesn't have an exportsType, it's a module
// without declared exports.
if (
(!module.buildMeta || !module.buildMeta.exportsType) &&
exportsInfo.otherExportsInfo.provided !== null
) {
// It's a module without declared exports
statNoExports++;
exportsInfo.setHasProvideInfo();
exportsInfo.setUnknownExportsProvided();
return callback();
}
// If the module has no hash, it's uncacheable
if (
typeof (/** @type {BuildInfo} */ (module.buildInfo).hash) !==
"string"
) {
statFlaggedUncached++;
// Enqueue uncacheable module for determining the exports
queue.enqueue(module);
exportsInfo.setHasProvideInfo();
return callback();
}
const memCache = moduleMemCaches && moduleMemCaches.get(module);
const memCacheValue = memCache && memCache.get(this);
if (memCacheValue !== undefined) {
statRestoredFromMemCache++;
exportsInfo.restoreProvided(memCacheValue);
return callback();
}
cache.get(
module.identifier(),
/** @type {BuildInfo} */
(module.buildInfo).hash,
(err, result) => {
if (err) return callback(err);
if (result !== undefined) {
statRestoredFromCache++;
exportsInfo.restoreProvided(result);
} else {
statNotCached++;
// Without cached info enqueue module for determining the exports
queue.enqueue(module);
exportsInfo.setHasProvideInfo();
}
callback();
}
);
},
err => {
logger.timeEnd("restore cached provided exports");
if (err) return callback(err);
/** @type {Set<Module>} */
const modulesToStore = new Set();
/** @type {Map<Module, Set<Module>>} */
const dependencies = new Map();
/** @type {Module} */
let module;
/** @type {ExportsInfo} */
let exportsInfo;
/** @type {Map<Dependency, ExportsSpec>} */
const exportsSpecsFromDependencies = new Map();
let cacheable = true;
let changed = false;
/**
* @param {DependenciesBlock} depBlock the dependencies block
* @returns {void}
*/
const processDependenciesBlock = depBlock => {
for (const dep of depBlock.dependencies) {
processDependency(dep);
}
for (const block of depBlock.blocks) {
processDependenciesBlock(block);
}
};
/**
* @param {Dependency} dep the dependency
* @returns {void}
*/
const processDependency = dep => {
const exportDesc = dep.getExports(moduleGraph);
if (!exportDesc) return;
exportsSpecsFromDependencies.set(dep, exportDesc);
};
/**
* @param {Dependency} dep dependency
* @param {ExportsSpec} exportDesc info
* @returns {void}
*/
const processExportsSpec = (dep, exportDesc) => {
const exports = exportDesc.exports;
const globalCanMangle = exportDesc.canMangle;
const globalFrom = exportDesc.from;
const globalPriority = exportDesc.priority;
const globalTerminalBinding =
exportDesc.terminalBinding || false;
const exportDeps = exportDesc.dependencies;
if (exportDesc.hideExports) {
for (const name of exportDesc.hideExports) {
const exportInfo = exportsInfo.getExportInfo(name);
exportInfo.unsetTarget(dep);
}
}
if (exports === true) {
// unknown exports
if (
exportsInfo.setUnknownExportsProvided(
globalCanMangle,
exportDesc.excludeExports,
globalFrom && dep,
globalFrom,
globalPriority
)
) {
changed = true;
}
} else if (Array.isArray(exports)) {
/**
* merge in new exports
* @param {ExportsInfo} exportsInfo own exports info
* @param {(ExportSpec | string)[]} exports list of exports
*/
const mergeExports = (exportsInfo, exports) => {
for (const exportNameOrSpec of exports) {
let name;
let canMangle = globalCanMangle;
let terminalBinding = globalTerminalBinding;
let exports;
let from = globalFrom;
let fromExport;
let priority = globalPriority;
let hidden = false;
if (typeof exportNameOrSpec === "string") {
name = exportNameOrSpec;
} else {
name = exportNameOrSpec.name;
if (exportNameOrSpec.canMangle !== undefined)
canMangle = exportNameOrSpec.canMangle;
if (exportNameOrSpec.export !== undefined)
fromExport = exportNameOrSpec.export;
if (exportNameOrSpec.exports !== undefined)
exports = exportNameOrSpec.exports;
if (exportNameOrSpec.from !== undefined)
from = exportNameOrSpec.from;
if (exportNameOrSpec.priority !== undefined)
priority = exportNameOrSpec.priority;
if (exportNameOrSpec.terminalBinding !== undefined)
terminalBinding = exportNameOrSpec.terminalBinding;
if (exportNameOrSpec.hidden !== undefined)
hidden = exportNameOrSpec.hidden;
}
const exportInfo = exportsInfo.getExportInfo(name);
if (
exportInfo.provided === false ||
exportInfo.provided === null
) {
exportInfo.provided = true;
changed = true;
}
if (
exportInfo.canMangleProvide !== false &&
canMangle === false
) {
exportInfo.canMangleProvide = false;
changed = true;
}
if (terminalBinding && !exportInfo.terminalBinding) {
exportInfo.terminalBinding = true;
changed = true;
}
if (exports) {
const nestedExportsInfo =
exportInfo.createNestedExportsInfo();
mergeExports(
/** @type {ExportsInfo} */ (nestedExportsInfo),
exports
);
}
if (
from &&
(hidden
? exportInfo.unsetTarget(dep)
: exportInfo.setTarget(
dep,
from,
fromExport === undefined ? [name] : fromExport,
priority
))
) {
changed = true;
}
// Recalculate target exportsInfo
const target = exportInfo.getTarget(moduleGraph);
let targetExportsInfo;
if (target) {
const targetModuleExportsInfo =
moduleGraph.getExportsInfo(target.module);
targetExportsInfo =
targetModuleExportsInfo.getNestedExportsInfo(
target.export
);
// add dependency for this module
const set = dependencies.get(target.module);
if (set === undefined) {
dependencies.set(target.module, new Set([module]));
} else {
set.add(module);
}
}
if (exportInfo.exportsInfoOwned) {
if (
/** @type {ExportsInfo} */
(exportInfo.exportsInfo).setRedirectNamedTo(
targetExportsInfo
)
) {
changed = true;
}
} else if (exportInfo.exportsInfo !== targetExportsInfo) {
exportInfo.exportsInfo = targetExportsInfo;
changed = true;
}
}
};
mergeExports(exportsInfo, exports);
}
// store dependencies
if (exportDeps) {
cacheable = false;
for (const exportDependency of exportDeps) {
// add dependency for this module
const set = dependencies.get(exportDependency);
if (set === undefined) {
dependencies.set(exportDependency, new Set([module]));
} else {
set.add(module);
}
}
}
};
const notifyDependencies = () => {
const deps = dependencies.get(module);
if (deps !== undefined) {
for (const dep of deps) {
queue.enqueue(dep);
}
}
};
logger.time("figure out provided exports");
while (queue.length > 0) {
module = /** @type {Module} */ (queue.dequeue());
statQueueItemsProcessed++;
exportsInfo = moduleGraph.getExportsInfo(module);
cacheable = true;
changed = false;
exportsSpecsFromDependencies.clear();
moduleGraph.freeze();
processDependenciesBlock(module);
moduleGraph.unfreeze();
for (const [dep, exportsSpec] of exportsSpecsFromDependencies) {
processExportsSpec(dep, exportsSpec);
}
if (cacheable) {
modulesToStore.add(module);
}
if (changed) {
notifyDependencies();
}
}
logger.timeEnd("figure out provided exports");
logger.log(
`${Math.round(
(100 * (statFlaggedUncached + statNotCached)) /
(statRestoredFromMemCache +
statRestoredFromCache +
statNotCached +
statFlaggedUncached +
statNoExports)
)}% of exports of modules have been determined (${statNoExports} no declared exports, ${statNotCached} not cached, ${statFlaggedUncached} flagged uncacheable, ${statRestoredFromCache} from cache, ${statRestoredFromMemCache} from mem cache, ${
statQueueItemsProcessed - statNotCached - statFlaggedUncached
} additional calculations due to dependencies)`
);
logger.time("store provided exports into cache");
asyncLib.each(
modulesToStore,
(module, callback) => {
if (
typeof (
/** @type {BuildInfo} */ (module.buildInfo).hash
) !== "string"
) {
// not cacheable
return callback();
}
const cachedData = moduleGraph
.getExportsInfo(module)
.getRestoreProvidedData();
const memCache =
moduleMemCaches && moduleMemCaches.get(module);
if (memCache) {
memCache.set(this, cachedData);
}
cache.store(
module.identifier(),
/** @type {BuildInfo} */
(module.buildInfo).hash,
cachedData,
callback
);
},
err => {
logger.timeEnd("store provided exports into cache");
callback(err);
}
);
}
);
}
);
/** @type {WeakMap<Module, any>} */
const providedExportsCache = new WeakMap();
compilation.hooks.rebuildModule.tap(PLUGIN_NAME, module => {
providedExportsCache.set(
module,
moduleGraph.getExportsInfo(module).getRestoreProvidedData()
);
});
compilation.hooks.finishRebuildingModule.tap(PLUGIN_NAME, module => {
moduleGraph
.getExportsInfo(module)
.restoreProvided(providedExportsCache.get(module));
});
});
}
}
module.exports = FlagDependencyExportsPlugin;

347
node_modules/webpack/lib/FlagDependencyUsagePlugin.js generated vendored Normal file
View file

@ -0,0 +1,347 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Dependency = require("./Dependency");
const { UsageState } = require("./ExportsInfo");
const ModuleGraphConnection = require("./ModuleGraphConnection");
const { STAGE_DEFAULT } = require("./OptimizationStages");
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("./ExportsInfo")} ExportsInfo */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
const { NO_EXPORTS_REFERENCED, EXPORTS_OBJECT_REFERENCED } = Dependency;
const PLUGIN_NAME = "FlagDependencyUsagePlugin";
const PLUGIN_LOGGER_NAME = `webpack.${PLUGIN_NAME}`;
class FlagDependencyUsagePlugin {
/**
* @param {boolean} global do a global analysis instead of per runtime
*/
constructor(global) {
this.global = global;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
const moduleGraph = compilation.moduleGraph;
compilation.hooks.optimizeDependencies.tap(
{ name: PLUGIN_NAME, stage: STAGE_DEFAULT },
modules => {
if (compilation.moduleMemCaches) {
throw new Error(
"optimization.usedExports can't be used with cacheUnaffected as export usage is a global effect"
);
}
const logger = compilation.getLogger(PLUGIN_LOGGER_NAME);
/** @type {Map<ExportsInfo, Module>} */
const exportInfoToModuleMap = new Map();
/** @type {TupleQueue<[Module, RuntimeSpec]>} */
const queue = new TupleQueue();
/**
* @param {Module} module module to process
* @param {(string[] | ReferencedExport)[]} usedExports list of used exports
* @param {RuntimeSpec} runtime part of which runtime
* @param {boolean} forceSideEffects always apply side effects
* @returns {void}
*/
const processReferencedModule = (
module,
usedExports,
runtime,
forceSideEffects
) => {
const exportsInfo = moduleGraph.getExportsInfo(module);
if (usedExports.length > 0) {
if (!module.buildMeta || !module.buildMeta.exportsType) {
if (exportsInfo.setUsedWithoutInfo(runtime)) {
queue.enqueue(module, runtime);
}
return;
}
for (const usedExportInfo of usedExports) {
let usedExport;
let canMangle = true;
if (Array.isArray(usedExportInfo)) {
usedExport = usedExportInfo;
} else {
usedExport = usedExportInfo.name;
canMangle = usedExportInfo.canMangle !== false;
}
if (usedExport.length === 0) {
if (exportsInfo.setUsedInUnknownWay(runtime)) {
queue.enqueue(module, runtime);
}
} else {
let currentExportsInfo = exportsInfo;
for (let i = 0; i < usedExport.length; i++) {
const exportInfo = currentExportsInfo.getExportInfo(
usedExport[i]
);
if (canMangle === false) {
exportInfo.canMangleUse = false;
}
const lastOne = i === usedExport.length - 1;
if (!lastOne) {
const nestedInfo = exportInfo.getNestedExportsInfo();
if (nestedInfo) {
if (
exportInfo.setUsedConditionally(
used => used === UsageState.Unused,
UsageState.OnlyPropertiesUsed,
runtime
)
) {
const currentModule =
currentExportsInfo === exportsInfo
? module
: exportInfoToModuleMap.get(currentExportsInfo);
if (currentModule) {
queue.enqueue(currentModule, runtime);
}
}
currentExportsInfo = nestedInfo;
continue;
}
}
if (
exportInfo.setUsedConditionally(
v => v !== UsageState.Used,
UsageState.Used,
runtime
)
) {
const currentModule =
currentExportsInfo === exportsInfo
? module
: exportInfoToModuleMap.get(currentExportsInfo);
if (currentModule) {
queue.enqueue(currentModule, runtime);
}
}
break;
}
}
}
} else {
// for a module without side effects we stop tracking usage here when no export is used
// This module won't be evaluated in this case
// TODO webpack 6 remove this check
if (
!forceSideEffects &&
module.factoryMeta !== undefined &&
module.factoryMeta.sideEffectFree
) {
return;
}
if (exportsInfo.setUsedForSideEffectsOnly(runtime)) {
queue.enqueue(module, runtime);
}
}
};
/**
* @param {DependenciesBlock} module the module
* @param {RuntimeSpec} runtime part of which runtime
* @param {boolean} forceSideEffects always apply side effects
* @returns {void}
*/
const processModule = (module, runtime, forceSideEffects) => {
/** @type {Map<Module, (string[] | ReferencedExport)[] | Map<string, string[] | ReferencedExport>>} */
const map = new Map();
/** @type {ArrayQueue<DependenciesBlock>} */
const queue = new ArrayQueue();
queue.enqueue(module);
for (;;) {
const block = queue.dequeue();
if (block === undefined) break;
for (const b of block.blocks) {
if (
!this.global &&
b.groupOptions &&
b.groupOptions.entryOptions
) {
processModule(
b,
b.groupOptions.entryOptions.runtime || undefined,
true
);
} else {
queue.enqueue(b);
}
}
for (const dep of block.dependencies) {
const connection = moduleGraph.getConnection(dep);
if (!connection || !connection.module) {
continue;
}
const activeState = connection.getActiveState(runtime);
if (activeState === false) continue;
const { module } = connection;
if (activeState === ModuleGraphConnection.TRANSITIVE_ONLY) {
processModule(module, runtime, false);
continue;
}
const oldReferencedExports = map.get(module);
if (oldReferencedExports === EXPORTS_OBJECT_REFERENCED) {
continue;
}
const referencedExports =
compilation.getDependencyReferencedExports(dep, runtime);
if (
oldReferencedExports === undefined ||
oldReferencedExports === NO_EXPORTS_REFERENCED ||
referencedExports === EXPORTS_OBJECT_REFERENCED
) {
map.set(module, referencedExports);
} else if (
oldReferencedExports !== undefined &&
referencedExports === NO_EXPORTS_REFERENCED
) {
continue;
} else {
let exportsMap;
if (Array.isArray(oldReferencedExports)) {
exportsMap = new Map();
for (const item of oldReferencedExports) {
if (Array.isArray(item)) {
exportsMap.set(item.join("\n"), item);
} else {
exportsMap.set(item.name.join("\n"), item);
}
}
map.set(module, exportsMap);
} else {
exportsMap = oldReferencedExports;
}
for (const item of referencedExports) {
if (Array.isArray(item)) {
const key = item.join("\n");
const oldItem = exportsMap.get(key);
if (oldItem === undefined) {
exportsMap.set(key, item);
}
// if oldItem is already an array we have to do nothing
// if oldItem is an ReferencedExport object, we don't have to do anything
// as canMangle defaults to true for arrays
} else {
const key = item.name.join("\n");
const oldItem = exportsMap.get(key);
if (oldItem === undefined || Array.isArray(oldItem)) {
exportsMap.set(key, item);
} else {
exportsMap.set(key, {
name: item.name,
canMangle: item.canMangle && oldItem.canMangle
});
}
}
}
}
}
}
for (const [module, referencedExports] of map) {
if (Array.isArray(referencedExports)) {
processReferencedModule(
module,
referencedExports,
runtime,
forceSideEffects
);
} else {
processReferencedModule(
module,
Array.from(referencedExports.values()),
runtime,
forceSideEffects
);
}
}
};
logger.time("initialize exports usage");
for (const module of modules) {
const exportsInfo = moduleGraph.getExportsInfo(module);
exportInfoToModuleMap.set(exportsInfo, module);
exportsInfo.setHasUseInfo();
}
logger.timeEnd("initialize exports usage");
logger.time("trace exports usage in graph");
/**
* @param {Dependency} dep dependency
* @param {RuntimeSpec} runtime runtime
*/
const processEntryDependency = (dep, runtime) => {
const module = moduleGraph.getModule(dep);
if (module) {
processReferencedModule(
module,
NO_EXPORTS_REFERENCED,
runtime,
true
);
}
};
/** @type {RuntimeSpec} */
let globalRuntime;
for (const [
entryName,
{ dependencies: deps, includeDependencies: includeDeps, options }
] of compilation.entries) {
const runtime = this.global
? undefined
: getEntryRuntime(compilation, entryName, options);
for (const dep of deps) {
processEntryDependency(dep, runtime);
}
for (const dep of includeDeps) {
processEntryDependency(dep, runtime);
}
globalRuntime = mergeRuntimeOwned(globalRuntime, runtime);
}
for (const dep of compilation.globalEntry.dependencies) {
processEntryDependency(dep, globalRuntime);
}
for (const dep of compilation.globalEntry.includeDependencies) {
processEntryDependency(dep, globalRuntime);
}
while (queue.length) {
const [module, runtime] = /** @type {[Module, RuntimeSpec]} */ (
queue.dequeue()
);
processModule(module, runtime, false);
}
logger.timeEnd("trace exports usage in graph");
}
);
});
}
}
module.exports = FlagDependencyUsagePlugin;

154
node_modules/webpack/lib/Generator.js generated vendored Normal file
View file

@ -0,0 +1,154 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./ConcatenationScope")} ConcatenationScope */
/** @typedef {import("./DependencyTemplate")} DependencyTemplate */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/**
* @typedef {object} GenerateContext
* @property {DependencyTemplates} dependencyTemplates mapping from dependencies to templates
* @property {RuntimeTemplate} runtimeTemplate the runtime template
* @property {ModuleGraph} moduleGraph the module graph
* @property {ChunkGraph} chunkGraph the chunk graph
* @property {RuntimeRequirements} runtimeRequirements the requirements for runtime
* @property {RuntimeSpec} runtime the runtime
* @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 {function(): Map<string, any>=} getData get access to the code generation data
*/
/**
* @typedef {object} UpdateHashContext
* @property {NormalModule} module the module
* @property {ChunkGraph} chunkGraph
* @property {RuntimeSpec} runtime
* @property {RuntimeTemplate=} runtimeTemplate
*/
class Generator {
/**
* @param {Record<string, Generator>} map map of types
* @returns {ByTypeGenerator} generator by type
*/
static byType(map) {
return new ByTypeGenerator(map);
}
/* istanbul ignore next */
/**
* @abstract
* @param {NormalModule} module fresh module
* @returns {Set<string>} available types (do not mutate)
*/
getTypes(module) {
const AbstractMethodError = require("./AbstractMethodError");
throw new AbstractMethodError();
}
/* istanbul ignore next */
/**
* @abstract
* @param {NormalModule} module the module
* @param {string=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {
const AbstractMethodError = require("./AbstractMethodError");
throw new AbstractMethodError();
}
/* istanbul ignore next */
/**
* @abstract
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source} generated code
*/
generate(
module,
{ dependencyTemplates, runtimeTemplate, moduleGraph, type }
) {
const AbstractMethodError = require("./AbstractMethodError");
throw new AbstractMethodError();
}
/**
* @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 `Module Concatenation is not implemented for ${this.constructor.name}`;
}
/**
* @param {Hash} hash hash that will be modified
* @param {UpdateHashContext} updateHashContext context for updating hash
*/
updateHash(hash, { module, runtime }) {
// no nothing
}
}
class ByTypeGenerator extends Generator {
/**
* @param {Record<string, Generator>} map map of types
*/
constructor(map) {
super();
this.map = map;
this._types = new Set(Object.keys(map));
}
/**
* @param {NormalModule} module fresh module
* @returns {Set<string>} available types (do not mutate)
*/
getTypes(module) {
return this._types;
}
/**
* @param {NormalModule} module the module
* @param {string=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type = "javascript") {
const t = type;
const generator = this.map[t];
return generator ? generator.getSize(module, t) : 0;
}
/**
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source} generated code
*/
generate(module, generateContext) {
const type = generateContext.type;
const generator = this.map[type];
if (!generator) {
throw new Error(`Generator.byType: no generator specified for ${type}`);
}
return generator.generate(module, generateContext);
}
}
module.exports = Generator;

38
node_modules/webpack/lib/GraphHelpers.js generated vendored Normal file
View file

@ -0,0 +1,38 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./ChunkGroup")} ChunkGroup */
/** @typedef {import("./DependenciesBlock")} DependenciesBlock */
/** @typedef {import("./Module")} Module */
/**
* @param {ChunkGroup} chunkGroup the ChunkGroup to connect
* @param {Chunk} chunk chunk to tie to ChunkGroup
* @returns {void}
*/
const connectChunkGroupAndChunk = (chunkGroup, chunk) => {
if (chunkGroup.pushChunk(chunk)) {
chunk.addGroup(chunkGroup);
}
};
/**
* @param {ChunkGroup} parent parent ChunkGroup to connect
* @param {ChunkGroup} child child ChunkGroup to connect
* @returns {void}
*/
const connectChunkGroupParentAndChild = (parent, child) => {
if (parent.addChild(child)) {
child.addParent(parent);
}
};
module.exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk;
module.exports.connectChunkGroupParentAndChild =
connectChunkGroupParentAndChild;

16
node_modules/webpack/lib/HarmonyLinkingError.js generated vendored Normal file
View file

@ -0,0 +1,16 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
const WebpackError = require("./WebpackError");
module.exports = class HarmonyLinkingError extends WebpackError {
/** @param {string} message Error message */
constructor(message) {
super(message);
this.name = "HarmonyLinkingError";
this.hideStack = true;
}
};

869
node_modules/webpack/lib/HotModuleReplacementPlugin.js generated vendored Normal file
View file

@ -0,0 +1,869 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { SyncBailHook } = require("tapable");
const { RawSource } = require("webpack-sources");
const ChunkGraph = require("./ChunkGraph");
const Compilation = require("./Compilation");
const HotUpdateChunk = require("./HotUpdateChunk");
const NormalModule = require("./NormalModule");
const RuntimeGlobals = require("./RuntimeGlobals");
const WebpackError = require("./WebpackError");
const ConstDependency = require("./dependencies/ConstDependency");
const ImportMetaHotAcceptDependency = require("./dependencies/ImportMetaHotAcceptDependency");
const ImportMetaHotDeclineDependency = require("./dependencies/ImportMetaHotDeclineDependency");
const ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency");
const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency");
const HotModuleReplacementRuntimeModule = require("./hmr/HotModuleReplacementRuntimeModule");
const JavascriptParser = require("./javascript/JavascriptParser");
const {
evaluateToIdentifier
} = require("./javascript/JavascriptParserHelpers");
const { find, isSubset } = require("./util/SetHelpers");
const TupleSet = require("./util/TupleSet");
const { compareModulesById } = require("./util/comparators");
const {
getRuntimeKey,
keyToRuntime,
forEachRuntime,
mergeRuntimeOwned,
subtractRuntime,
intersectRuntime
} = require("./util/runtime");
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM,
WEBPACK_MODULE_TYPE_RUNTIME
} = require("./ModuleTypeConstants");
/** @typedef {import("estree").CallExpression} CallExpression */
/** @typedef {import("estree").Expression} Expression */
/** @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("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./Module").BuildInfo} BuildInfo */
/** @typedef {import("./RuntimeModule")} RuntimeModule */
/** @typedef {import("./javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
/** @typedef {import("./javascript/JavascriptParserHelpers").Range} Range */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
/**
* @typedef {object} HMRJavascriptParserHooks
* @property {SyncBailHook<[TODO, string[]], void>} hotAcceptCallback
* @property {SyncBailHook<[TODO, string[]], void>} hotAcceptWithoutCallback
*/
/** @typedef {{ updatedChunkIds: Set<ChunkId>, removedChunkIds: Set<ChunkId>, removedModules: Set<Module>, filename: string, assetInfo: AssetInfo }} HotUpdateMainContentByRuntimeItem */
/** @typedef {Map<string, HotUpdateMainContentByRuntimeItem>} HotUpdateMainContentByRuntime */
/** @type {WeakMap<JavascriptParser, HMRJavascriptParserHooks>} */
const parserHooksMap = new WeakMap();
const PLUGIN_NAME = "HotModuleReplacementPlugin";
class HotModuleReplacementPlugin {
/**
* @param {JavascriptParser} parser the parser
* @returns {HMRJavascriptParserHooks} the attached hooks
*/
static getParserHooks(parser) {
if (!(parser instanceof JavascriptParser)) {
throw new TypeError(
"The 'parser' argument must be an instance of JavascriptParser"
);
}
let hooks = parserHooksMap.get(parser);
if (hooks === undefined) {
hooks = {
hotAcceptCallback: new SyncBailHook(["expression", "requests"]),
hotAcceptWithoutCallback: new SyncBailHook(["expression", "requests"])
};
parserHooksMap.set(parser, hooks);
}
return hooks;
}
/**
* @param {object=} options options
*/
constructor(options) {
this.options = options || {};
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const { _backCompat: backCompat } = compiler;
if (compiler.options.output.strictModuleErrorHandling === undefined)
compiler.options.output.strictModuleErrorHandling = true;
const runtimeRequirements = [RuntimeGlobals.module];
/**
* @param {JavascriptParser} parser the parser
* @param {typeof ModuleHotAcceptDependency} ParamDependency dependency
* @returns {(expr: CallExpression) => boolean | undefined} callback
*/
const createAcceptHandler = (parser, ParamDependency) => {
const { hotAcceptCallback, hotAcceptWithoutCallback } =
HotModuleReplacementPlugin.getParserHooks(parser);
return expr => {
const module = parser.state.module;
const dep = new ConstDependency(
`${module.moduleArgument}.hot.accept`,
/** @type {Range} */ (expr.callee.range),
runtimeRequirements
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
module.addPresentationalDependency(dep);
/** @type {BuildInfo} */
(module.buildInfo).moduleConcatenationBailout =
"Hot Module Replacement";
if (expr.arguments.length >= 1) {
const arg = parser.evaluateExpression(
/** @type {Expression} */ (expr.arguments[0])
);
/** @type {BasicEvaluatedExpression[]} */
let params = [];
if (arg.isString()) {
params = [arg];
} else if (arg.isArray()) {
params =
/** @type {BasicEvaluatedExpression[]} */
(arg.items).filter(param => param.isString());
}
/** @type {string[]} */
const requests = [];
if (params.length > 0) {
for (const [idx, param] of params.entries()) {
const request = /** @type {string} */ (param.string);
const dep = new ParamDependency(
request,
/** @type {Range} */ (param.range)
);
dep.optional = true;
dep.loc = Object.create(
/** @type {DependencyLocation} */ (expr.loc)
);
dep.loc.index = idx;
module.addDependency(dep);
requests.push(request);
}
if (expr.arguments.length > 1) {
hotAcceptCallback.call(expr.arguments[1], requests);
for (let i = 1; i < expr.arguments.length; i++) {
parser.walkExpression(expr.arguments[i]);
}
return true;
}
hotAcceptWithoutCallback.call(expr, requests);
return true;
}
}
parser.walkExpressions(expr.arguments);
return true;
};
};
/**
* @param {JavascriptParser} parser the parser
* @param {typeof ModuleHotDeclineDependency} ParamDependency dependency
* @returns {(expr: CallExpression) => boolean | undefined} callback
*/
const createDeclineHandler = (parser, ParamDependency) => expr => {
const module = parser.state.module;
const dep = new ConstDependency(
`${module.moduleArgument}.hot.decline`,
/** @type {Range} */ (expr.callee.range),
runtimeRequirements
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
module.addPresentationalDependency(dep);
/** @type {BuildInfo} */
(module.buildInfo).moduleConcatenationBailout = "Hot Module Replacement";
if (expr.arguments.length === 1) {
const arg = parser.evaluateExpression(expr.arguments[0]);
/** @type {BasicEvaluatedExpression[]} */
let params = [];
if (arg.isString()) {
params = [arg];
} else if (arg.isArray()) {
params =
/** @type {BasicEvaluatedExpression[]} */
(arg.items).filter(param => param.isString());
}
for (const [idx, param] of params.entries()) {
const dep = new ParamDependency(
/** @type {string} */ (param.string),
/** @type {Range} */ (param.range)
);
dep.optional = true;
dep.loc = Object.create(/** @type {DependencyLocation} */ (expr.loc));
dep.loc.index = idx;
module.addDependency(dep);
}
}
return true;
};
/**
* @param {JavascriptParser} parser the parser
* @returns {(expr: Expression) => boolean | undefined} callback
*/
const createHMRExpressionHandler = parser => expr => {
const module = parser.state.module;
const dep = new ConstDependency(
`${module.moduleArgument}.hot`,
/** @type {Range} */ (expr.range),
runtimeRequirements
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
module.addPresentationalDependency(dep);
/** @type {BuildInfo} */
(module.buildInfo).moduleConcatenationBailout = "Hot Module Replacement";
return true;
};
/**
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const applyModuleHot = parser => {
parser.hooks.evaluateIdentifier.for("module.hot").tap(
{
name: PLUGIN_NAME,
before: "NodeStuffPlugin"
},
expr =>
evaluateToIdentifier(
"module.hot",
"module",
() => ["hot"],
true
)(expr)
);
parser.hooks.call
.for("module.hot.accept")
.tap(
PLUGIN_NAME,
createAcceptHandler(parser, ModuleHotAcceptDependency)
);
parser.hooks.call
.for("module.hot.decline")
.tap(
PLUGIN_NAME,
createDeclineHandler(parser, ModuleHotDeclineDependency)
);
parser.hooks.expression
.for("module.hot")
.tap(PLUGIN_NAME, createHMRExpressionHandler(parser));
};
/**
* @param {JavascriptParser} parser the parser
* @returns {void}
*/
const applyImportMetaHot = parser => {
parser.hooks.evaluateIdentifier
.for("import.meta.webpackHot")
.tap(PLUGIN_NAME, expr =>
evaluateToIdentifier(
"import.meta.webpackHot",
"import.meta",
() => ["webpackHot"],
true
)(expr)
);
parser.hooks.call
.for("import.meta.webpackHot.accept")
.tap(
PLUGIN_NAME,
createAcceptHandler(parser, ImportMetaHotAcceptDependency)
);
parser.hooks.call
.for("import.meta.webpackHot.decline")
.tap(
PLUGIN_NAME,
createDeclineHandler(parser, ImportMetaHotDeclineDependency)
);
parser.hooks.expression
.for("import.meta.webpackHot")
.tap(PLUGIN_NAME, createHMRExpressionHandler(parser));
};
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
// This applies the HMR plugin only to the targeted compiler
// It should not affect child compilations
if (compilation.compiler !== compiler) return;
// #region module.hot.* API
compilation.dependencyFactories.set(
ModuleHotAcceptDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ModuleHotAcceptDependency,
new ModuleHotAcceptDependency.Template()
);
compilation.dependencyFactories.set(
ModuleHotDeclineDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ModuleHotDeclineDependency,
new ModuleHotDeclineDependency.Template()
);
// #endregion
// #region import.meta.webpackHot.* API
compilation.dependencyFactories.set(
ImportMetaHotAcceptDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ImportMetaHotAcceptDependency,
new ImportMetaHotAcceptDependency.Template()
);
compilation.dependencyFactories.set(
ImportMetaHotDeclineDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ImportMetaHotDeclineDependency,
new ImportMetaHotDeclineDependency.Template()
);
// #endregion
let hotIndex = 0;
/** @type {Record<string, string>} */
const fullHashChunkModuleHashes = {};
/** @type {Record<string, string>} */
const chunkModuleHashes = {};
compilation.hooks.record.tap(PLUGIN_NAME, (compilation, records) => {
if (records.hash === compilation.hash) return;
const chunkGraph = compilation.chunkGraph;
records.hash = compilation.hash;
records.hotIndex = hotIndex;
records.fullHashChunkModuleHashes = fullHashChunkModuleHashes;
records.chunkModuleHashes = chunkModuleHashes;
records.chunkHashes = {};
records.chunkRuntime = {};
for (const chunk of compilation.chunks) {
const chunkId = /** @type {ChunkId} */ (chunk.id);
records.chunkHashes[chunkId] = chunk.hash;
records.chunkRuntime[chunkId] = getRuntimeKey(chunk.runtime);
}
records.chunkModuleIds = {};
for (const chunk of compilation.chunks) {
records.chunkModuleIds[/** @type {ChunkId} */ (chunk.id)] =
Array.from(
chunkGraph.getOrderedChunkModulesIterable(
chunk,
compareModulesById(chunkGraph)
),
m => chunkGraph.getModuleId(m)
);
}
});
/** @type {TupleSet<[Module, Chunk]>} */
const updatedModules = new TupleSet();
/** @type {TupleSet<[Module, Chunk]>} */
const fullHashModules = new TupleSet();
/** @type {TupleSet<[Module, RuntimeSpec]>} */
const nonCodeGeneratedModules = new TupleSet();
compilation.hooks.fullHash.tap(PLUGIN_NAME, hash => {
const chunkGraph = compilation.chunkGraph;
const records = compilation.records;
for (const chunk of compilation.chunks) {
/**
* @param {Module} module module
* @returns {string} module hash
*/
const getModuleHash = module => {
if (
compilation.codeGenerationResults.has(module, chunk.runtime)
) {
return compilation.codeGenerationResults.getHash(
module,
chunk.runtime
);
}
nonCodeGeneratedModules.add(module, chunk.runtime);
return chunkGraph.getModuleHash(module, chunk.runtime);
};
const fullHashModulesInThisChunk =
chunkGraph.getChunkFullHashModulesSet(chunk);
if (fullHashModulesInThisChunk !== undefined) {
for (const module of fullHashModulesInThisChunk) {
fullHashModules.add(module, chunk);
}
}
const modules = chunkGraph.getChunkModulesIterable(chunk);
if (modules !== undefined) {
if (records.chunkModuleHashes) {
if (fullHashModulesInThisChunk !== undefined) {
for (const module of modules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = getModuleHash(module);
if (
fullHashModulesInThisChunk.has(
/** @type {RuntimeModule} */ (module)
)
) {
if (records.fullHashChunkModuleHashes[key] !== hash) {
updatedModules.add(module, chunk);
}
fullHashChunkModuleHashes[key] = hash;
} else {
if (records.chunkModuleHashes[key] !== hash) {
updatedModules.add(module, chunk);
}
chunkModuleHashes[key] = hash;
}
}
} else {
for (const module of modules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = getModuleHash(module);
if (records.chunkModuleHashes[key] !== hash) {
updatedModules.add(module, chunk);
}
chunkModuleHashes[key] = hash;
}
}
} else if (fullHashModulesInThisChunk !== undefined) {
for (const module of modules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = getModuleHash(module);
if (
fullHashModulesInThisChunk.has(
/** @type {RuntimeModule} */ (module)
)
) {
fullHashChunkModuleHashes[key] = hash;
} else {
chunkModuleHashes[key] = hash;
}
}
} else {
for (const module of modules) {
const key = `${chunk.id}|${module.identifier()}`;
const hash = getModuleHash(module);
chunkModuleHashes[key] = hash;
}
}
}
}
hotIndex = records.hotIndex || 0;
if (updatedModules.size > 0) hotIndex++;
hash.update(`${hotIndex}`);
});
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
},
() => {
const chunkGraph = compilation.chunkGraph;
const records = compilation.records;
if (records.hash === compilation.hash) return;
if (
!records.chunkModuleHashes ||
!records.chunkHashes ||
!records.chunkModuleIds
) {
return;
}
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
);
if (records.chunkModuleHashes[key] !== hash) {
updatedModules.add(module, chunk);
}
chunkModuleHashes[key] = hash;
}
/** @type {HotUpdateMainContentByRuntime} */
const hotUpdateMainContentByRuntime = new Map();
let allOldRuntime;
for (const key of Object.keys(records.chunkRuntime)) {
const runtime = keyToRuntime(records.chunkRuntime[key]);
allOldRuntime = mergeRuntimeOwned(allOldRuntime, runtime);
}
forEachRuntime(allOldRuntime, runtime => {
const { path: filename, info: assetInfo } =
compilation.getPathWithInfo(
/** @type {NonNullable<OutputNormalized["hotUpdateMainFilename"]>} */
(compilation.outputOptions.hotUpdateMainFilename),
{
hash: records.hash,
runtime
}
);
hotUpdateMainContentByRuntime.set(
/** @type {string} */ (runtime),
{
updatedChunkIds: new Set(),
removedChunkIds: new Set(),
removedModules: new Set(),
filename,
assetInfo
}
);
});
if (hotUpdateMainContentByRuntime.size === 0) return;
// Create a list of all active modules to verify which modules are removed completely
/** @type {Map<number|string, Module>} */
const allModules = new Map();
for (const module of compilation.modules) {
const id =
/** @type {ModuleId} */
(chunkGraph.getModuleId(module));
allModules.set(id, module);
}
// List of completely removed modules
/** @type {Set<string | number>} */
const completelyRemovedModules = new Set();
for (const key of Object.keys(records.chunkHashes)) {
const oldRuntime = keyToRuntime(records.chunkRuntime[key]);
/** @type {Module[]} */
const remainingModules = [];
// Check which modules are removed
for (const id of records.chunkModuleIds[key]) {
const module = allModules.get(id);
if (module === undefined) {
completelyRemovedModules.add(id);
} else {
remainingModules.push(module);
}
}
/** @type {ChunkId | null} */
let chunkId;
let newModules;
let newRuntimeModules;
let newFullHashModules;
let newDependentHashModules;
let newRuntime;
let removedFromRuntime;
const currentChunk = find(
compilation.chunks,
chunk => `${chunk.id}` === key
);
if (currentChunk) {
chunkId = currentChunk.id;
newRuntime = intersectRuntime(
currentChunk.runtime,
allOldRuntime
);
if (newRuntime === undefined) continue;
newModules = chunkGraph
.getChunkModules(currentChunk)
.filter(module => updatedModules.has(module, currentChunk));
newRuntimeModules = Array.from(
chunkGraph.getChunkRuntimeModulesIterable(currentChunk)
).filter(module => updatedModules.has(module, currentChunk));
const fullHashModules =
chunkGraph.getChunkFullHashModulesIterable(currentChunk);
newFullHashModules =
fullHashModules &&
Array.from(fullHashModules).filter(module =>
updatedModules.has(module, currentChunk)
);
const dependentHashModules =
chunkGraph.getChunkDependentHashModulesIterable(currentChunk);
newDependentHashModules =
dependentHashModules &&
Array.from(dependentHashModules).filter(module =>
updatedModules.has(module, currentChunk)
);
removedFromRuntime = subtractRuntime(oldRuntime, newRuntime);
} else {
// chunk has completely removed
chunkId = `${Number(key)}` === key ? Number(key) : key;
removedFromRuntime = oldRuntime;
newRuntime = oldRuntime;
}
if (removedFromRuntime) {
// chunk was removed from some runtimes
forEachRuntime(removedFromRuntime, runtime => {
const item =
/** @type {HotUpdateMainContentByRuntimeItem} */
(
hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)
)
);
item.removedChunkIds.add(/** @type {ChunkId} */ (chunkId));
});
// dispose modules from the chunk in these runtimes
// where they are no longer in this runtime
for (const module of remainingModules) {
const moduleKey = `${key}|${module.identifier()}`;
const oldHash = records.chunkModuleHashes[moduleKey];
const runtimes = chunkGraph.getModuleRuntimes(module);
if (oldRuntime === newRuntime && runtimes.has(newRuntime)) {
// Module is still in the same runtime combination
const hash = nonCodeGeneratedModules.has(module, newRuntime)
? chunkGraph.getModuleHash(module, newRuntime)
: compilation.codeGenerationResults.getHash(
module,
newRuntime
);
if (hash !== oldHash) {
if (module.type === WEBPACK_MODULE_TYPE_RUNTIME) {
newRuntimeModules = newRuntimeModules || [];
newRuntimeModules.push(
/** @type {RuntimeModule} */ (module)
);
} else {
newModules = newModules || [];
newModules.push(module);
}
}
} else {
// module is no longer in this runtime combination
// We (incorrectly) assume that it's not in an overlapping runtime combination
// and dispose it from the main runtimes the chunk was removed from
forEachRuntime(removedFromRuntime, runtime => {
// If the module is still used in this runtime, do not dispose it
// This could create a bad runtime state where the module is still loaded,
// but no chunk which contains it. This means we don't receive further HMR updates
// to this module and that's bad.
// TODO force load one of the chunks which contains the module
for (const moduleRuntime of runtimes) {
if (typeof moduleRuntime === "string") {
if (moduleRuntime === runtime) return;
} else if (
moduleRuntime !== undefined &&
moduleRuntime.has(/** @type {string} */ (runtime))
)
return;
}
const item =
/** @type {HotUpdateMainContentByRuntimeItem} */ (
hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)
)
);
item.removedModules.add(module);
});
}
}
}
if (
(newModules && newModules.length > 0) ||
(newRuntimeModules && newRuntimeModules.length > 0)
) {
const hotUpdateChunk = new HotUpdateChunk();
if (backCompat)
ChunkGraph.setChunkGraphForChunk(hotUpdateChunk, chunkGraph);
hotUpdateChunk.id = chunkId;
hotUpdateChunk.runtime = newRuntime;
if (currentChunk) {
for (const group of currentChunk.groupsIterable)
hotUpdateChunk.addGroup(group);
}
chunkGraph.attachModules(hotUpdateChunk, newModules || []);
chunkGraph.attachRuntimeModules(
hotUpdateChunk,
newRuntimeModules || []
);
if (newFullHashModules) {
chunkGraph.attachFullHashModules(
hotUpdateChunk,
newFullHashModules
);
}
if (newDependentHashModules) {
chunkGraph.attachDependentHashModules(
hotUpdateChunk,
newDependentHashModules
);
}
const renderManifest = compilation.getRenderManifest({
chunk: hotUpdateChunk,
hash: records.hash,
fullHash: records.hash,
outputOptions: compilation.outputOptions,
moduleTemplates: compilation.moduleTemplates,
dependencyTemplates: compilation.dependencyTemplates,
codeGenerationResults: compilation.codeGenerationResults,
runtimeTemplate: compilation.runtimeTemplate,
moduleGraph: compilation.moduleGraph,
chunkGraph
});
for (const entry of renderManifest) {
/** @type {string} */
let filename;
/** @type {AssetInfo} */
let assetInfo;
if ("filename" in entry) {
filename = entry.filename;
assetInfo = entry.info;
} else {
({ path: filename, info: assetInfo } =
compilation.getPathWithInfo(
entry.filenameTemplate,
entry.pathOptions
));
}
const source = entry.render();
compilation.additionalChunkAssets.push(filename);
compilation.emitAsset(filename, source, {
hotModuleReplacement: true,
...assetInfo
});
if (currentChunk) {
currentChunk.files.add(filename);
compilation.hooks.chunkAsset.call(currentChunk, filename);
}
}
forEachRuntime(newRuntime, runtime => {
const item =
/** @type {HotUpdateMainContentByRuntimeItem} */ (
hotUpdateMainContentByRuntime.get(
/** @type {string} */ (runtime)
)
);
item.updatedChunkIds.add(/** @type {ChunkId} */ (chunkId));
});
}
}
const completelyRemovedModulesArray = Array.from(
completelyRemovedModules
);
const hotUpdateMainContentByFilename = new Map();
for (const {
removedChunkIds,
removedModules,
updatedChunkIds,
filename,
assetInfo
} of hotUpdateMainContentByRuntime.values()) {
const old = hotUpdateMainContentByFilename.get(filename);
if (
old &&
(!isSubset(old.removedChunkIds, removedChunkIds) ||
!isSubset(old.removedModules, removedModules) ||
!isSubset(old.updatedChunkIds, updatedChunkIds))
) {
compilation.warnings.push(
new WebpackError(`HotModuleReplacementPlugin
The configured output.hotUpdateMainFilename doesn't lead to unique filenames per runtime and HMR update differs between runtimes.
This might lead to incorrect runtime behavior of the applied update.
To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename option, or use the default config.`)
);
for (const chunkId of removedChunkIds)
old.removedChunkIds.add(chunkId);
for (const chunkId of removedModules)
old.removedModules.add(chunkId);
for (const chunkId of updatedChunkIds)
old.updatedChunkIds.add(chunkId);
continue;
}
hotUpdateMainContentByFilename.set(filename, {
removedChunkIds,
removedModules,
updatedChunkIds,
assetInfo
});
}
for (const [
filename,
{ removedChunkIds, removedModules, updatedChunkIds, assetInfo }
] of hotUpdateMainContentByFilename) {
const hotUpdateMainJson = {
c: Array.from(updatedChunkIds),
r: Array.from(removedChunkIds),
m:
removedModules.size === 0
? completelyRemovedModulesArray
: completelyRemovedModulesArray.concat(
Array.from(
removedModules,
m =>
/** @type {ModuleId} */ (chunkGraph.getModuleId(m))
)
)
};
const source = new RawSource(JSON.stringify(hotUpdateMainJson));
compilation.emitAsset(filename, source, {
hotModuleReplacement: true,
...assetInfo
});
}
}
);
compilation.hooks.additionalTreeRuntimeRequirements.tap(
PLUGIN_NAME,
(chunk, runtimeRequirements) => {
runtimeRequirements.add(RuntimeGlobals.hmrDownloadManifest);
runtimeRequirements.add(RuntimeGlobals.hmrDownloadUpdateHandlers);
runtimeRequirements.add(RuntimeGlobals.interceptModuleExecution);
runtimeRequirements.add(RuntimeGlobals.moduleCache);
compilation.addRuntimeModule(
chunk,
new HotModuleReplacementRuntimeModule()
);
}
);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, parser => {
applyModuleHot(parser);
applyImportMetaHot(parser);
});
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, parser => {
applyModuleHot(parser);
});
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, parser => {
applyImportMetaHot(parser);
});
NormalModule.getCompilationHooks(compilation).loader.tap(
PLUGIN_NAME,
context => {
context.hot = true;
}
);
}
);
}
}
module.exports = HotModuleReplacementPlugin;

19
node_modules/webpack/lib/HotUpdateChunk.js generated vendored Normal file
View file

@ -0,0 +1,19 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Chunk = require("./Chunk");
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./util/Hash")} Hash */
class HotUpdateChunk extends Chunk {
constructor() {
super();
}
}
module.exports = HotUpdateChunk;

84
node_modules/webpack/lib/IgnorePlugin.js generated vendored Normal file
View file

@ -0,0 +1,84 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const createSchemaValidation = require("./util/create-schema-validation");
/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./NormalModuleFactory").ResolveData} ResolveData */
const validate = createSchemaValidation(
require("../schemas/plugins/IgnorePlugin.check.js"),
() => require("../schemas/plugins/IgnorePlugin.json"),
{
name: "Ignore Plugin",
baseDataPath: "options"
}
);
class IgnorePlugin {
/**
* @param {IgnorePluginOptions} options IgnorePlugin options
*/
constructor(options) {
validate(options);
this.options = options;
/**
* @private
* @type {Function}
*/
this.checkIgnore = this.checkIgnore.bind(this);
}
/**
* 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
*/
checkIgnore(resolveData) {
if (
"checkResource" in this.options &&
this.options.checkResource &&
this.options.checkResource(resolveData.request, resolveData.context)
) {
return false;
}
if (
"resourceRegExp" in this.options &&
this.options.resourceRegExp &&
this.options.resourceRegExp.test(resolveData.request)
) {
if ("contextRegExp" in this.options && this.options.contextRegExp) {
// if "contextRegExp" is given,
// both the "resourceRegExp" and "contextRegExp" have to match.
if (this.options.contextRegExp.test(resolveData.context)) {
return false;
}
} else {
return false;
}
}
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.normalModuleFactory.tap("IgnorePlugin", nmf => {
nmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
});
compiler.hooks.contextModuleFactory.tap("IgnorePlugin", cmf => {
cmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore);
});
}
}
module.exports = IgnorePlugin;

144
node_modules/webpack/lib/LibManifestPlugin.js generated vendored Normal file
View file

@ -0,0 +1,144 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const EntryDependency = require("./dependencies/EntryDependency");
const { someInIterable } = require("./util/IterableHelpers");
const { compareModulesById } = require("./util/comparators");
const { dirname, mkdirp } = require("./util/fs");
/** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Compiler").IntermediateFileSystem} IntermediateFileSystem */
/** @typedef {import("./Module").BuildMeta} BuildMeta */
/**
* @typedef {object} ManifestModuleData
* @property {string | number} id
* @property {BuildMeta} buildMeta
* @property {boolean | string[] | undefined} exports
*/
/**
* @typedef {object} LibManifestPluginOptions
* @property {string=} context Context of requests in the manifest file (defaults to the webpack context).
* @property {boolean=} entryOnly If true, only entry points will be exposed (default: true).
* @property {boolean=} format If true, manifest json file (output) will be formatted.
* @property {string=} name Name of the exposed dll function (external name, use value of 'output.library').
* @property {string} path Absolute path to the manifest json file (output).
* @property {string=} type Type of the dll bundle (external type, use value of 'output.libraryTarget').
*/
class LibManifestPlugin {
/**
* @param {LibManifestPluginOptions} options the options
*/
constructor(options) {
this.options = options;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.emit.tapAsync(
{
name: "LibManifestPlugin",
stage: 110
},
(compilation, callback) => {
const moduleGraph = compilation.moduleGraph;
// store used paths to detect issue and output an error. #18200
const usedPaths = new Set();
asyncLib.each(
Array.from(compilation.chunks),
(chunk, callback) => {
if (!chunk.canBeInitial()) {
callback();
return;
}
const chunkGraph = compilation.chunkGraph;
const targetPath = compilation.getPath(this.options.path, {
chunk
});
if (usedPaths.has(targetPath)) {
callback(new Error("each chunk must have a unique path"));
return;
}
usedPaths.add(targetPath);
const name =
this.options.name &&
compilation.getPath(this.options.name, {
chunk,
contentHashType: "javascript"
});
const content = Object.create(null);
for (const module of chunkGraph.getOrderedChunkModulesIterable(
chunk,
compareModulesById(chunkGraph)
)) {
if (
this.options.entryOnly &&
!someInIterable(
moduleGraph.getIncomingConnections(module),
c => c.dependency instanceof EntryDependency
)
) {
continue;
}
const ident = module.libIdent({
context:
this.options.context ||
/** @type {string} */ (compiler.options.context),
associatedObjectForCache: compiler.root
});
if (ident) {
const exportsInfo = moduleGraph.getExportsInfo(module);
const providedExports = exportsInfo.getProvidedExports();
/** @type {ManifestModuleData} */
const data = {
id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)),
buildMeta: /** @type {BuildMeta} */ (module.buildMeta),
exports: Array.isArray(providedExports)
? providedExports
: undefined
};
content[ident] = data;
}
}
const manifest = {
name,
type: this.options.type,
content
};
// Apply formatting to content if format flag is true;
const manifestContent = this.options.format
? JSON.stringify(manifest, null, 2)
: JSON.stringify(manifest);
const buffer = Buffer.from(manifestContent, "utf8");
const intermediateFileSystem =
/** @type {IntermediateFileSystem} */ (
compiler.intermediateFileSystem
);
mkdirp(
intermediateFileSystem,
dirname(intermediateFileSystem, targetPath),
err => {
if (err) return callback(err);
intermediateFileSystem.writeFile(targetPath, buffer, callback);
}
);
},
callback
);
}
);
}
}
module.exports = LibManifestPlugin;

48
node_modules/webpack/lib/LibraryTemplatePlugin.js generated vendored Normal file
View file

@ -0,0 +1,48 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const EnableLibraryPlugin = require("./library/EnableLibraryPlugin");
/** @typedef {import("../declarations/WebpackOptions").AuxiliaryComment} AuxiliaryComment */
/** @typedef {import("../declarations/WebpackOptions").LibraryExport} LibraryExport */
/** @typedef {import("../declarations/WebpackOptions").LibraryName} LibraryName */
/** @typedef {import("../declarations/WebpackOptions").LibraryType} LibraryType */
/** @typedef {import("../declarations/WebpackOptions").UmdNamedDefine} UmdNamedDefine */
/** @typedef {import("./Compiler")} Compiler */
// TODO webpack 6 remove
class LibraryTemplatePlugin {
/**
* @param {LibraryName} name name of library
* @param {LibraryType} target type of library
* @param {UmdNamedDefine} umdNamedDefine setting this to true will name the UMD module
* @param {AuxiliaryComment} auxiliaryComment comment in the UMD wrapper
* @param {LibraryExport} exportProperty which export should be exposed as library
*/
constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) {
this.library = {
type: target || "var",
name,
umdNamedDefine,
auxiliaryComment,
export: exportProperty
};
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const { output } = compiler.options;
output.library = this.library;
new EnableLibraryPlugin(this.library.type).apply(compiler);
}
}
module.exports = LibraryTemplatePlugin;

81
node_modules/webpack/lib/LoaderOptionsPlugin.js generated vendored Normal file
View file

@ -0,0 +1,81 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
const NormalModule = require("./NormalModule");
const createSchemaValidation = require("./util/create-schema-validation");
/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./ModuleFilenameHelpers").MatchObject} MatchObject */
const validate = createSchemaValidation(
require("../schemas/plugins/LoaderOptionsPlugin.check.js"),
() => require("../schemas/plugins/LoaderOptionsPlugin.json"),
{
name: "Loader Options Plugin",
baseDataPath: "options"
}
);
class LoaderOptionsPlugin {
/**
* @param {LoaderOptionsPluginOptions & MatchObject} options options object
*/
constructor(options = {}) {
validate(options);
// If no options are set then generate empty options object
if (typeof options !== "object") options = {};
if (!options.test) {
// This is mocking a RegExp object which always returns true
// TODO: Figure out how to do `as unknown as RegExp` for this line
// in JSDoc equivalent
/** @type {any} */
const defaultTrueMockRegExp = {
test: () => true
};
/** @type {RegExp} */
options.test = defaultTrueMockRegExp;
}
this.options = options;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const options = this.options;
compiler.hooks.compilation.tap("LoaderOptionsPlugin", compilation => {
NormalModule.getCompilationHooks(compilation).loader.tap(
"LoaderOptionsPlugin",
(context, module) => {
const resource = module.resource;
if (!resource) return;
const i = resource.indexOf("?");
if (
ModuleFilenameHelpers.matchObject(
options,
i < 0 ? resource : resource.slice(0, i)
)
) {
for (const key of Object.keys(options)) {
if (key === "include" || key === "exclude" || key === "test") {
continue;
}
context[key] = options[key];
}
}
}
);
});
}
}
module.exports = LoaderOptionsPlugin;

37
node_modules/webpack/lib/LoaderTargetPlugin.js generated vendored Normal file
View file

@ -0,0 +1,37 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const NormalModule = require("./NormalModule");
/** @typedef {import("./Compiler")} Compiler */
class LoaderTargetPlugin {
/**
* @param {string} target the target
*/
constructor(target) {
this.target = target;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap("LoaderTargetPlugin", compilation => {
NormalModule.getCompilationHooks(compilation).loader.tap(
"LoaderTargetPlugin",
loaderContext => {
loaderContext.target = this.target;
}
);
});
}
}
module.exports = LoaderTargetPlugin;

382
node_modules/webpack/lib/MainTemplate.js generated vendored Normal file
View file

@ -0,0 +1,382 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { SyncWaterfallHook } = require("tapable");
const util = require("util");
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 */
/** @typedef {import("./Chunk")} Chunk */
/** @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} */
/**
* @template T
* @typedef {import("tapable").IfSet<T>} IfSet
*/
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
);
const getJsonpTemplatePlugin = memoize(() =>
require("./web/JsonpTemplatePlugin")
);
const getLoadScriptRuntimeModule = memoize(() =>
require("./runtime/LoadScriptRuntimeModule")
);
// TODO webpack 6 remove this class
class MainTemplate {
/**
* @param {OutputOptions} outputOptions output options for the MainTemplate
* @param {Compilation} compilation the compilation
*/
constructor(outputOptions, compilation) {
/** @type {OutputOptions} */
this._outputOptions = outputOptions || {};
this.hooks = Object.freeze({
renderManifest: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(RenderManifestEntry[], RenderManifestOptions): RenderManifestEntry[]} fn fn
*/
(options, fn) => {
compilation.hooks.renderManifest.tap(
options,
(entries, options) => {
if (!options.chunk.hasRuntime()) return entries;
return fn(entries, options);
}
);
},
"MainTemplate.hooks.renderManifest is deprecated (use Compilation.hooks.renderManifest instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_RENDER_MANIFEST"
)
},
modules: {
tap: () => {
throw new Error(
"MainTemplate.hooks.modules has been removed (there is no replacement, please create an issue to request that)"
);
}
},
moduleObj: {
tap: () => {
throw new Error(
"MainTemplate.hooks.moduleObj has been removed (there is no replacement, please create an issue to request that)"
);
}
},
require: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(string, RenderBootstrapContext): string} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderRequire.tap(options, fn);
},
"MainTemplate.hooks.require is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderRequire instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_REQUIRE"
)
},
beforeStartup: {
tap: () => {
throw new Error(
"MainTemplate.hooks.beforeStartup has been removed (use RuntimeGlobals.startupOnlyBefore instead)"
);
}
},
startup: {
tap: () => {
throw new Error(
"MainTemplate.hooks.startup has been removed (use RuntimeGlobals.startup instead)"
);
}
},
afterStartup: {
tap: () => {
throw new Error(
"MainTemplate.hooks.afterStartup has been removed (use RuntimeGlobals.startupOnlyAfter instead)"
);
}
},
render: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Chunk, string | undefined, ModuleTemplate, DependencyTemplates): Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.render.tap(options, (source, renderContext) => {
if (
renderContext.chunkGraph.getNumberOfEntryModules(
renderContext.chunk
) === 0 ||
!renderContext.chunk.hasRuntime()
) {
return source;
}
return fn(
source,
renderContext.chunk,
compilation.hash,
compilation.moduleTemplates.javascript,
compilation.dependencyTemplates
);
});
},
"MainTemplate.hooks.render is deprecated (use JavascriptModulesPlugin.getCompilationHooks().render instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_RENDER"
)
},
renderWithEntry: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Chunk, string | undefined): Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.render.tap(options, (source, renderContext) => {
if (
renderContext.chunkGraph.getNumberOfEntryModules(
renderContext.chunk
) === 0 ||
!renderContext.chunk.hasRuntime()
) {
return source;
}
return fn(source, renderContext.chunk, compilation.hash);
});
},
"MainTemplate.hooks.renderWithEntry is deprecated (use JavascriptModulesPlugin.getCompilationHooks().render instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_RENDER_WITH_ENTRY"
)
},
assetPath: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(string, object, AssetInfo | undefined): string} fn fn
*/
(options, fn) => {
compilation.hooks.assetPath.tap(options, fn);
},
"MainTemplate.hooks.assetPath is deprecated (use Compilation.hooks.assetPath instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_ASSET_PATH"
),
call: util.deprecate(
/**
* @param {TemplatePath} filename used to get asset path with hash
* @param {PathData} options context data
* @returns {string} interpolated path
*/
(filename, options) => compilation.getAssetPath(filename, options),
"MainTemplate.hooks.assetPath is deprecated (use Compilation.hooks.assetPath instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_ASSET_PATH"
)
},
hash: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Hash): void} fn fn
*/
(options, fn) => {
compilation.hooks.fullHash.tap(options, fn);
},
"MainTemplate.hooks.hash is deprecated (use Compilation.hooks.fullHash instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_HASH"
)
},
hashForChunk: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Hash, Chunk): void} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.chunkHash.tap(options, (chunk, hash) => {
if (!chunk.hasRuntime()) return;
return fn(hash, chunk);
});
},
"MainTemplate.hooks.hashForChunk is deprecated (use JavascriptModulesPlugin.getCompilationHooks().chunkHash instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_HASH_FOR_CHUNK"
)
},
globalHashPaths: {
tap: util.deprecate(
() => {},
"MainTemplate.hooks.globalHashPaths has been removed (it's no longer needed)",
"DEP_WEBPACK_MAIN_TEMPLATE_HASH_FOR_CHUNK"
)
},
globalHash: {
tap: util.deprecate(
() => {},
"MainTemplate.hooks.globalHash has been removed (it's no longer needed)",
"DEP_WEBPACK_MAIN_TEMPLATE_HASH_FOR_CHUNK"
)
},
hotBootstrap: {
tap: () => {
throw new Error(
"MainTemplate.hooks.hotBootstrap has been removed (use your own RuntimeModule instead)"
);
}
},
// for compatibility:
/** @type {SyncWaterfallHook<[string, Chunk, string, ModuleTemplate, DependencyTemplates]>} */
bootstrap: new SyncWaterfallHook([
"source",
"chunk",
"hash",
"moduleTemplate",
"dependencyTemplates"
]),
/** @type {SyncWaterfallHook<[string, Chunk, string]>} */
localVars: new SyncWaterfallHook(["source", "chunk", "hash"]),
/** @type {SyncWaterfallHook<[string, Chunk, string]>} */
requireExtensions: new SyncWaterfallHook(["source", "chunk", "hash"]),
/** @type {SyncWaterfallHook<[string, Chunk, string, string]>} */
requireEnsure: new SyncWaterfallHook([
"source",
"chunk",
"hash",
"chunkIdExpression"
]),
get jsonpScript() {
const hooks =
getLoadScriptRuntimeModule().getCompilationHooks(compilation);
return hooks.createScript;
},
get linkPrefetch() {
const hooks = getJsonpTemplatePlugin().getCompilationHooks(compilation);
return hooks.linkPrefetch;
},
get linkPreload() {
const hooks = getJsonpTemplatePlugin().getCompilationHooks(compilation);
return hooks.linkPreload;
}
});
this.renderCurrentHashCode = util.deprecate(
/**
* @deprecated
* @param {string} hash the hash
* @param {number=} length length of the hash
* @returns {string} generated code
*/
(hash, length) => {
if (length) {
return `${RuntimeGlobals.getFullHash} ? ${
RuntimeGlobals.getFullHash
}().slice(0, ${length}) : ${hash.slice(0, length)}`;
}
return `${RuntimeGlobals.getFullHash} ? ${RuntimeGlobals.getFullHash}() : ${hash}`;
},
"MainTemplate.renderCurrentHashCode is deprecated (use RuntimeGlobals.getFullHash runtime function instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_RENDER_CURRENT_HASH_CODE"
);
this.getPublicPath = util.deprecate(
/**
* @param {PathData} options context data
* @returns {string} interpolated path
*/ options =>
compilation.getAssetPath(
/** @type {string} */
(compilation.outputOptions.publicPath),
options
),
"MainTemplate.getPublicPath is deprecated (use Compilation.getAssetPath(compilation.outputOptions.publicPath, options) instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_GET_PUBLIC_PATH"
);
this.getAssetPath = util.deprecate(
/**
* @param {TemplatePath} path used to get asset path with hash
* @param {PathData} options context data
* @returns {string} interpolated path
*/
(path, options) => compilation.getAssetPath(path, options),
"MainTemplate.getAssetPath is deprecated (use Compilation.getAssetPath instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_GET_ASSET_PATH"
);
this.getAssetPathWithInfo = util.deprecate(
/**
* @param {TemplatePath} path used to get asset path with hash
* @param {PathData} options context data
* @returns {InterpolatedPathAndAssetInfo} interpolated path and asset info
*/
(path, options) => compilation.getAssetPathWithInfo(path, options),
"MainTemplate.getAssetPathWithInfo is deprecated (use Compilation.getAssetPath instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_GET_ASSET_PATH_WITH_INFO"
);
}
}
Object.defineProperty(MainTemplate.prototype, "requireFn", {
get: util.deprecate(
() => RuntimeGlobals.require,
`MainTemplate.requireFn is deprecated (use "${RuntimeGlobals.require}")`,
"DEP_WEBPACK_MAIN_TEMPLATE_REQUIRE_FN"
)
});
Object.defineProperty(MainTemplate.prototype, "outputOptions", {
get: util.deprecate(
/**
* @this {MainTemplate}
* @returns {OutputOptions} output options
*/
function () {
return this._outputOptions;
},
"MainTemplate.outputOptions is deprecated (use Compilation.outputOptions instead)",
"DEP_WEBPACK_MAIN_TEMPLATE_OUTPUT_OPTIONS"
)
});
module.exports = MainTemplate;

1191
node_modules/webpack/lib/Module.js generated vendored Normal file

File diff suppressed because it is too large Load diff

79
node_modules/webpack/lib/ModuleBuildError.js generated vendored Normal file
View file

@ -0,0 +1,79 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { cutOffLoaderExecution } = require("./ErrorHelpers");
const WebpackError = require("./WebpackError");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
class ModuleBuildError extends WebpackError {
/**
* @param {string | Error&any} err error thrown
* @param {{from?: string|null}} info additional info
*/
constructor(err, { from = null } = {}) {
let message = "Module build failed";
let details;
message += from ? ` (from ${from}):\n` : ": ";
if (err !== null && typeof err === "object") {
if (typeof err.stack === "string" && err.stack) {
const stack = cutOffLoaderExecution(err.stack);
if (!err.hideStack) {
message += stack;
} else {
details = stack;
message +=
typeof err.message === "string" && err.message ? err.message : err;
}
} else if (typeof err.message === "string" && err.message) {
message += err.message;
} else {
message += String(err);
}
} else {
message += String(err);
}
super(message);
this.name = "ModuleBuildError";
this.details = details;
this.error = err;
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.error);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
this.error = read();
super.deserialize(context);
}
}
makeSerializable(ModuleBuildError, "webpack/lib/ModuleBuildError");
module.exports = ModuleBuildError;

42
node_modules/webpack/lib/ModuleDependencyError.js generated vendored Normal file
View file

@ -0,0 +1,42 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("./WebpackError");
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Module")} Module */
class ModuleDependencyError extends WebpackError {
/**
* Creates an instance of ModuleDependencyError.
* @param {Module} module module tied to dependency
* @param {Error} err error thrown
* @param {DependencyLocation} loc location of dependency
*/
constructor(module, err, loc) {
super(err.message);
this.name = "ModuleDependencyError";
this.details =
err && !(/** @type {any} */ (err).hideStack)
? /** @type {string} */ (err.stack).split("\n").slice(1).join("\n")
: undefined;
this.module = module;
this.loc = loc;
/** error is not (de)serialized, so it might be undefined after deserialization */
this.error = err;
if (err && /** @type {any} */ (err).hideStack && err.stack) {
this.stack = /** @type {string} */ `${err.stack
.split("\n")
.slice(1)
.join("\n")}\n\n${this.stack}`;
}
}
}
module.exports = ModuleDependencyError;

47
node_modules/webpack/lib/ModuleDependencyWarning.js generated vendored Normal file
View file

@ -0,0 +1,47 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("./WebpackError");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Module")} Module */
class ModuleDependencyWarning extends WebpackError {
/**
* @param {Module} module module tied to dependency
* @param {Error} err error thrown
* @param {DependencyLocation} loc location of dependency
*/
constructor(module, err, loc) {
super(err ? err.message : "");
this.name = "ModuleDependencyWarning";
this.details =
err && !(/** @type {any} */ (err).hideStack)
? /** @type {string} */ (err.stack).split("\n").slice(1).join("\n")
: undefined;
this.module = module;
this.loc = loc;
/** error is not (de)serialized, so it might be undefined after deserialization */
this.error = err;
if (err && /** @type {any} */ (err).hideStack && err.stack) {
this.stack = /** @type {string} */ `${err.stack
.split("\n")
.slice(1)
.join("\n")}\n\n${this.stack}`;
}
}
}
makeSerializable(
ModuleDependencyWarning,
"webpack/lib/ModuleDependencyWarning"
);
module.exports = ModuleDependencyWarning;

66
node_modules/webpack/lib/ModuleError.js generated vendored Normal file
View file

@ -0,0 +1,66 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { cleanUp } = require("./ErrorHelpers");
const WebpackError = require("./WebpackError");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
class ModuleError extends WebpackError {
/**
* @param {Error} err error thrown
* @param {{from?: string|null}} info additional info
*/
constructor(err, { from = null } = {}) {
let message = "Module Error";
message += from ? ` (from ${from}):\n` : ": ";
if (err && typeof err === "object" && err.message) {
message += err.message;
} else if (err) {
message += err;
}
super(message);
this.name = "ModuleError";
this.error = err;
this.details =
err && typeof err === "object" && err.stack
? cleanUp(err.stack, this.message)
: undefined;
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.error);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
this.error = read();
super.deserialize(context);
}
}
makeSerializable(ModuleError, "webpack/lib/ModuleError");
module.exports = ModuleError;

383
node_modules/webpack/lib/ModuleFilenameHelpers.js generated vendored Normal file
View file

@ -0,0 +1,383 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const NormalModule = require("./NormalModule");
const createHash = require("./util/createHash");
const memoize = require("./util/memoize");
/** @typedef {import("./ChunkGraph")} ChunkGraph */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {typeof import("./util/Hash")} Hash */
/** @typedef {string | RegExp | (string | RegExp)[]} Matcher */
/** @typedef {{test?: Matcher, include?: Matcher, exclude?: Matcher }} MatchObject */
const ModuleFilenameHelpers = module.exports;
// TODO webpack 6: consider removing these
ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]";
ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE =
/\[all-?loaders\]\[resource\]/gi;
ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]";
ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi;
ModuleFilenameHelpers.RESOURCE = "[resource]";
ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi;
ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]";
// cSpell:words olute
ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH =
/\[abs(olute)?-?resource-?path\]/gi;
ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]";
ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi;
ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]";
ModuleFilenameHelpers.REGEXP_ALL_LOADERS = /\[all-?loaders\]/gi;
ModuleFilenameHelpers.LOADERS = "[loaders]";
ModuleFilenameHelpers.REGEXP_LOADERS = /\[loaders\]/gi;
ModuleFilenameHelpers.QUERY = "[query]";
ModuleFilenameHelpers.REGEXP_QUERY = /\[query\]/gi;
ModuleFilenameHelpers.ID = "[id]";
ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi;
ModuleFilenameHelpers.HASH = "[hash]";
ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi;
ModuleFilenameHelpers.NAMESPACE = "[namespace]";
ModuleFilenameHelpers.REGEXP_NAMESPACE = /\[namespace\]/gi;
/** @typedef {() => string} ReturnStringCallback */
/**
* Returns a function that returns the part of the string after the token
* @param {ReturnStringCallback} strFn the function to get the string
* @param {string} token the token to search for
* @returns {ReturnStringCallback} a function that returns the part of the string after the token
*/
const getAfter = (strFn, token) => () => {
const str = strFn();
const idx = str.indexOf(token);
return idx < 0 ? "" : str.slice(idx);
};
/**
* Returns a function that returns the part of the string before the token
* @param {ReturnStringCallback} strFn the function to get the string
* @param {string} token the token to search for
* @returns {ReturnStringCallback} a function that returns the part of the string before the token
*/
const getBefore = (strFn, token) => () => {
const str = strFn();
const idx = str.lastIndexOf(token);
return idx < 0 ? "" : str.slice(0, idx);
};
/**
* Returns a function that returns a hash of the string
* @param {ReturnStringCallback} strFn the function to get the string
* @param {string | Hash=} hashFunction the hash function to use
* @returns {ReturnStringCallback} a function that returns the hash of the string
*/
const getHash =
(strFn, hashFunction = "md4") =>
() => {
const hash = createHash(hashFunction);
hash.update(strFn());
const digest = /** @type {string} */ (hash.digest("hex"));
return digest.slice(0, 4);
};
/**
* Returns a function that returns the string with the token replaced with the replacement
* @param {string|RegExp} test A regular expression string or Regular Expression object
* @returns {RegExp} A regular expression object
* @example
* ```js
* const test = asRegExp("test");
* test.test("test"); // true
*
* const test2 = asRegExp(/test/);
* test2.test("test"); // true
* ```
*/
const asRegExp = test => {
if (typeof test === "string") {
// Escape special characters in the string to prevent them from being interpreted as special characters in a regular expression. Do this by
// adding a backslash before each special character
test = new RegExp(`^${test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")}`);
}
return test;
};
/**
* @template T
* 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 {object} the lazy access object
*/
const lazyObject = obj => {
const newObj = {};
for (const key of Object.keys(obj)) {
const fn = obj[key];
Object.defineProperty(newObj, key, {
get: () => fn(),
set: v => {
Object.defineProperty(newObj, key, {
value: v,
enumerable: true,
writable: true
});
},
enumerable: true,
configurable: true
});
}
return newObj;
};
const SQUARE_BRACKET_TAG_REGEXP = /\[\\*([\w-]+)\\*\]/gi;
/**
* @param {Module | string} module the module
* @param {TODO} options options
* @param {object} contextInfo context info
* @param {RequestShortener} contextInfo.requestShortener requestShortener
* @param {ChunkGraph} contextInfo.chunkGraph chunk graph
* @param {string | Hash=} contextInfo.hashFunction the hash function to use
* @returns {string} the filename
*/
ModuleFilenameHelpers.createFilename = (
// eslint-disable-next-line default-param-last
module = "",
options,
{ requestShortener, chunkGraph, hashFunction = "md4" }
) => {
const opts = {
namespace: "",
moduleFilenameTemplate: "",
...(typeof options === "object"
? options
: {
moduleFilenameTemplate: options
})
};
let absoluteResourcePath;
let hash;
/** @type {ReturnStringCallback} */
let identifier;
/** @type {ReturnStringCallback} */
let moduleId;
/** @type {ReturnStringCallback} */
let shortIdentifier;
if (typeof module === "string") {
shortIdentifier =
/** @type {ReturnStringCallback} */
(memoize(() => requestShortener.shorten(module)));
identifier = shortIdentifier;
moduleId = () => "";
absoluteResourcePath = () => module.split("!").pop();
hash = getHash(identifier, hashFunction);
} else {
shortIdentifier = memoize(() =>
module.readableIdentifier(requestShortener)
);
identifier =
/** @type {ReturnStringCallback} */
(memoize(() => requestShortener.shorten(module.identifier())));
moduleId =
/** @type {ReturnStringCallback} */
(() => chunkGraph.getModuleId(module));
absoluteResourcePath = () =>
module instanceof NormalModule
? module.resource
: module.identifier().split("!").pop();
hash = getHash(identifier, hashFunction);
}
const resource =
/** @type {ReturnStringCallback} */
(memoize(() => shortIdentifier().split("!").pop()));
const loaders = getBefore(shortIdentifier, "!");
const allLoaders = getBefore(identifier, "!");
const query = getAfter(resource, "?");
const resourcePath = () => {
const q = query().length;
return q === 0 ? resource() : resource().slice(0, -q);
};
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
})
);
}
// TODO webpack 6: consider removing alternatives without dashes
/** @type {Map<string, function(): string>} */
const replacements = new Map([
["identifier", identifier],
["short-identifier", shortIdentifier],
["resource", resource],
["resource-path", resourcePath],
// cSpell:words resourcepath
["resourcepath", resourcePath],
["absolute-resource-path", absoluteResourcePath],
["abs-resource-path", absoluteResourcePath],
// cSpell:words absoluteresource
["absoluteresource-path", absoluteResourcePath],
// cSpell:words absresource
["absresource-path", absoluteResourcePath],
// cSpell:words resourcepath
["absolute-resourcepath", absoluteResourcePath],
// cSpell:words resourcepath
["abs-resourcepath", absoluteResourcePath],
// cSpell:words absoluteresourcepath
["absoluteresourcepath", absoluteResourcePath],
// cSpell:words absresourcepath
["absresourcepath", absoluteResourcePath],
["all-loaders", allLoaders],
// cSpell:words allloaders
["allloaders", allLoaders],
["loaders", loaders],
["query", query],
["id", moduleId],
["hash", hash],
["namespace", () => opts.namespace]
]);
// TODO webpack 6: consider removing weird double placeholders
return /** @type {string} */ (opts.moduleFilenameTemplate)
.replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, "[identifier]")
.replace(
ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE,
"[short-identifier]"
)
.replace(SQUARE_BRACKET_TAG_REGEXP, (match, content) => {
if (content.length + 2 === match.length) {
const replacement = replacements.get(content.toLowerCase());
if (replacement !== undefined) {
return replacement();
}
} else if (match.startsWith("[\\") && match.endsWith("\\]")) {
return `[${match.slice(2, -2)}]`;
}
return match;
});
};
/**
* Replaces duplicate items in an array with new values generated by a callback function.
* The callback function is called with the duplicate item, the index of the duplicate item, and the number of times the item has been replaced.
* The callback function should return the new value for the duplicate item.
* @template T
* @param {T[]} array the array with duplicates to be replaced
* @param {(duplicateItem: T, duplicateItemIndex: number, numberOfTimesReplaced: number) => T} fn callback function to generate new values for the duplicate items
* @param {(firstElement:T, nextElement:T) => -1 | 0 | 1} [comparator] optional comparator function to sort the duplicate items
* @returns {T[]} the array with duplicates replaced
* @example
* ```js
* const array = ["a", "b", "c", "a", "b", "a"];
* const result = ModuleFilenameHelpers.replaceDuplicates(array, (item, index, count) => `${item}-${count}`);
* // result: ["a-1", "b-1", "c", "a-2", "b-2", "a-3"]
* ```
*/
ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => {
const countMap = Object.create(null);
const posMap = Object.create(null);
for (const [idx, item] of array.entries()) {
countMap[item] = countMap[item] || [];
countMap[item].push(idx);
posMap[item] = 0;
}
if (comparator) {
for (const item of Object.keys(countMap)) {
countMap[item].sort(comparator);
}
}
return array.map((item, i) => {
if (countMap[item].length > 1) {
if (comparator && countMap[item][0] === i) return item;
return fn(item, i, posMap[item]++);
}
return item;
});
};
/**
* Tests if a string matches a RegExp or an array of RegExp.
* @param {string} str string to test
* @param {Matcher} test value which will be used to match against the string
* @returns {boolean} true, when the RegExp matches
* @example
* ```js
* ModuleFilenameHelpers.matchPart("foo.js", "foo"); // true
* ModuleFilenameHelpers.matchPart("foo.js", "foo.js"); // true
* ModuleFilenameHelpers.matchPart("foo.js", "foo."); // false
* ModuleFilenameHelpers.matchPart("foo.js", "foo*"); // false
* ModuleFilenameHelpers.matchPart("foo.js", "foo.*"); // true
* ModuleFilenameHelpers.matchPart("foo.js", /^foo/); // true
* ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, "bar"]); // true
* ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, "bar"]); // true
* ModuleFilenameHelpers.matchPart("foo.js", [/^foo/, /^bar/]); // true
* ModuleFilenameHelpers.matchPart("foo.js", [/^baz/, /^bar/]); // false
* ```
*/
ModuleFilenameHelpers.matchPart = (str, test) => {
if (!test) return true;
if (Array.isArray(test)) {
return test.map(asRegExp).some(regExp => regExp.test(str));
}
return asRegExp(test).test(str);
};
/**
* Tests if a string matches a match object. The match object can have the following properties:
* - `test`: a RegExp or an array of RegExp
* - `include`: a RegExp or an array of RegExp
* - `exclude`: a RegExp or an array of RegExp
*
* The `test` property is tested first, then `include` and then `exclude`.
* @param {MatchObject} obj a match object to test against the string
* @param {string} str string to test against the matching object
* @returns {boolean} true, when the object matches
* @example
* ```js
* ModuleFilenameHelpers.matchObject({ test: "foo.js" }, "foo.js"); // true
* ModuleFilenameHelpers.matchObject({ test: /^foo/ }, "foo.js"); // true
* ModuleFilenameHelpers.matchObject({ test: [/^foo/, "bar"] }, "foo.js"); // true
* ModuleFilenameHelpers.matchObject({ test: [/^foo/, "bar"] }, "baz.js"); // false
* ModuleFilenameHelpers.matchObject({ include: "foo.js" }, "foo.js"); // true
* ModuleFilenameHelpers.matchObject({ include: "foo.js" }, "bar.js"); // false
* ModuleFilenameHelpers.matchObject({ include: /^foo/ }, "foo.js"); // true
* ModuleFilenameHelpers.matchObject({ include: [/^foo/, "bar"] }, "foo.js"); // true
* ModuleFilenameHelpers.matchObject({ include: [/^foo/, "bar"] }, "baz.js"); // false
* ModuleFilenameHelpers.matchObject({ exclude: "foo.js" }, "foo.js"); // false
* ModuleFilenameHelpers.matchObject({ exclude: [/^foo/, "bar"] }, "foo.js"); // false
* ```
*/
ModuleFilenameHelpers.matchObject = (obj, str) => {
if (obj.test && !ModuleFilenameHelpers.matchPart(str, obj.test)) {
return false;
}
if (obj.include && !ModuleFilenameHelpers.matchPart(str, obj.include)) {
return false;
}
if (obj.exclude && ModuleFilenameHelpers.matchPart(str, obj.exclude)) {
return false;
}
return true;
};

89
node_modules/webpack/lib/ModuleNotFoundError.js generated vendored Normal file
View file

@ -0,0 +1,89 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("./WebpackError");
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./Module")} Module */
const previouslyPolyfilledBuiltinModules = {
assert: "assert/",
buffer: "buffer/",
console: "console-browserify",
constants: "constants-browserify",
crypto: "crypto-browserify",
domain: "domain-browser",
events: "events/",
http: "stream-http",
https: "https-browserify",
os: "os-browserify/browser",
path: "path-browserify",
punycode: "punycode/",
process: "process/browser",
querystring: "querystring-es3",
stream: "stream-browserify",
_stream_duplex: "readable-stream/duplex",
_stream_passthrough: "readable-stream/passthrough",
_stream_readable: "readable-stream/readable",
_stream_transform: "readable-stream/transform",
_stream_writable: "readable-stream/writable",
string_decoder: "string_decoder/",
sys: "util/",
timers: "timers-browserify",
tty: "tty-browserify",
url: "url/",
util: "util/",
vm: "vm-browserify",
zlib: "browserify-zlib"
};
class ModuleNotFoundError extends WebpackError {
/**
* @param {Module | null} module module tied to dependency
* @param {Error&any} err error thrown
* @param {DependencyLocation} loc location of dependency
*/
constructor(module, err, loc) {
let message = `Module not found: ${err.toString()}`;
// TODO remove in webpack 6
const match = err.message.match(/Can't resolve '([^']+)'/);
if (match) {
const request = match[1];
const alias =
previouslyPolyfilledBuiltinModules[
/** @type {keyof previouslyPolyfilledBuiltinModules} */ (request)
];
if (alias) {
const pathIndex = alias.indexOf("/");
const dependency = pathIndex > 0 ? alias.slice(0, pathIndex) : alias;
message +=
"\n\n" +
"BREAKING CHANGE: " +
"webpack < 5 used to include polyfills for node.js core modules by default.\n" +
"This is no longer the case. Verify if you need this module and configure a polyfill for it.\n\n";
message +=
"If you want to include a polyfill, you need to:\n" +
`\t- add a fallback 'resolve.fallback: { "${request}": require.resolve("${alias}") }'\n` +
`\t- install '${dependency}'\n`;
message +=
"If you don't want to include a polyfill, you can use an empty module like this:\n" +
`\tresolve.fallback: { "${request}": false }`;
}
}
super(message);
this.name = "ModuleNotFoundError";
this.details = err.details;
this.module = module;
this.error = err;
this.loc = loc;
}
}
module.exports = ModuleNotFoundError;

117
node_modules/webpack/lib/ModuleParseError.js generated vendored Normal file
View file

@ -0,0 +1,117 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("./WebpackError");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
const WASM_HEADER = Buffer.from([0x00, 0x61, 0x73, 0x6d]);
class ModuleParseError extends WebpackError {
/**
* @param {string | Buffer} source source code
* @param {Error & any} err the parse error
* @param {string[]} loaders the loaders used
* @param {string} type module type
*/
constructor(source, err, loaders, type) {
let message = `Module parse failed: ${err && err.message}`;
let loc;
if (
((Buffer.isBuffer(source) && source.slice(0, 4).equals(WASM_HEADER)) ||
(typeof source === "string" && /^\0asm/.test(source))) &&
!type.startsWith("webassembly")
) {
message +=
"\nThe module seem to be a WebAssembly module, but module is not flagged as WebAssembly module for webpack.";
message +=
"\nBREAKING CHANGE: Since webpack 5 WebAssembly is not enabled by default and flagged as experimental feature.";
message +=
"\nYou need to enable one of the WebAssembly experiments via 'experiments.asyncWebAssembly: true' (based on async modules) or 'experiments.syncWebAssembly: true' (like webpack 4, deprecated).";
message +=
"\nFor files that transpile to WebAssembly, make sure to set the module type in the 'module.rules' section of the config (e. g. 'type: \"webassembly/async\"').";
} else if (!loaders) {
message +=
"\nYou may need an appropriate loader to handle this file type.";
} else if (loaders.length >= 1) {
message += `\nFile was processed with these loaders:${loaders
.map(loader => `\n * ${loader}`)
.join("")}`;
message +=
"\nYou may need an additional loader to handle the result of these loaders.";
} else {
message +=
"\nYou may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders";
}
if (
err &&
err.loc &&
typeof err.loc === "object" &&
typeof err.loc.line === "number"
) {
const lineNumber = err.loc.line;
if (
Buffer.isBuffer(source) ||
/[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source)
) {
// binary file
message += "\n(Source code omitted for this binary file)";
} else {
const sourceLines = source.split(/\r?\n/);
const start = Math.max(0, lineNumber - 3);
const linesBefore = sourceLines.slice(start, lineNumber - 1);
const theLine = sourceLines[lineNumber - 1];
const linesAfter = sourceLines.slice(lineNumber, lineNumber + 2);
message += `${linesBefore
.map(l => `\n| ${l}`)
.join("")}\n> ${theLine}${linesAfter.map(l => `\n| ${l}`).join("")}`;
}
loc = { start: err.loc };
} else if (err && err.stack) {
message += `\n${err.stack}`;
}
super(message);
this.name = "ModuleParseError";
this.loc = loc;
this.error = err;
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.error);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
this.error = read();
super.deserialize(context);
}
}
makeSerializable(ModuleParseError, "webpack/lib/ModuleParseError");
module.exports = ModuleParseError;

174
node_modules/webpack/lib/ModuleTemplate.js generated vendored Normal file
View file

@ -0,0 +1,174 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
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("./util/Hash")} Hash */
/**
* @template T
* @typedef {import("tapable").IfSet<T>} IfSet
*/
const getJavascriptModulesPlugin = memoize(() =>
require("./javascript/JavascriptModulesPlugin")
);
// TODO webpack 6: remove this class
class ModuleTemplate {
/**
* @param {RuntimeTemplate} runtimeTemplate the runtime template
* @param {Compilation} compilation the compilation
*/
constructor(runtimeTemplate, compilation) {
this._runtimeTemplate = runtimeTemplate;
this.type = "javascript";
this.hooks = Object.freeze({
content: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Module, ChunkRenderContext, DependencyTemplates): Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderModuleContent.tap(
options,
(source, module, renderContext) =>
fn(
source,
module,
renderContext,
renderContext.dependencyTemplates
)
);
},
"ModuleTemplate.hooks.content is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContent instead)",
"DEP_MODULE_TEMPLATE_CONTENT"
)
},
module: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Module, ChunkRenderContext, DependencyTemplates): Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderModuleContent.tap(
options,
(source, module, renderContext) =>
fn(
source,
module,
renderContext,
renderContext.dependencyTemplates
)
);
},
"ModuleTemplate.hooks.module is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContent instead)",
"DEP_MODULE_TEMPLATE_MODULE"
)
},
render: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Module, ChunkRenderContext, DependencyTemplates): Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderModuleContainer.tap(
options,
(source, module, renderContext) =>
fn(
source,
module,
renderContext,
renderContext.dependencyTemplates
)
);
},
"ModuleTemplate.hooks.render is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModuleContainer instead)",
"DEP_MODULE_TEMPLATE_RENDER"
)
},
package: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Source, Module, ChunkRenderContext, DependencyTemplates): Source} fn fn
*/
(options, fn) => {
getJavascriptModulesPlugin()
.getCompilationHooks(compilation)
.renderModulePackage.tap(
options,
(source, module, renderContext) =>
fn(
source,
module,
renderContext,
renderContext.dependencyTemplates
)
);
},
"ModuleTemplate.hooks.package is deprecated (use JavascriptModulesPlugin.getCompilationHooks().renderModulePackage instead)",
"DEP_MODULE_TEMPLATE_PACKAGE"
)
},
hash: {
tap: util.deprecate(
/**
* @template AdditionalOptions
* @param {string | Tap & IfSet<AdditionalOptions>} options options
* @param {function(Hash): void} fn fn
*/
(options, fn) => {
compilation.hooks.fullHash.tap(options, fn);
},
"ModuleTemplate.hooks.hash is deprecated (use Compilation.hooks.fullHash instead)",
"DEP_MODULE_TEMPLATE_HASH"
)
}
});
}
}
Object.defineProperty(ModuleTemplate.prototype, "runtimeTemplate", {
get: util.deprecate(
/**
* @this {ModuleTemplate}
* @returns {RuntimeTemplate} output options
*/
function () {
return this._runtimeTemplate;
},
"ModuleTemplate.runtimeTemplate is deprecated (use Compilation.runtimeTemplate instead)",
"DEP_WEBPACK_CHUNK_TEMPLATE_OUTPUT_OPTIONS"
)
});
module.exports = ModuleTemplate;

66
node_modules/webpack/lib/ModuleWarning.js generated vendored Normal file
View file

@ -0,0 +1,66 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { cleanUp } = require("./ErrorHelpers");
const WebpackError = require("./WebpackError");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
class ModuleWarning extends WebpackError {
/**
* @param {Error} warning error thrown
* @param {{from?: string|null}} info additional info
*/
constructor(warning, { from = null } = {}) {
let message = "Module Warning";
message += from ? ` (from ${from}):\n` : ": ";
if (warning && typeof warning === "object" && warning.message) {
message += warning.message;
} else if (warning) {
message += String(warning);
}
super(message);
this.name = "ModuleWarning";
this.warning = warning;
this.details =
warning && typeof warning === "object" && warning.stack
? cleanUp(warning.stack, this.message)
: undefined;
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.warning);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
this.warning = read();
super.deserialize(context);
}
}
makeSerializable(ModuleWarning, "webpack/lib/ModuleWarning");
module.exports = ModuleWarning;

659
node_modules/webpack/lib/MultiCompiler.js generated vendored Normal file
View file

@ -0,0 +1,659 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const { SyncHook, MultiHook } = require("tapable");
const ConcurrentCompilationError = require("./ConcurrentCompilationError");
const MultiStats = require("./MultiStats");
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").WatchOptions} WatchOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @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
*/
/**
* @typedef {object} MultiCompilerOptions
* @property {number=} parallelism how many Compilers are allows to run at the same time in parallel
*/
module.exports = class MultiCompiler {
/**
* @param {Compiler[] | Record<string, Compiler>} compilers child compilers
* @param {MultiCompilerOptions} options options
*/
constructor(compilers, options) {
if (!Array.isArray(compilers)) {
/** @type {Compiler[]} */
compilers = Object.keys(compilers).map(name => {
/** @type {Record<string, Compiler>} */
(compilers)[name].name = name;
return /** @type {Record<string, Compiler>} */ (compilers)[name];
});
}
this.hooks = Object.freeze({
/** @type {SyncHook<[MultiStats]>} */
done: new SyncHook(["stats"]),
/** @type {MultiHook<SyncHook<[string | null, number]>>} */
invalid: new MultiHook(compilers.map(c => c.hooks.invalid)),
/** @type {MultiHook<AsyncSeriesHook<[Compiler]>>} */
run: new MultiHook(compilers.map(c => c.hooks.run)),
/** @type {SyncHook<[]>} */
watchClose: new SyncHook([]),
/** @type {MultiHook<AsyncSeriesHook<[Compiler]>>} */
watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)),
/** @type {MultiHook<SyncBailHook<[string, string, any[]], true>>} */
infrastructureLog: new MultiHook(
compilers.map(c => c.hooks.infrastructureLog)
)
});
this.compilers = compilers;
/** @type {MultiCompilerOptions} */
this._options = {
parallelism: options.parallelism || Infinity
};
/** @type {WeakMap<Compiler, string[]>} */
this.dependencies = new WeakMap();
this.running = false;
/** @type {(Stats | null)[]} */
const compilerStats = this.compilers.map(() => null);
let doneCompilers = 0;
for (let index = 0; index < this.compilers.length; index++) {
const compiler = this.compilers[index];
const compilerIndex = index;
let compilerDone = false;
// eslint-disable-next-line no-loop-func
compiler.hooks.done.tap("MultiCompiler", stats => {
if (!compilerDone) {
compilerDone = true;
doneCompilers++;
}
compilerStats[compilerIndex] = stats;
if (doneCompilers === this.compilers.length) {
this.hooks.done.call(
new MultiStats(/** @type {Stats[]} */ (compilerStats))
);
}
});
// eslint-disable-next-line no-loop-func
compiler.hooks.invalid.tap("MultiCompiler", () => {
if (compilerDone) {
compilerDone = false;
doneCompilers--;
}
});
}
this._validateCompilersOptions();
}
_validateCompilersOptions() {
if (this.compilers.length < 2) return;
/**
* @param {Compiler} compiler compiler
* @param {WebpackError} warning warning
*/
const addWarning = (compiler, warning) => {
compiler.hooks.thisCompilation.tap("MultiCompiler", compilation => {
compilation.warnings.push(warning);
});
};
const cacheNames = new Set();
for (const compiler of this.compilers) {
if (compiler.options.cache && "name" in compiler.options.cache) {
const name = compiler.options.cache.name;
if (cacheNames.has(name)) {
addWarning(
compiler,
new WebpackError(
`${
compiler.name
? `Compiler with name "${compiler.name}" doesn't use unique cache name. `
: ""
}Please set unique "cache.name" option. Name "${name}" already used.`
)
);
} else {
cacheNames.add(name);
}
}
}
}
get options() {
return Object.assign(
this.compilers.map(c => c.options),
this._options
);
}
get outputPath() {
let commonPath = this.compilers[0].outputPath;
for (const compiler of this.compilers) {
while (
compiler.outputPath.indexOf(commonPath) !== 0 &&
/[/\\]/.test(commonPath)
) {
commonPath = commonPath.replace(/[/\\][^/\\]*$/, "");
}
}
if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/";
return commonPath;
}
get inputFileSystem() {
throw new Error("Cannot read inputFileSystem of a MultiCompiler");
}
/**
* @param {InputFileSystem} value the new input file system
*/
set inputFileSystem(value) {
for (const compiler of this.compilers) {
compiler.inputFileSystem = value;
}
}
get outputFileSystem() {
throw new Error("Cannot read outputFileSystem of a MultiCompiler");
}
/**
* @param {OutputFileSystem} value the new output file system
*/
set outputFileSystem(value) {
for (const compiler of this.compilers) {
compiler.outputFileSystem = value;
}
}
get watchFileSystem() {
throw new Error("Cannot read watchFileSystem of a MultiCompiler");
}
/**
* @param {WatchFileSystem} value the new watch file system
*/
set watchFileSystem(value) {
for (const compiler of this.compilers) {
compiler.watchFileSystem = value;
}
}
/**
* @param {IntermediateFileSystem} value the new intermediate file system
*/
set intermediateFileSystem(value) {
for (const compiler of this.compilers) {
compiler.intermediateFileSystem = value;
}
}
get intermediateFileSystem() {
throw new Error("Cannot read outputFileSystem of a MultiCompiler");
}
/**
* @param {string | (function(): string)} name name of the logger, or function called once to get the logger name
* @returns {Logger} a logger with that name
*/
getInfrastructureLogger(name) {
return this.compilers[0].getInfrastructureLogger(name);
}
/**
* @param {Compiler} compiler the child compiler
* @param {string[]} dependencies its dependencies
* @returns {void}
*/
setDependencies(compiler, dependencies) {
this.dependencies.set(compiler, dependencies);
}
/**
* @param {Callback<MultiStats>} callback signals when the validation is complete
* @returns {boolean} true if the dependencies are valid
*/
validateDependencies(callback) {
/** @type {Set<{source: Compiler, target: Compiler}>} */
const edges = new Set();
/** @type {string[]} */
const missing = [];
/**
* @param {Compiler} compiler compiler
* @returns {boolean} target was found
*/
const targetFound = compiler => {
for (const edge of edges) {
if (edge.target === compiler) {
return true;
}
}
return false;
};
/**
* @param {{source: Compiler, target: Compiler}} e1 edge 1
* @param {{source: Compiler, target: Compiler}} e2 edge 2
* @returns {number} result
*/
const sortEdges = (e1, e2) =>
/** @type {string} */
(e1.source.name).localeCompare(/** @type {string} */ (e2.source.name)) ||
/** @type {string} */
(e1.target.name).localeCompare(/** @type {string} */ (e2.target.name));
for (const source of this.compilers) {
const dependencies = this.dependencies.get(source);
if (dependencies) {
for (const dep of dependencies) {
const target = this.compilers.find(c => c.name === dep);
if (!target) {
missing.push(dep);
} else {
edges.add({
source,
target
});
}
}
}
}
/** @type {string[]} */
const errors = missing.map(m => `Compiler dependency \`${m}\` not found.`);
const stack = this.compilers.filter(c => !targetFound(c));
while (stack.length > 0) {
const current = stack.pop();
for (const edge of edges) {
if (edge.source === current) {
edges.delete(edge);
const target = edge.target;
if (!targetFound(target)) {
stack.push(target);
}
}
}
}
if (edges.size > 0) {
/** @type {string[]} */
const lines = Array.from(edges)
.sort(sortEdges)
.map(edge => `${edge.source.name} -> ${edge.target.name}`);
lines.unshift("Circular dependency found in compiler dependencies.");
errors.unshift(lines.join("\n"));
}
if (errors.length > 0) {
const message = errors.join("\n");
callback(new Error(message));
return false;
}
return true;
}
// TODO webpack 6 remove
/**
* @deprecated This method should have been private
* @param {Compiler[]} compilers the child compilers
* @param {RunWithDependenciesHandler} fn a handler to run for each compiler
* @param {Callback<MultiStats>} callback the compiler's handler
* @returns {void}
*/
runWithDependencies(compilers, fn, callback) {
const fulfilledNames = new Set();
let remainingCompilers = compilers;
/**
* @param {string} d dependency
* @returns {boolean} when dependency was fulfilled
*/
const isDependencyFulfilled = d => fulfilledNames.has(d);
/**
* @returns {Compiler[]} compilers
*/
const getReadyCompilers = () => {
const readyCompilers = [];
const list = remainingCompilers;
remainingCompilers = [];
for (const c of list) {
const dependencies = this.dependencies.get(c);
const ready =
!dependencies || dependencies.every(isDependencyFulfilled);
if (ready) {
readyCompilers.push(c);
} else {
remainingCompilers.push(c);
}
}
return readyCompilers;
};
/**
* @param {Callback<MultiStats>} callback callback
* @returns {void}
*/
const runCompilers = callback => {
if (remainingCompilers.length === 0) return callback(null);
asyncLib.map(
getReadyCompilers(),
(compiler, callback) => {
fn(compiler, err => {
if (err) return callback(err);
fulfilledNames.add(compiler.name);
runCompilers(callback);
});
},
(err, results) => {
callback(err, /** @type {TODO} */ (results));
}
);
};
runCompilers(callback);
}
/**
* @template SetupResult
* @param {function(Compiler, number, Callback<Stats>, function(): boolean, function(): void, function(): void): SetupResult} setup setup a single compiler
* @param {function(Compiler, SetupResult, Callback<Stats>): void} run run/continue a single compiler
* @param {Callback<MultiStats>} callback callback when all compilers are done, result includes Stats of all changed compilers
* @returns {SetupResult[]} result of setup
*/
_runGraph(setup, run, callback) {
/** @typedef {{ compiler: Compiler, setupResult: undefined | SetupResult, result: undefined | Stats, state: "pending" | "blocked" | "queued" | "starting" | "running" | "running-outdated" | "done", children: Node[], parents: Node[] }} Node */
// State transitions for nodes:
// -> blocked (initial)
// blocked -> starting [running++] (when all parents done)
// queued -> starting [running++] (when processing the queue)
// starting -> running (when run has been called)
// running -> done [running--] (when compilation is done)
// done -> pending (when invalidated from file change)
// pending -> blocked [add to queue] (when invalidated from aggregated changes)
// done -> blocked [add to queue] (when invalidated, from parent invalidation)
// running -> running-outdated (when invalidated, either from change or parent invalidation)
// running-outdated -> blocked [running--] (when compilation is done)
/** @type {Node[]} */
const nodes = this.compilers.map(compiler => ({
compiler,
setupResult: undefined,
result: undefined,
state: "blocked",
children: [],
parents: []
}));
/** @type {Map<string, Node>} */
const compilerToNode = new Map();
for (const node of nodes) {
compilerToNode.set(/** @type {string} */ (node.compiler.name), node);
}
for (const node of nodes) {
const dependencies = this.dependencies.get(node.compiler);
if (!dependencies) continue;
for (const dep of dependencies) {
const parent = /** @type {Node} */ (compilerToNode.get(dep));
node.parents.push(parent);
parent.children.push(node);
}
}
/** @type {ArrayQueue<Node>} */
const queue = new ArrayQueue();
for (const node of nodes) {
if (node.parents.length === 0) {
node.state = "queued";
queue.enqueue(node);
}
}
let errored = false;
let running = 0;
const parallelism = /** @type {number} */ (this._options.parallelism);
/**
* @param {Node} node node
* @param {(Error | null)=} err error
* @param {Stats=} stats result
* @returns {void}
*/
const nodeDone = (node, err, stats) => {
if (errored) return;
if (err) {
errored = true;
return asyncLib.each(
nodes,
(node, callback) => {
if (node.compiler.watching) {
node.compiler.watching.close(callback);
} else {
callback();
}
},
() => callback(err)
);
}
node.result = stats;
running--;
if (node.state === "running") {
node.state = "done";
for (const child of node.children) {
if (child.state === "blocked") queue.enqueue(child);
}
} else if (node.state === "running-outdated") {
node.state = "blocked";
queue.enqueue(node);
}
processQueue();
};
/**
* @param {Node} node node
* @returns {void}
*/
const nodeInvalidFromParent = node => {
if (node.state === "done") {
node.state = "blocked";
} else if (node.state === "running") {
node.state = "running-outdated";
}
for (const child of node.children) {
nodeInvalidFromParent(child);
}
};
/**
* @param {Node} node node
* @returns {void}
*/
const nodeInvalid = node => {
if (node.state === "done") {
node.state = "pending";
} else if (node.state === "running") {
node.state = "running-outdated";
}
for (const child of node.children) {
nodeInvalidFromParent(child);
}
};
/**
* @param {Node} node node
* @returns {void}
*/
const nodeChange = node => {
nodeInvalid(node);
if (node.state === "pending") {
node.state = "blocked";
}
if (node.state === "blocked") {
queue.enqueue(node);
processQueue();
}
};
/** @type {SetupResult[]} */
const setupResults = [];
for (const [i, node] of nodes.entries()) {
setupResults.push(
(node.setupResult = setup(
node.compiler,
i,
nodeDone.bind(null, node),
() => node.state !== "starting" && node.state !== "running",
() => nodeChange(node),
() => nodeInvalid(node)
))
);
}
let processing = true;
const processQueue = () => {
if (processing) return;
processing = true;
process.nextTick(processQueueWorker);
};
const processQueueWorker = () => {
// eslint-disable-next-line no-unmodified-loop-condition
while (running < parallelism && queue.length > 0 && !errored) {
const node = /** @type {Node} */ (queue.dequeue());
if (
node.state === "queued" ||
(node.state === "blocked" &&
node.parents.every(p => p.state === "done"))
) {
running++;
node.state = "starting";
run(
node.compiler,
/** @type {SetupResult} */ (node.setupResult),
nodeDone.bind(null, node)
);
node.state = "running";
}
}
processing = false;
if (
!errored &&
running === 0 &&
nodes.every(node => node.state === "done")
) {
const stats = [];
for (const node of nodes) {
const result = node.result;
if (result) {
node.result = undefined;
stats.push(result);
}
}
if (stats.length > 0) {
callback(null, new MultiStats(stats));
}
}
};
processQueueWorker();
return setupResults;
}
/**
* @param {WatchOptions|WatchOptions[]} watchOptions the watcher's options
* @param {Callback<MultiStats>} handler signals when the call finishes
* @returns {MultiWatching} a compiler watcher
*/
watch(watchOptions, handler) {
if (this.running) {
return handler(new ConcurrentCompilationError());
}
this.running = true;
if (this.validateDependencies(handler)) {
const watchings = this._runGraph(
(compiler, idx, callback, isBlocked, setChanged, setInvalid) => {
const watching = compiler.watch(
Array.isArray(watchOptions) ? watchOptions[idx] : watchOptions,
callback
);
if (watching) {
watching._onInvalid = setInvalid;
watching._onChange = setChanged;
watching._isBlocked = isBlocked;
}
return watching;
},
(compiler, watching, callback) => {
if (compiler.watching !== watching) return;
if (!watching.running) watching.invalidate();
},
handler
);
return new MultiWatching(watchings, this);
}
return new MultiWatching([], this);
}
/**
* @param {Callback<MultiStats>} callback signals when the call finishes
* @returns {void}
*/
run(callback) {
if (this.running) {
return callback(new ConcurrentCompilationError());
}
this.running = true;
if (this.validateDependencies(callback)) {
this._runGraph(
() => {},
(compiler, setupResult, callback) => compiler.run(callback),
(err, stats) => {
this.running = false;
if (callback !== undefined) {
return callback(err, stats);
}
}
);
}
}
purgeInputFileSystem() {
for (const compiler of this.compilers) {
if (compiler.inputFileSystem && compiler.inputFileSystem.purge) {
compiler.inputFileSystem.purge();
}
}
}
/**
* @param {Callback<void>} callback signals when the compiler closes
* @returns {void}
*/
close(callback) {
asyncLib.each(
this.compilers,
(compiler, callback) => {
compiler.close(callback);
},
error => {
callback(error);
}
);
}
};

208
node_modules/webpack/lib/MultiStats.js generated vendored Normal file
View file

@ -0,0 +1,208 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const identifierUtils = require("./util/identifier");
/** @typedef {import("../declarations/WebpackOptions").StatsOptions} StatsOptions */
/** @typedef {import("./Compilation").CreateStatsOptionsContext} CreateStatsOptionsContext */
/** @typedef {import("./Compilation").NormalizedStatsOptions} NormalizedStatsOptions */
/** @typedef {import("./Stats")} Stats */
/** @typedef {import("./stats/DefaultStatsFactoryPlugin").KnownStatsCompilation} KnownStatsCompilation */
/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsCompilation} StatsCompilation */
/** @typedef {import("./stats/DefaultStatsFactoryPlugin").StatsError} StatsError */
/**
* @param {string} str string
* @param {string} prefix pref
* @returns {string} indent
*/
const indent = (str, prefix) => {
const rem = str.replace(/\n([^\n])/g, `\n${prefix}$1`);
return prefix + rem;
};
/** @typedef {{ version: boolean, hash: boolean, errorsCount: boolean, warningsCount: boolean, errors: boolean, warnings: boolean, children: NormalizedStatsOptions[] }} ChildOptions */
class MultiStats {
/**
* @param {Stats[]} stats the child stats
*/
constructor(stats) {
this.stats = stats;
}
get hash() {
return this.stats.map(stat => stat.hash).join("");
}
/**
* @returns {boolean} true if a child compilation encountered an error
*/
hasErrors() {
return this.stats.some(stat => stat.hasErrors());
}
/**
* @returns {boolean} true if a child compilation had a warning
*/
hasWarnings() {
return this.stats.some(stat => stat.hasWarnings());
}
/**
* @param {string | boolean | StatsOptions | undefined} options stats options
* @param {CreateStatsOptionsContext} context context
* @returns {ChildOptions} context context
*/
_createChildOptions(options, context) {
const getCreateStatsOptions = () => {
if (!options) {
options = {};
}
const { children: childrenOptions = undefined, ...baseOptions } =
typeof options === "string"
? { preset: options }
: /** @type {StatsOptions} */ (options);
return { childrenOptions, baseOptions };
};
const children = this.stats.map((stat, idx) => {
if (typeof options === "boolean") {
return stat.compilation.createStatsOptions(options, context);
}
const { childrenOptions, baseOptions } = getCreateStatsOptions();
const childOptions = Array.isArray(childrenOptions)
? childrenOptions[idx]
: childrenOptions;
return stat.compilation.createStatsOptions(
{
...baseOptions,
...(typeof childOptions === "string"
? { preset: childOptions }
: childOptions && typeof childOptions === "object"
? childOptions
: undefined)
},
context
);
});
return {
version: children.every(o => o.version),
hash: children.every(o => o.hash),
errorsCount: children.every(o => o.errorsCount),
warningsCount: children.every(o => o.warningsCount),
errors: children.every(o => o.errors),
warnings: children.every(o => o.warnings),
children
};
}
/**
* @param {(string | boolean | StatsOptions)=} options stats options
* @returns {StatsCompilation} json output
*/
toJson(options) {
const childOptions = this._createChildOptions(options, {
forToString: false
});
/** @type {KnownStatsCompilation} */
const obj = {};
obj.children = this.stats.map((stat, idx) => {
const obj = stat.toJson(childOptions.children[idx]);
const compilationName = stat.compilation.name;
const name =
compilationName &&
identifierUtils.makePathsRelative(
stat.compilation.compiler.context,
compilationName,
stat.compilation.compiler.root
);
obj.name = name;
return obj;
});
if (childOptions.version) {
obj.version = obj.children[0].version;
}
if (childOptions.hash) {
obj.hash = obj.children.map(j => j.hash).join("");
}
/**
* @param {StatsCompilation} j stats error
* @param {StatsError} obj Stats error
* @returns {TODO} result
*/
const mapError = (j, obj) => ({
...obj,
compilerPath: obj.compilerPath ? `${j.name}.${obj.compilerPath}` : j.name
});
if (childOptions.errors) {
obj.errors = [];
for (const j of obj.children) {
const errors =
/** @type {NonNullable<KnownStatsCompilation["errors"]>} */
(j.errors);
for (const i of errors) {
obj.errors.push(mapError(j, i));
}
}
}
if (childOptions.warnings) {
obj.warnings = [];
for (const j of obj.children) {
const warnings =
/** @type {NonNullable<KnownStatsCompilation["warnings"]>} */
(j.warnings);
for (const i of warnings) {
obj.warnings.push(mapError(j, i));
}
}
}
if (childOptions.errorsCount) {
obj.errorsCount = 0;
for (const j of obj.children) {
obj.errorsCount += /** @type {number} */ (j.errorsCount);
}
}
if (childOptions.warningsCount) {
obj.warningsCount = 0;
for (const j of obj.children) {
obj.warningsCount += /** @type {number} */ (j.warningsCount);
}
}
return obj;
}
/**
* @param {(string | boolean | StatsOptions)=} options stats options
* @returns {string} string output
*/
toString(options) {
const childOptions = this._createChildOptions(options, {
forToString: true
});
const results = this.stats.map((stat, idx) => {
const str = stat.toString(childOptions.children[idx]);
const compilationName = stat.compilation.name;
const name =
compilationName &&
identifierUtils
.makePathsRelative(
stat.compilation.compiler.context,
compilationName,
stat.compilation.compiler.root
)
.replace(/\|/g, " ");
if (!str) return str;
return name ? `${name}:\n${indent(str, " ")}` : str;
});
return results.filter(Boolean).join("\n\n");
}
}
module.exports = MultiStats;

81
node_modules/webpack/lib/MultiWatching.js generated vendored Normal file
View file

@ -0,0 +1,81 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
/** @typedef {import("./MultiCompiler")} MultiCompiler */
/** @typedef {import("./Watching")} Watching */
/**
* @template T
* @callback Callback
* @param {(Error | null)=} err
* @param {T=} result
*/
class MultiWatching {
/**
* @param {Watching[]} watchings child compilers' watchers
* @param {MultiCompiler} compiler the compiler
*/
constructor(watchings, compiler) {
this.watchings = watchings;
this.compiler = compiler;
}
/**
* @param {Callback<void>=} callback signals when the build has completed again
* @returns {void}
*/
invalidate(callback) {
if (callback) {
asyncLib.each(
this.watchings,
(watching, callback) => watching.invalidate(callback),
callback
);
} else {
for (const watching of this.watchings) {
watching.invalidate();
}
}
}
suspend() {
for (const watching of this.watchings) {
watching.suspend();
}
}
resume() {
for (const watching of this.watchings) {
watching.resume();
}
}
/**
* @param {Callback<void>} callback signals when the watcher is closed
* @returns {void}
*/
close(callback) {
asyncLib.each(
this.watchings,
(watching, finishedCallback) => {
watching.close(finishedCallback);
},
err => {
this.compiler.hooks.watchClose.call();
if (typeof callback === "function") {
this.compiler.running = false;
callback(err);
}
}
);
}
}
module.exports = MultiWatching;

28
node_modules/webpack/lib/NoEmitOnErrorsPlugin.js generated vendored Normal file
View file

@ -0,0 +1,28 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./Compiler")} Compiler */
class NoEmitOnErrorsPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.shouldEmit.tap("NoEmitOnErrorsPlugin", compilation => {
if (compilation.getStats().hasErrors()) return false;
});
compiler.hooks.compilation.tap("NoEmitOnErrorsPlugin", compilation => {
compilation.hooks.shouldRecord.tap("NoEmitOnErrorsPlugin", () => {
if (compilation.getStats().hasErrors()) return false;
});
});
}
}
module.exports = NoEmitOnErrorsPlugin;

22
node_modules/webpack/lib/NoModeWarning.js generated vendored Normal file
View file

@ -0,0 +1,22 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("./WebpackError");
module.exports = class NoModeWarning extends WebpackError {
constructor() {
super();
this.name = "NoModeWarning";
this.message =
"configuration\n" +
"The 'mode' option has not been set, webpack will fallback to 'production' for this value.\n" +
"Set 'mode' option to 'development' or 'production' to enable defaults for each environment.\n" +
"You can also set it to 'none' to disable any default behavior. " +
"Learn more: https://webpack.js.org/configuration/mode/";
}
};

275
node_modules/webpack/lib/NodeStuffPlugin.js generated vendored Normal file
View file

@ -0,0 +1,275 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC
} = require("./ModuleTypeConstants");
const NodeStuffInWebError = require("./NodeStuffInWebError");
const RuntimeGlobals = require("./RuntimeGlobals");
const CachedConstDependency = require("./dependencies/CachedConstDependency");
const ConstDependency = require("./dependencies/ConstDependency");
const ExternalModuleDependency = require("./dependencies/ExternalModuleDependency");
const {
evaluateToString,
expressionIsUnsupported
} = require("./javascript/JavascriptParserHelpers");
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 */
const PLUGIN_NAME = "NodeStuffPlugin";
class NodeStuffPlugin {
/**
* @param {NodeOptions} options options
*/
constructor(options) {
this.options = options;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const options = this.options;
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ExternalModuleDependency,
new ExternalModuleDependency.Template()
);
/**
* @param {JavascriptParser} parser the parser
* @param {JavascriptParserOptions} parserOptions options
* @returns {void}
*/
const handler = (parser, parserOptions) => {
if (parserOptions.node === false) return;
let localOptions = options;
if (parserOptions.node) {
localOptions = { ...localOptions, ...parserOptions.node };
}
if (localOptions.global !== false) {
const withWarning = localOptions.global === "warn";
parser.hooks.expression.for("global").tap(PLUGIN_NAME, expr => {
const dep = new ConstDependency(
RuntimeGlobals.global,
/** @type {Range} */ (expr.range),
[RuntimeGlobals.global]
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
// TODO webpack 6 remove
if (withWarning) {
parser.state.module.addWarning(
new NodeStuffInWebError(
dep.loc,
"global",
"The global namespace object is a Node.js feature and isn't available in browsers."
)
);
}
});
parser.hooks.rename.for("global").tap(PLUGIN_NAME, expr => {
const dep = new ConstDependency(
RuntimeGlobals.global,
/** @type {Range} */ (expr.range),
[RuntimeGlobals.global]
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return false;
});
}
/**
* @param {string} expressionName expression name
* @param {(module: NormalModule) => string} fn function
* @param {string=} warning warning
* @returns {void}
*/
const setModuleConstant = (expressionName, fn, warning) => {
parser.hooks.expression
.for(expressionName)
.tap(PLUGIN_NAME, expr => {
const dep = new CachedConstDependency(
JSON.stringify(fn(parser.state.module)),
/** @type {Range} */ (expr.range),
expressionName
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
// TODO webpack 6 remove
if (warning) {
parser.state.module.addWarning(
new NodeStuffInWebError(dep.loc, expressionName, warning)
);
}
return true;
});
};
/**
* @param {string} expressionName expression name
* @param {(value: string) => string} fn function
* @returns {void}
*/
const setUrlModuleConstant = (expressionName, fn) => {
parser.hooks.expression
.for(expressionName)
.tap(PLUGIN_NAME, expr => {
const dep = new ExternalModuleDependency(
"url",
[
{
name: "fileURLToPath",
value: "__webpack_fileURLToPath__"
}
],
undefined,
fn("__webpack_fileURLToPath__"),
/** @type {Range} */ (expr.range),
expressionName
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addPresentationalDependency(dep);
return true;
});
};
/**
* @param {string} expressionName expression name
* @param {string} value value
* @param {string=} warning warning
* @returns {void}
*/
const setConstant = (expressionName, value, warning) =>
setModuleConstant(expressionName, () => value, warning);
const context = compiler.context;
if (localOptions.__filename) {
switch (localOptions.__filename) {
case "mock":
setConstant("__filename", "/index.js");
break;
case "warn-mock":
setConstant(
"__filename",
"/index.js",
"__filename is a Node.js feature and isn't available in browsers."
);
break;
case "node-module":
setUrlModuleConstant(
"__filename",
functionName => `${functionName}(import.meta.url)`
);
break;
case true:
setModuleConstant("__filename", module =>
relative(
/** @type {InputFileSystem} */ (compiler.inputFileSystem),
context,
module.resource
)
);
break;
}
parser.hooks.evaluateIdentifier
.for("__filename")
.tap(PLUGIN_NAME, expr => {
if (!parser.state.module) return;
const resource = parseResource(parser.state.module.resource);
return evaluateToString(resource.path)(expr);
});
}
if (localOptions.__dirname) {
switch (localOptions.__dirname) {
case "mock":
setConstant("__dirname", "/");
break;
case "warn-mock":
setConstant(
"__dirname",
"/",
"__dirname is a Node.js feature and isn't available in browsers."
);
break;
case "node-module":
setUrlModuleConstant(
"__dirname",
functionName =>
`${functionName}(import.meta.url + "/..").slice(0, -1)`
);
break;
case true:
setModuleConstant("__dirname", module =>
relative(
/** @type {InputFileSystem} */ (compiler.inputFileSystem),
context,
/** @type {string} */ (module.context)
)
);
break;
}
parser.hooks.evaluateIdentifier
.for("__dirname")
.tap(PLUGIN_NAME, expr => {
if (!parser.state.module) return;
return evaluateToString(
/** @type {string} */ (parser.state.module.context)
)(expr);
});
}
parser.hooks.expression
.for("require.extensions")
.tap(
PLUGIN_NAME,
expressionIsUnsupported(
parser,
"require.extensions is not supported by webpack. Use a loader instead."
)
);
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
}
);
}
}
module.exports = NodeStuffPlugin;

1639
node_modules/webpack/lib/NormalModule.js generated vendored Normal file

File diff suppressed because it is too large Load diff

1310
node_modules/webpack/lib/NormalModuleFactory.js generated vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,77 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { join, dirname } = require("./util/fs");
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {function(import("./NormalModuleFactory").ResolveData): void} ModuleReplacer */
class NormalModuleReplacementPlugin {
/**
* Create an instance of the plugin
* @param {RegExp} resourceRegExp the resource matcher
* @param {string|ModuleReplacer} newResource the resource replacement
*/
constructor(resourceRegExp, newResource) {
this.resourceRegExp = resourceRegExp;
this.newResource = newResource;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const resourceRegExp = this.resourceRegExp;
const newResource = this.newResource;
compiler.hooks.normalModuleFactory.tap(
"NormalModuleReplacementPlugin",
nmf => {
nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => {
if (resourceRegExp.test(result.request)) {
if (typeof newResource === "function") {
newResource(result);
} else {
result.request = newResource;
}
}
});
nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => {
const createData = result.createData;
if (
resourceRegExp.test(/** @type {string} */ (createData.resource))
) {
if (typeof newResource === "function") {
newResource(result);
} else {
const fs =
/** @type {InputFileSystem} */
(compiler.inputFileSystem);
if (
newResource.startsWith("/") ||
(newResource.length > 1 && newResource[1] === ":")
) {
createData.resource = newResource;
} else {
createData.resource = join(
fs,
dirname(fs, /** @type {string} */ (createData.resource)),
newResource
);
}
}
}
});
}
);
}
}
module.exports = NormalModuleReplacementPlugin;

23
node_modules/webpack/lib/NullFactory.js generated vendored Normal file
View file

@ -0,0 +1,23 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ModuleFactory = require("./ModuleFactory");
/** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
class NullFactory extends ModuleFactory {
/**
* @param {ModuleFactoryCreateData} data data object
* @param {function((Error | null)=, ModuleFactoryResult=): void} callback callback
* @returns {void}
*/
create(data, callback) {
return callback();
}
}
module.exports = NullFactory;

11
node_modules/webpack/lib/OptionsApply.js generated vendored Normal file
View file

@ -0,0 +1,11 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class OptionsApply {
process(options, compiler) {}
}
module.exports = OptionsApply;

38
node_modules/webpack/lib/Parser.js generated vendored Normal file
View file

@ -0,0 +1,38 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./NormalModule")} NormalModule */
/** @typedef {Record<string, any>} PreparsedAst */
/**
* @typedef {object} ParserStateBase
* @property {string | Buffer} source
* @property {NormalModule} current
* @property {NormalModule} module
* @property {Compilation} compilation
* @property {{[k: string]: any}} options
*/
/** @typedef {Record<string, any> & ParserStateBase} ParserState */
class Parser {
/* istanbul ignore next */
/**
* @abstract
* @param {string | Buffer | PreparsedAst} source the source to parse
* @param {ParserState} state the parser state
* @returns {ParserState} the parser state
*/
parse(source, state) {
const AbstractMethodError = require("./AbstractMethodError");
throw new AbstractMethodError();
}
}
module.exports = Parser;

54
node_modules/webpack/lib/PrefetchPlugin.js generated vendored Normal file
View file

@ -0,0 +1,54 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const PrefetchDependency = require("./dependencies/PrefetchDependency");
/** @typedef {import("./Compiler")} Compiler */
class PrefetchPlugin {
/**
* @param {string} context context or request if context is not set
* @param {string} [request] request
*/
constructor(context, request) {
if (request) {
this.context = context;
this.request = request;
} else {
this.context = null;
this.request = context;
}
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
"PrefetchPlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(
PrefetchDependency,
normalModuleFactory
);
}
);
compiler.hooks.make.tapAsync("PrefetchPlugin", (compilation, callback) => {
compilation.addModuleChain(
this.context || compiler.context,
new PrefetchDependency(this.request),
err => {
callback(err);
}
);
});
}
}
module.exports = PrefetchPlugin;

669
node_modules/webpack/lib/ProgressPlugin.js generated vendored Normal file
View file

@ -0,0 +1,669 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Compiler = require("./Compiler");
const MultiCompiler = require("./MultiCompiler");
const NormalModule = require("./NormalModule");
const createSchemaValidation = require("./util/create-schema-validation");
const { contextify } = require("./util/identifier");
/** @typedef {import("tapable").Tap} Tap */
/** @typedef {import("../declarations/plugins/ProgressPlugin").HandlerFunction} HandlerFunction */
/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */
/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./logging/Logger").Logger} Logger */
/**
* @typedef {object} CountsData
* @property {number} modulesCount modules count
* @property {number} dependenciesCount dependencies count
*/
const validate = createSchemaValidation(
require("../schemas/plugins/ProgressPlugin.check.js"),
() => require("../schemas/plugins/ProgressPlugin.json"),
{
name: "Progress Plugin",
baseDataPath: "options"
}
);
/**
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @returns {number} median
*/
const median3 = (a, b, c) => a + b + c - Math.max(a, b, c) - Math.min(a, b, c);
/**
* @param {boolean | null | undefined} profile need profile
* @param {Logger} logger logger
* @returns {defaultHandler} 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
*/
const defaultHandler = (percentage, msg, ...args) => {
if (profile) {
if (percentage === 0) {
lastStateInfo.length = 0;
}
const fullState = [msg, ...args];
const state = fullState.map(s => s.replace(/\d+\/\d+ /g, ""));
const now = Date.now();
const len = Math.max(state.length, lastStateInfo.length);
for (let i = len; i >= 0; i--) {
const stateItem = i < state.length ? state[i] : undefined;
const lastStateItem =
i < lastStateInfo.length ? lastStateInfo[i] : undefined;
if (lastStateItem) {
if (stateItem !== lastStateItem.value) {
const diff = now - lastStateItem.time;
if (lastStateItem.value) {
let reportState = lastStateItem.value;
if (i > 0) {
reportState = `${lastStateInfo[i - 1].value} > ${reportState}`;
}
const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`;
const d = diff;
// This depends on timing so we ignore it for coverage
/* eslint-disable no-lone-blocks */
/* istanbul ignore next */
{
if (d > 10000) {
logger.error(stateMsg);
} else if (d > 1000) {
logger.warn(stateMsg);
} else if (d > 10) {
logger.info(stateMsg);
} else if (d > 5) {
logger.log(stateMsg);
} else {
logger.debug(stateMsg);
}
}
/* eslint-enable no-lone-blocks */
}
if (stateItem === undefined) {
lastStateInfo.length = i;
} else {
lastStateItem.value = stateItem;
lastStateItem.time = now;
lastStateInfo.length = i + 1;
}
}
} else {
lastStateInfo[i] = {
value: stateItem,
time: now
};
}
}
}
logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args);
if (percentage === 1 || (!msg && args.length === 0)) logger.status();
};
return defaultHandler;
};
/**
* @callback ReportProgress
* @param {number} p percentage
* @param {...string} args additional arguments
* @returns {void}
*/
/** @type {WeakMap<Compiler, ReportProgress | undefined>} */
const progressReporters = new WeakMap();
class ProgressPlugin {
/**
* @param {Compiler} compiler the current compiler
* @returns {ReportProgress | undefined} a progress reporter, if any
*/
static getReporter(compiler) {
return progressReporters.get(compiler);
}
/**
* @param {ProgressPluginArgument} options options
*/
constructor(options = {}) {
if (typeof options === "function") {
options = {
handler: options
};
}
validate(options);
options = { ...ProgressPlugin.defaultOptions, ...options };
this.profile = options.profile;
this.handler = options.handler;
this.modulesCount = options.modulesCount;
this.dependenciesCount = options.dependenciesCount;
this.showEntries = options.entries;
this.showModules = options.modules;
this.showDependencies = options.dependencies;
this.showActiveModules = options.activeModules;
this.percentBy = options.percentBy;
}
/**
* @param {Compiler | MultiCompiler} compiler webpack compiler
* @returns {void}
*/
apply(compiler) {
const handler =
this.handler ||
createDefaultHandler(
this.profile,
compiler.getInfrastructureLogger("webpack.Progress")
);
if (compiler instanceof MultiCompiler) {
this._applyOnMultiCompiler(compiler, handler);
} else if (compiler instanceof Compiler) {
this._applyOnCompiler(compiler, handler);
}
}
/**
* @param {MultiCompiler} compiler webpack multi-compiler
* @param {HandlerFunction} handler function that executes for every progress step
* @returns {void}
*/
_applyOnMultiCompiler(compiler, handler) {
const states = compiler.compilers.map(
() => /** @type {[number, ...string[]]} */ ([0])
);
for (const [idx, item] of compiler.compilers.entries()) {
new ProgressPlugin((p, msg, ...args) => {
states[idx] = [p, msg, ...args];
let sum = 0;
for (const [p] of states) sum += p;
handler(sum / states.length, `[${idx}] ${msg}`, ...args);
}).apply(item);
}
}
/**
* @param {Compiler} compiler webpack compiler
* @param {HandlerFunction} handler function that executes for every progress step
* @returns {void}
*/
_applyOnCompiler(compiler, handler) {
const showEntries = this.showEntries;
const showModules = this.showModules;
const showDependencies = this.showDependencies;
const showActiveModules = this.showActiveModules;
let lastActiveModule = "";
let currentLoader = "";
let lastModulesCount = 0;
let lastDependenciesCount = 0;
let lastEntriesCount = 0;
let modulesCount = 0;
let dependenciesCount = 0;
let entriesCount = 1;
let doneModules = 0;
let doneDependencies = 0;
let doneEntries = 0;
const activeModules = new Set();
let lastUpdate = 0;
const updateThrottled = () => {
if (lastUpdate + 500 < Date.now()) update();
};
const update = () => {
/** @type {string[]} */
const items = [];
const percentByModules =
doneModules /
Math.max(lastModulesCount || this.modulesCount || 1, modulesCount);
const percentByEntries =
doneEntries /
Math.max(lastEntriesCount || this.dependenciesCount || 1, entriesCount);
const percentByDependencies =
doneDependencies /
Math.max(lastDependenciesCount || 1, dependenciesCount);
let percentageFactor;
switch (this.percentBy) {
case "entries":
percentageFactor = percentByEntries;
break;
case "dependencies":
percentageFactor = percentByDependencies;
break;
case "modules":
percentageFactor = percentByModules;
break;
default:
percentageFactor = median3(
percentByModules,
percentByEntries,
percentByDependencies
);
}
const percentage = 0.1 + percentageFactor * 0.55;
if (currentLoader) {
items.push(
`import loader ${contextify(
compiler.context,
currentLoader,
compiler.root
)}`
);
} else {
const statItems = [];
if (showEntries) {
statItems.push(`${doneEntries}/${entriesCount} entries`);
}
if (showDependencies) {
statItems.push(
`${doneDependencies}/${dependenciesCount} dependencies`
);
}
if (showModules) {
statItems.push(`${doneModules}/${modulesCount} modules`);
}
if (showActiveModules) {
statItems.push(`${activeModules.size} active`);
}
if (statItems.length > 0) {
items.push(statItems.join(" "));
}
if (showActiveModules) {
items.push(lastActiveModule);
}
}
handler(percentage, "building", ...items);
lastUpdate = Date.now();
};
const factorizeAdd = () => {
dependenciesCount++;
if (dependenciesCount < 50 || dependenciesCount % 100 === 0)
updateThrottled();
};
const factorizeDone = () => {
doneDependencies++;
if (doneDependencies < 50 || doneDependencies % 100 === 0)
updateThrottled();
};
const moduleAdd = () => {
modulesCount++;
if (modulesCount < 50 || modulesCount % 100 === 0) updateThrottled();
};
// only used when showActiveModules is set
/**
* @param {Module} module the module
*/
const moduleBuild = module => {
const ident = module.identifier();
if (ident) {
activeModules.add(ident);
lastActiveModule = ident;
update();
}
};
/**
* @param {Dependency} entry entry dependency
* @param {EntryOptions} options options object
*/
const entryAdd = (entry, options) => {
entriesCount++;
if (entriesCount < 5 || entriesCount % 10 === 0) updateThrottled();
};
/**
* @param {Module} module the module
*/
const moduleDone = module => {
doneModules++;
if (showActiveModules) {
const ident = module.identifier();
if (ident) {
activeModules.delete(ident);
if (lastActiveModule === ident) {
lastActiveModule = "";
for (const m of activeModules) {
lastActiveModule = m;
}
update();
return;
}
}
}
if (doneModules < 50 || doneModules % 100 === 0) updateThrottled();
};
/**
* @param {Dependency} entry entry dependency
* @param {EntryOptions} options options object
*/
const entryDone = (entry, options) => {
doneEntries++;
update();
};
const cache = compiler
.getCache("ProgressPlugin")
.getItemCache("counts", null);
/** @type {Promise<CountsData> | undefined} */
let cacheGetPromise;
compiler.hooks.beforeCompile.tap("ProgressPlugin", () => {
if (!cacheGetPromise) {
cacheGetPromise = cache.getPromise().then(
data => {
if (data) {
lastModulesCount = lastModulesCount || data.modulesCount;
lastDependenciesCount =
lastDependenciesCount || data.dependenciesCount;
}
return data;
},
err => {
// Ignore error
}
);
}
});
compiler.hooks.afterCompile.tapPromise("ProgressPlugin", compilation => {
if (compilation.compiler.isChild()) return Promise.resolve();
return /** @type {Promise<CountsData>} */ (cacheGetPromise).then(
async oldData => {
if (
!oldData ||
oldData.modulesCount !== modulesCount ||
oldData.dependenciesCount !== dependenciesCount
) {
await cache.storePromise({ modulesCount, dependenciesCount });
}
}
);
});
compiler.hooks.compilation.tap("ProgressPlugin", compilation => {
if (compilation.compiler.isChild()) return;
lastModulesCount = modulesCount;
lastEntriesCount = entriesCount;
lastDependenciesCount = dependenciesCount;
modulesCount = dependenciesCount = entriesCount = 0;
doneModules = doneDependencies = doneEntries = 0;
compilation.factorizeQueue.hooks.added.tap(
"ProgressPlugin",
factorizeAdd
);
compilation.factorizeQueue.hooks.result.tap(
"ProgressPlugin",
factorizeDone
);
compilation.addModuleQueue.hooks.added.tap("ProgressPlugin", moduleAdd);
compilation.processDependenciesQueue.hooks.result.tap(
"ProgressPlugin",
moduleDone
);
if (showActiveModules) {
compilation.hooks.buildModule.tap("ProgressPlugin", moduleBuild);
}
compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd);
compilation.hooks.failedEntry.tap("ProgressPlugin", entryDone);
compilation.hooks.succeedEntry.tap("ProgressPlugin", entryDone);
// avoid dynamic require if bundled with webpack
// @ts-expect-error
if (typeof __webpack_require__ !== "function") {
const requiredLoaders = new Set();
NormalModule.getCompilationHooks(compilation).beforeLoaders.tap(
"ProgressPlugin",
loaders => {
for (const loader of loaders) {
if (
loader.type !== "module" &&
!requiredLoaders.has(loader.loader)
) {
requiredLoaders.add(loader.loader);
currentLoader = loader.loader;
update();
require(loader.loader);
}
}
if (currentLoader) {
currentLoader = "";
update();
}
}
);
}
const hooks = {
finishModules: "finish module graph",
seal: "plugins",
optimizeDependencies: "dependencies optimization",
afterOptimizeDependencies: "after dependencies optimization",
beforeChunks: "chunk graph",
afterChunks: "after chunk graph",
optimize: "optimizing",
optimizeModules: "module optimization",
afterOptimizeModules: "after module optimization",
optimizeChunks: "chunk optimization",
afterOptimizeChunks: "after chunk optimization",
optimizeTree: "module and chunk tree optimization",
afterOptimizeTree: "after module and chunk tree optimization",
optimizeChunkModules: "chunk modules optimization",
afterOptimizeChunkModules: "after chunk modules optimization",
reviveModules: "module reviving",
beforeModuleIds: "before module ids",
moduleIds: "module ids",
optimizeModuleIds: "module id optimization",
afterOptimizeModuleIds: "module id optimization",
reviveChunks: "chunk reviving",
beforeChunkIds: "before chunk ids",
chunkIds: "chunk ids",
optimizeChunkIds: "chunk id optimization",
afterOptimizeChunkIds: "after chunk id optimization",
recordModules: "record modules",
recordChunks: "record chunks",
beforeModuleHash: "module hashing",
beforeCodeGeneration: "code generation",
beforeRuntimeRequirements: "runtime requirements",
beforeHash: "hashing",
afterHash: "after hashing",
recordHash: "record hash",
beforeModuleAssets: "module assets processing",
beforeChunkAssets: "chunk assets processing",
processAssets: "asset processing",
afterProcessAssets: "after asset optimization",
record: "recording",
afterSeal: "after seal"
};
const numberOfHooks = Object.keys(hooks).length;
for (const [idx, name] of Object.keys(hooks).entries()) {
const title = hooks[/** @type {keyof typeof hooks} */ (name)];
const percentage = (idx / numberOfHooks) * 0.25 + 0.7;
compilation.hooks[/** @type {keyof typeof hooks} */ (name)].intercept({
name: "ProgressPlugin",
call() {
handler(percentage, "sealing", title);
},
done() {
progressReporters.set(compiler, undefined);
handler(percentage, "sealing", title);
},
result() {
handler(percentage, "sealing", title);
},
error() {
handler(percentage, "sealing", title);
},
tap(tap) {
// p is percentage from 0 to 1
// args is any number of messages in a hierarchical matter
progressReporters.set(compilation.compiler, (p, ...args) => {
handler(percentage, "sealing", title, tap.name, ...args);
});
handler(percentage, "sealing", title, tap.name);
}
});
}
});
compiler.hooks.make.intercept({
name: "ProgressPlugin",
call() {
handler(0.1, "building");
},
done() {
handler(0.65, "building");
}
});
/**
* @param {TODO} hook hook
* @param {number} progress progress from 0 to 1
* @param {string} category category
* @param {string} name name
*/
const interceptHook = (hook, progress, category, name) => {
hook.intercept({
name: "ProgressPlugin",
call() {
handler(progress, category, name);
},
done() {
progressReporters.set(compiler, undefined);
handler(progress, category, name);
},
result() {
handler(progress, category, name);
},
error() {
handler(progress, category, name);
},
/**
* @param {Tap} tap tap
*/
tap(tap) {
progressReporters.set(compiler, (p, ...args) => {
handler(progress, category, name, tap.name, ...args);
});
handler(progress, category, name, tap.name);
}
});
};
compiler.cache.hooks.endIdle.intercept({
name: "ProgressPlugin",
call() {
handler(0, "");
}
});
interceptHook(compiler.cache.hooks.endIdle, 0.01, "cache", "end idle");
compiler.hooks.beforeRun.intercept({
name: "ProgressPlugin",
call() {
handler(0, "");
}
});
interceptHook(compiler.hooks.beforeRun, 0.01, "setup", "before run");
interceptHook(compiler.hooks.run, 0.02, "setup", "run");
interceptHook(compiler.hooks.watchRun, 0.03, "setup", "watch run");
interceptHook(
compiler.hooks.normalModuleFactory,
0.04,
"setup",
"normal module factory"
);
interceptHook(
compiler.hooks.contextModuleFactory,
0.05,
"setup",
"context module factory"
);
interceptHook(
compiler.hooks.beforeCompile,
0.06,
"setup",
"before compile"
);
interceptHook(compiler.hooks.compile, 0.07, "setup", "compile");
interceptHook(compiler.hooks.thisCompilation, 0.08, "setup", "compilation");
interceptHook(compiler.hooks.compilation, 0.09, "setup", "compilation");
interceptHook(compiler.hooks.finishMake, 0.69, "building", "finish");
interceptHook(compiler.hooks.emit, 0.95, "emitting", "emit");
interceptHook(compiler.hooks.afterEmit, 0.98, "emitting", "after emit");
interceptHook(compiler.hooks.done, 0.99, "done", "plugins");
compiler.hooks.done.intercept({
name: "ProgressPlugin",
done() {
handler(0.99, "");
}
});
interceptHook(
compiler.cache.hooks.storeBuildDependencies,
0.99,
"cache",
"store build dependencies"
);
interceptHook(compiler.cache.hooks.shutdown, 0.99, "cache", "shutdown");
interceptHook(compiler.cache.hooks.beginIdle, 0.99, "cache", "begin idle");
interceptHook(
compiler.hooks.watchClose,
0.99,
"end",
"closing watch compilation"
);
compiler.cache.hooks.beginIdle.intercept({
name: "ProgressPlugin",
done() {
handler(1, "");
}
});
compiler.cache.hooks.shutdown.intercept({
name: "ProgressPlugin",
done() {
handler(1, "");
}
});
}
}
ProgressPlugin.defaultOptions = {
profile: false,
modulesCount: 5000,
dependenciesCount: 10000,
modules: true,
dependencies: true,
activeModules: false,
entries: true
};
ProgressPlugin.createDefaultHandler = createDefaultHandler;
module.exports = ProgressPlugin;

119
node_modules/webpack/lib/ProvidePlugin.js generated vendored Normal file
View file

@ -0,0 +1,119 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const ConstDependency = require("./dependencies/ConstDependency");
const ProvidedDependency = require("./dependencies/ProvidedDependency");
const { approve } = require("./javascript/JavascriptParserHelpers");
/** @typedef {import("../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
/** @typedef {import("./javascript/JavascriptParser").Range} Range */
const PLUGIN_NAME = "ProvidePlugin";
class ProvidePlugin {
/**
* @param {Record<string, string | string[]>} definitions the provided identifiers
*/
constructor(definitions) {
this.definitions = definitions;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const definitions = this.definitions;
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
compilation.dependencyFactories.set(
ProvidedDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ProvidedDependency,
new ProvidedDependency.Template()
);
/**
* @param {JavascriptParser} parser the parser
* @param {JavascriptParserOptions} parserOptions options
* @returns {void}
*/
const handler = (parser, parserOptions) => {
for (const name of Object.keys(definitions)) {
const request =
/** @type {string[]} */
([]).concat(definitions[name]);
const splittedName = name.split(".");
if (splittedName.length > 0) {
for (const [i, _] of splittedName.slice(1).entries()) {
const name = splittedName.slice(0, i + 1).join(".");
parser.hooks.canRename.for(name).tap(PLUGIN_NAME, approve);
}
}
parser.hooks.expression.for(name).tap(PLUGIN_NAME, expr => {
const nameIdentifier = name.includes(".")
? `__webpack_provided_${name.replace(/\./g, "_dot_")}`
: name;
const dep = new ProvidedDependency(
request[0],
nameIdentifier,
request.slice(1),
/** @type {Range} */ (expr.range)
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addDependency(dep);
return true;
});
parser.hooks.call.for(name).tap(PLUGIN_NAME, expr => {
const nameIdentifier = name.includes(".")
? `__webpack_provided_${name.replace(/\./g, "_dot_")}`
: name;
const dep = new ProvidedDependency(
request[0],
nameIdentifier,
request.slice(1),
/** @type {Range} */ (expr.callee.range)
);
dep.loc = /** @type {DependencyLocation} */ (expr.callee.loc);
parser.state.module.addDependency(dep);
parser.walkExpressions(expr.arguments);
return true;
});
}
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_ESM)
.tap(PLUGIN_NAME, handler);
}
);
}
}
module.exports = ProvidePlugin;

165
node_modules/webpack/lib/RawModule.js generated vendored Normal file
View file

@ -0,0 +1,165 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { OriginalSource, RawSource } = require("webpack-sources");
const Module = require("./Module");
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("./Compilation")} Compilation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
/** @typedef {import("./Module").SourceTypes} SourceTypes */
/** @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 */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
const TYPES = new Set(["javascript"]);
class RawModule extends Module {
/**
* @param {string} source source code
* @param {string} identifier unique identifier
* @param {string=} readableIdentifier readable identifier
* @param {ReadOnlyRuntimeRequirements=} runtimeRequirements runtime requirements needed for the source code
*/
constructor(source, identifier, readableIdentifier, runtimeRequirements) {
super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
this.sourceStr = source;
this.identifierStr = identifier || this.sourceStr;
this.readableIdentifierStr = readableIdentifier || this.identifierStr;
this.runtimeRequirements = runtimeRequirements || null;
}
/**
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
}
/**
* @returns {string} a unique identifier of the module
*/
identifier() {
return this.identifierStr;
}
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
return Math.max(1, this.sourceStr.length);
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return /** @type {string} */ (
requestShortener.shorten(this.readableIdentifierStr)
);
}
/**
* @param {NeedBuildContext} context context info
* @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
return callback(null, !this.buildMeta);
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
this.buildMeta = {};
this.buildInfo = {
cacheable: true
};
callback();
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration(context) {
const sources = new Map();
if (this.useSourceMap || this.useSimpleSourceMap) {
sources.set(
"javascript",
new OriginalSource(this.sourceStr, this.identifier())
);
} else {
sources.set("javascript", new RawSource(this.sourceStr));
}
return { sources, runtimeRequirements: this.runtimeRequirements };
}
/**
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
hash.update(this.sourceStr);
super.updateHash(hash, context);
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.sourceStr);
write(this.identifierStr);
write(this.readableIdentifierStr);
write(this.runtimeRequirements);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
this.sourceStr = read();
this.identifierStr = read();
this.readableIdentifierStr = read();
this.runtimeRequirements = read();
super.deserialize(context);
}
}
makeSerializable(RawModule, "webpack/lib/RawModule");
module.exports = RawModule;

238
node_modules/webpack/lib/RecordIdsPlugin.js generated vendored Normal file
View file

@ -0,0 +1,238 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { compareNumbers } = require("./util/comparators");
const identifierUtils = require("./util/identifier");
/** @typedef {import("./Chunk")} Chunk */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Module")} Module */
/**
* @typedef {object} RecordsChunks
* @property {Record<string, number>=} byName
* @property {Record<string, number>=} bySource
* @property {number[]=} usedIds
*/
/**
* @typedef {object} RecordsModules
* @property {Record<string, number>=} byIdentifier
* @property {Record<string, number>=} bySource
* @property {number[]=} usedIds
*/
/**
* @typedef {object} Records
* @property {RecordsChunks=} chunks
* @property {RecordsModules=} modules
*/
class RecordIdsPlugin {
/**
* @param {object} options Options object
* @param {boolean=} options.portableIds true, when ids need to be portable
*/
constructor(options) {
this.options = options || {};
}
/**
* @param {Compiler} compiler the Compiler
* @returns {void}
*/
apply(compiler) {
const portableIds = this.options.portableIds;
const makePathsRelative =
identifierUtils.makePathsRelative.bindContextCache(
compiler.context,
compiler.root
);
/**
* @param {Module} module the module
* @returns {string} the (portable) identifier
*/
const getModuleIdentifier = module => {
if (portableIds) {
return makePathsRelative(module.identifier());
}
return module.identifier();
};
compiler.hooks.compilation.tap("RecordIdsPlugin", compilation => {
compilation.hooks.recordModules.tap(
"RecordIdsPlugin",
/**
* @param {Iterable<Module>} modules the modules array
* @param {Records} records the records object
* @returns {void}
*/
(modules, records) => {
const chunkGraph = compilation.chunkGraph;
if (!records.modules) records.modules = {};
if (!records.modules.byIdentifier) records.modules.byIdentifier = {};
/** @type {Set<number>} */
const usedIds = new Set();
for (const module of modules) {
const moduleId = chunkGraph.getModuleId(module);
if (typeof moduleId !== "number") continue;
const identifier = getModuleIdentifier(module);
records.modules.byIdentifier[identifier] = moduleId;
usedIds.add(moduleId);
}
records.modules.usedIds = Array.from(usedIds).sort(compareNumbers);
}
);
compilation.hooks.reviveModules.tap(
"RecordIdsPlugin",
/**
* @param {Iterable<Module>} modules the modules array
* @param {Records} records the records object
* @returns {void}
*/
(modules, records) => {
if (!records.modules) return;
if (records.modules.byIdentifier) {
const chunkGraph = compilation.chunkGraph;
/** @type {Set<number>} */
const usedIds = new Set();
for (const module of modules) {
const moduleId = chunkGraph.getModuleId(module);
if (moduleId !== null) continue;
const identifier = getModuleIdentifier(module);
const id = records.modules.byIdentifier[identifier];
if (id === undefined) continue;
if (usedIds.has(id)) continue;
usedIds.add(id);
chunkGraph.setModuleId(module, id);
}
}
if (Array.isArray(records.modules.usedIds)) {
compilation.usedModuleIds = new Set(records.modules.usedIds);
}
}
);
/**
* @param {Chunk} chunk the chunk
* @returns {string[]} sources of the chunk
*/
const getChunkSources = chunk => {
/** @type {string[]} */
const sources = [];
for (const chunkGroup of chunk.groupsIterable) {
const index = chunkGroup.chunks.indexOf(chunk);
if (chunkGroup.name) {
sources.push(`${index} ${chunkGroup.name}`);
} else {
for (const origin of chunkGroup.origins) {
if (origin.module) {
if (origin.request) {
sources.push(
`${index} ${getModuleIdentifier(origin.module)} ${
origin.request
}`
);
} else if (typeof origin.loc === "string") {
sources.push(
`${index} ${getModuleIdentifier(origin.module)} ${
origin.loc
}`
);
} else if (
origin.loc &&
typeof origin.loc === "object" &&
"start" in origin.loc
) {
sources.push(
`${index} ${getModuleIdentifier(
origin.module
)} ${JSON.stringify(origin.loc.start)}`
);
}
}
}
}
}
return sources;
};
compilation.hooks.recordChunks.tap(
"RecordIdsPlugin",
/**
* @param {Iterable<Chunk>} chunks the chunks array
* @param {Records} records the records object
* @returns {void}
*/
(chunks, records) => {
if (!records.chunks) records.chunks = {};
if (!records.chunks.byName) records.chunks.byName = {};
if (!records.chunks.bySource) records.chunks.bySource = {};
/** @type {Set<number>} */
const usedIds = new Set();
for (const chunk of chunks) {
if (typeof chunk.id !== "number") continue;
const name = chunk.name;
if (name) records.chunks.byName[name] = chunk.id;
const sources = getChunkSources(chunk);
for (const source of sources) {
records.chunks.bySource[source] = chunk.id;
}
usedIds.add(chunk.id);
}
records.chunks.usedIds = Array.from(usedIds).sort(compareNumbers);
}
);
compilation.hooks.reviveChunks.tap(
"RecordIdsPlugin",
/**
* @param {Iterable<Chunk>} chunks the chunks array
* @param {Records} records the records object
* @returns {void}
*/
(chunks, records) => {
if (!records.chunks) return;
/** @type {Set<number>} */
const usedIds = new Set();
if (records.chunks.byName) {
for (const chunk of chunks) {
if (chunk.id !== null) continue;
if (!chunk.name) continue;
const id = records.chunks.byName[chunk.name];
if (id === undefined) continue;
if (usedIds.has(id)) continue;
usedIds.add(id);
chunk.id = id;
chunk.ids = [id];
}
}
if (records.chunks.bySource) {
for (const chunk of chunks) {
if (chunk.id !== null) continue;
const sources = getChunkSources(chunk);
for (const source of sources) {
const id = records.chunks.bySource[source];
if (id === undefined) continue;
if (usedIds.has(id)) continue;
usedIds.add(id);
chunk.id = id;
chunk.ids = [id];
break;
}
}
}
if (Array.isArray(records.chunks.usedIds)) {
compilation.usedChunkIds = new Set(records.chunks.usedIds);
}
}
);
});
}
}
module.exports = RecordIdsPlugin;

34
node_modules/webpack/lib/RequestShortener.js generated vendored Normal file
View file

@ -0,0 +1,34 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { contextify } = require("./util/identifier");
class RequestShortener {
/**
* @param {string} dir the directory
* @param {object=} associatedObjectForCache an object to which the cache will be attached
*/
constructor(dir, associatedObjectForCache) {
this.contextify = contextify.bindContextCache(
dir,
associatedObjectForCache
);
}
/**
* @param {string | undefined | null} request the request to shorten
* @returns {string | undefined | null} the shortened request
*/
shorten(request) {
if (!request) {
return request;
}
return this.contextify(request);
}
}
module.exports = RequestShortener;

84
node_modules/webpack/lib/RequireJsStuffPlugin.js generated vendored Normal file
View file

@ -0,0 +1,84 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC
} = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const ConstDependency = require("./dependencies/ConstDependency");
const {
toConstantDependency
} = require("./javascript/JavascriptParserHelpers");
/** @typedef {import("../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
const PLUGIN_NAME = "RequireJsStuffPlugin";
module.exports = class RequireJsStuffPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(compilation, { normalModuleFactory }) => {
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
/**
* @param {JavascriptParser} parser the parser
* @param {JavascriptParserOptions} parserOptions options
* @returns {void}
*/
const handler = (parser, parserOptions) => {
if (
parserOptions.requireJs === undefined ||
!parserOptions.requireJs
) {
return;
}
parser.hooks.call
.for("require.config")
.tap(PLUGIN_NAME, toConstantDependency(parser, "undefined"));
parser.hooks.call
.for("requirejs.config")
.tap(PLUGIN_NAME, toConstantDependency(parser, "undefined"));
parser.hooks.expression
.for("require.version")
.tap(
PLUGIN_NAME,
toConstantDependency(parser, JSON.stringify("0.0.0"))
);
parser.hooks.expression
.for("requirejs.onError")
.tap(
PLUGIN_NAME,
toConstantDependency(
parser,
RuntimeGlobals.uncaughtErrorHandler,
[RuntimeGlobals.uncaughtErrorHandler]
)
);
};
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_AUTO)
.tap(PLUGIN_NAME, handler);
normalModuleFactory.hooks.parser
.for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
.tap(PLUGIN_NAME, handler);
}
);
}
};

155
node_modules/webpack/lib/ResolverFactory.js generated vendored Normal file
View file

@ -0,0 +1,155 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Factory = require("enhanced-resolve").ResolverFactory;
const { HookMap, SyncHook, SyncWaterfallHook } = require("tapable");
const {
cachedCleverMerge,
removeOperations,
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 */
/** @typedef {WebpackResolveOptions & {dependencyType?: string, resolveToContext?: boolean }} ResolveOptionsWithDependencyType */
/**
* @typedef {object} WithOptions
* @property {function(Partial<ResolveOptionsWithDependencyType>): ResolverWithOptions} withOptions create a resolver with additional/different options
*/
/** @typedef {Resolver & WithOptions} ResolverWithOptions */
// need to be hoisted on module level for caching identity
const EMPTY_RESOLVE_OPTIONS = {};
/**
* @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType enhanced options
* @returns {ResolveOptions} merged options
*/
const convertToResolveOptions = resolveOptionsWithDepType => {
const { dependencyType, plugins, ...remaining } = resolveOptionsWithDepType;
// check type compat
/** @type {Partial<ResolveOptions>} */
const partialOptions = {
...remaining,
plugins:
plugins &&
/** @type {ResolvePluginInstance[]} */ (
plugins.filter(item => item !== "...")
)
};
if (!partialOptions.fileSystem) {
throw new Error(
"fileSystem is missing in resolveOptions, but it's required for enhanced-resolve"
);
}
// These weird types validate that we checked all non-optional properties
const options =
/** @type {Partial<ResolveOptions> & Pick<ResolveOptions, "fileSystem">} */ (
partialOptions
);
return removeOperations(
resolveByProperty(options, "byDependency", dependencyType),
// Keep the `unsafeCache` because it can be a `Proxy`
["unsafeCache"]
);
};
/**
* @typedef {object} ResolverCache
* @property {WeakMap<object, ResolverWithOptions>} direct
* @property {Map<string, ResolverWithOptions>} stringified
*/
module.exports = class ResolverFactory {
constructor() {
this.hooks = Object.freeze({
/** @type {HookMap<SyncWaterfallHook<[ResolveOptionsWithDependencyType]>>} */
resolveOptions: new HookMap(
() => new SyncWaterfallHook(["resolveOptions"])
),
/** @type {HookMap<SyncHook<[Resolver, ResolveOptions, ResolveOptionsWithDependencyType]>>} */
resolver: new HookMap(
() => new SyncHook(["resolver", "resolveOptions", "userResolveOptions"])
)
});
/** @type {Map<string, ResolverCache>} */
this.cache = new Map();
}
/**
* @param {string} type type of resolver
* @param {ResolveOptionsWithDependencyType=} resolveOptions options
* @returns {ResolverWithOptions} the resolver
*/
get(type, resolveOptions = EMPTY_RESOLVE_OPTIONS) {
let typedCaches = this.cache.get(type);
if (!typedCaches) {
typedCaches = {
direct: new WeakMap(),
stringified: new Map()
};
this.cache.set(type, typedCaches);
}
const cachedResolver = typedCaches.direct.get(resolveOptions);
if (cachedResolver) {
return cachedResolver;
}
const ident = JSON.stringify(resolveOptions);
const resolver = typedCaches.stringified.get(ident);
if (resolver) {
typedCaches.direct.set(resolveOptions, resolver);
return resolver;
}
const newResolver = this._create(type, resolveOptions);
typedCaches.direct.set(resolveOptions, newResolver);
typedCaches.stringified.set(ident, newResolver);
return newResolver;
}
/**
* @param {string} type type of resolver
* @param {ResolveOptionsWithDependencyType} resolveOptionsWithDepType options
* @returns {ResolverWithOptions} the resolver
*/
_create(type, resolveOptionsWithDepType) {
/** @type {ResolveOptionsWithDependencyType} */
const originalResolveOptions = { ...resolveOptionsWithDepType };
const resolveOptions = convertToResolveOptions(
this.hooks.resolveOptions.for(type).call(resolveOptionsWithDepType)
);
const resolver = /** @type {ResolverWithOptions} */ (
Factory.createResolver(resolveOptions)
);
if (!resolver) {
throw new Error("No resolver created");
}
/** @type {WeakMap<Partial<ResolveOptionsWithDependencyType>, ResolverWithOptions>} */
const childCache = new WeakMap();
resolver.withOptions = options => {
const cacheEntry = childCache.get(options);
if (cacheEntry !== undefined) return cacheEntry;
const mergedOptions = cachedCleverMerge(originalResolveOptions, options);
const resolver = this.get(type, mergedOptions);
childCache.set(options, resolver);
return resolver;
};
this.hooks.resolver
.for(type)
.call(resolver, resolveOptions, originalResolveOptions);
return resolver;
}
};

1131
node_modules/webpack/lib/RuntimeTemplate.js generated vendored Normal file

File diff suppressed because it is too large Load diff

8
node_modules/webpack/lib/SingleEntryPlugin.js generated vendored Normal file
View file

@ -0,0 +1,8 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sean Larkin @thelarkinn
*/
"use strict";
module.exports = require("./EntryPlugin");

25
node_modules/webpack/lib/SizeFormatHelpers.js generated vendored Normal file
View file

@ -0,0 +1,25 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sean Larkin @thelarkinn
*/
"use strict";
/**
* @param {number} size the size in bytes
* @returns {string} the formatted size
*/
module.exports.formatSize = size => {
if (typeof size !== "number" || Number.isNaN(size) === true) {
return "unknown size";
}
if (size <= 0) {
return "0 bytes";
}
const abbreviations = ["bytes", "KiB", "MiB", "GiB"];
const index = Math.floor(Math.log(size) / Math.log(1024));
return `${Number((size / 1024 ** index).toPrecision(3))} ${abbreviations[index]}`;
};

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